def exam_add_member(id,page=1,values=''): form = ExamStudentSearchForm() apply_num = ExamService.get_apply_num_by_id(id) if request.method == 'GET': values_json = {} if values != '': values_json = json.loads(base64.b64decode(values)) pagination = UserService.search_userinfo(values_json,page) return render_template('web/exam_manage/exam_add_member.html', id = id, values = values, form = form, pagination = pagination, user_list = pagination.items, apply_num = apply_num, level = Config.USER_LEVEL, status = Config.STATUS, active = Config.ADMIN_PAGE_ACTIVE['exam']) if form.validate_on_submit(): if form.submit.data: values = base64.b64encode(json.dumps(form.to_dict())) return redirect(url_for('web.exam_add_member', id=id, page=1, values=values)) elif form.submit_add.data: user_filter_list = UserService.search_userinfo_nopage(form.to_dict()) #按条件批量获取用户id,并添加 ExamService.add_exam_member_by_list(id,user_filter_list) return redirect(url_for('web.exam_add_member', id=id, page=page)) else : return redirect(url_for('web.exam_add_member',id=id,page=page))
def confirm_email(token): success = 'You have replaced your password successfully!' failed = 'The confirmation link is invalid or has expired.' url_f = url_for('web.getback') url_s = url_for('web.login') form = ReplacePasswdForm() try: email = verify_email_token(token) if email is None: return render_template("web/failed.html", failed=failed, url=url_f) except: return render_template("web/falied.html", failed=failed, url=url_f) if request.method == 'GET': return render_template('web/auth/update_password.html', form=form) if form.validate_on_submit(): password = form.password.data password_again = form.password_again.data try: user = UserService.get_userinfo_by_email(email['email']) user.password = password_again UserService.update_userpasswd_by_confirm(user) flash(u"您的密码已经成功更新,请登录") return redirect(url_for('web.logout')) except: flash(u"您的密码更新失败,请重试") return redirect(url_for('web.confirm_email', token=token)) return render_template('web/auth/update_password.html', form=form)
def user_get(user_id): service = UserService(db) user = service.get(user_id) if user: return jsonify(user.json(verbose=True)) else: abort(404)
def user_post(): service = UserService(db) user = service.add(request.json) if user: return jsonify(user.json()) else: raise BadRequest()
def show_exam(id): if request.method == 'GET': user_info = {} if current_user.user_level > 1: condition = ExamConditionService.get_user_exam_condition_by_examid( id) for con in condition: user_info[con.sutdent_id] = UserService.get_userinfo_by_id( con.sutdent_id) condition = zip(condition, range(1, len(condition) + 1)) return render_template('web/exam/look_exam.html', condition=condition, user_info=user_info, current_user=current_user) elif current_user.user_level == 1: user_info_dict = {} condition_list = [] condition = ExamConditionService.get_user_exam_condition_by_userid( id, current_user.user_id) user_info = UserService.get_userinfo_by_id(current_user.user_id) user_info_dict[condition.student_id] = user_info condition_list.append(condition) condition_list = zip(condition_list, range(1, len(condition_list) + 1)) return render_template('web/exam/look_exam.html', condition=condition_list, user_info=user_info_dict, current_user=current_user)
def login(): req = request.get_json() user_service = UserService(req) login = user_service.login() if login.status_code == 200: access_token = create_access_token(identity=req["username"]) return dict(message=f"Logged in as {req['username']}", access_token=access_token) return login
def load_user(): token = request.headers.get('token') #用来校验令牌是否有效 user = UserService.get_user_by_token(token) form = LoadUserForm() # 第几页 current_page = form.currentPage.data # 用户名模糊查询 name = form.userName.data # 角色模糊查询 role_id = form.roleId.data return Utils.resp_success( UserService.find_user_by_name_role_page(name, role_id, current_page))
def get_token(): # get_json(self,force=False,silent=False,cache=True):作为json解析并返回数据, # 如果MIME类型不是json,返回None(除非force设为True); # 解析出错则抛出Werkzeug提供的BadRequest异常(如果未开启调试模式,则返回400错误响应), # 如果silent设为True则返回None;cache设置是否缓存解析后的json数据 data = request.get_json(silent=True) if data and "username" in data: user_name = data["username"] else: user_name = None if data and "password" in data: password = data["password"] else: password = None identity = UserService.verify(user_name, password) # Token expiration = current_app.config['TOKEN_EXPIRATION'] print('wecharType:', ClientTypeEnum.WECHAR.value) token = generate_auth_token(identity['uid'], ClientTypeEnum.WECHAR.value, identity['scope']) print('original-token:', token) print('create-token:', token.decode('ascii')) json_result["data"]["token"] = token.decode('ascii') print('json_result:', json_result) return jsonify(json_result)
def create_user(): data = request.get_json(silent=True) if data and "username" in data: user_name = data["username"] else: user_name = None if data and "password" in data: password = str(data["password"]) else: password = None print("username:%s, password:%s" % (user_name, password)) UserService.register(user_name, password) return jsonify(json_result)
def get_user_info(): current_user = g.current_user print('current_uid:', current_user.uid) user = UserService.get_user_info(g.current_user.uid) user = user.hide("login_pwd") json_result["data"] = user return jsonify(json_result)
def getback(): form = GetbackPwdForm() if request.method == 'GET': return render_template('web/auth/forgotpwd.html', form=form) if form.validate_on_submit(): username = form.username.data email = form.email.data user = UserService.get_userinfo_by_email(email) if user is None or username != user.user_name: flash(u'您的用户名和邮箱不匹配,请确认后重新输入') return redirect(url_for('web.getback')) token = generate_email_token(email) confirm_url = url_for('web.confirm_email', token=token, external=True) html = 'Please click url to finishing confirm. After, you can replace your password.<br>' + confirm_url sender = '*****@*****.**' subject = 'OnlineTest Confirm Email' try: send_email(subject, sender, email, html) flash('Your confirm email send successful! :)', 'success') except: flash('Your confirm email send failed :(', 'danger') return redirect(url_for('web.getback')) return render_template('web/auth/forgotpwd.html', form=form)
def tum_kullanicilar(): return jsonify([{ 'id': user.id, 'username': user.username, 'email': user.email, 'registered_on': user.registered_on, 'admin': user.admin } for user in UserService.tum_kullanicilar()])
def validate_nickname(form, field): pattern = re.compile(r'^[0-9a-zA-Z_\u4E00-\u9FA5]{3,24}$') #组成合法性 if not pattern.match(field.data): raise ValidationError('Nickname input is illegal') #查重 if UserService.nickname_is_exist(field.data): raise ValidationError('Nickname already registered')
def register(): form = RegisterForm() if current_user.is_authenticated: return render_template('web/index.html') if request.method == 'GET': return render_template('web/auth/register.html', form=form) if form.validate_on_submit(): try: UserService.register_user(form) except Exception, e: print e flash('regist failed') return render_template('web/auth/register.html', form=form) flash('regist success ! please login :)') return redirect(url_for('web.login'))
def validate_username_reg(form, field): pattern = re.compile(r'^[0-9a-zA-Z_]{2,15}$') #组成合法性 if not pattern.match(field.data): raise ValidationError('Username input is illegal') #查重 if UserService.username_is_exist(field.data): raise ValidationError('Username already registered')
def delete_user(id): token = request.headers.get('token') #用来校验令牌是否有效 user = UserService.get_user_by_token(token) user = User.get_by_id(id) if user.name == 'admin': return Utils.resp_failure('admin不允许删除') user.delete_instance() return Utils.resp_success()
def load_user(id): if id is None: redirect(url_for('web.login')) userinfo = UserService.get_userinfo_by_id(id) user = UserLog(userinfo.user_id, userinfo.user_name, userinfo.level) if user.is_active: return user else: return None
def new_role(): token = request.headers.get('token') #用来校验令牌是否有效 UserService.get_user_by_token(token) form = NewRoleForm() form.validate_for_api() name = form.name.data # 判断名是否重复 role = Role.get_or_none(Role.name == name) if role is not None: return Utils.resp_failure('角色名' + name + '已存在') role = Role() role.name = name role.create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) role.update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) role.save() return Utils.resp_success(role)
def left(): #用来校验令牌是否有效 user = UserService.get_user_by_token(request.headers.get('token')) # 根据角色ID获取对应的权限列表 role_items = RoleItem.select().where(RoleItem.role_id == user.role_id) # 根据菜单ID查出所有的菜单详情 items = [] for roleItem in role_items: item = Item.get_by_id(roleItem.item_id) items.append(item) return Utils.resp_success(items)
def update_info(): form = AuthUpdateForm() if request.method == 'GET': userinfo = UserService.get_userinfo_by_id(current_user.user_id) form.nickname.data = userinfo.nick_name form.email.data = userinfo.email form.college.data = userinfo.college_name form.major.data = userinfo.major_name form.grade.data = userinfo.grade form.classnum.data = userinfo.classnum return render_template('web/auth/update_info.html', form=form) if form.validate_on_submit(): try: UserService.update_userinfo_auth(form, current_user.user_id) flash('Update Success') except: flash('Update Failed') return render_template('web/auth/update_info.html', form=form)
def tek_kullanici(k_id): status = HTTPStatus.OK.real try: auth_token = request.headers.get('Authorization') user = UserService.tek_kullanici(k_id, auth_token) response = { 'id': user.id, 'email': user.email, 'registered_on': user.registered_on, 'admin': user.admin } except Exception as e: response = {'Hata': str(e)} status = getStatus(e) return response, status
def login(): form = LoginForm() if session.has_key('user_id') and session['user_id']: return redirect(url_for('web.index')) if request.method == 'GET': return render_template('web/auth/login.html', form=form) if form.validate_on_submit(): username = form.username.data password = form.password.data userinfo = UserService.get_userinfo_by_uname(username) if userinfo: user = UserLog(userinfo.user_id, userinfo.user_name, userinfo.level) if user and userinfo.status \ and UserService.check_password(userinfo.password, password): login_user(user) return redirect(url_for('web.index')) else: flash(u'您的用户名或密码错误') else: flash(u'您的用户名或密码错误') return render_template('web/auth/login.html', form=form)
def add_exam_member_single(id,user_id,page=1,values=''): try: if UserService.get_userinfo_by_id(user_id).status: ExamService.add_exam_member_single(id,user_id) ExamConditionService.add_user_exam_condition(id, user_id) flash('success') else: flash('failed') except: flash('failed') if values == '': return redirect(url_for('web.exam_add_member', id=id, page=page)) return redirect(url_for('web.exam_add_member',id=id,page=page,values=values))
def exam_member(id): form = ExamStudentSearchForm() apply_num = ExamService.get_apply_num_by_id(id) member_list = [] for student in apply_num: member_list.append(UserService.get_userinfo_by_id(student)) if request.method == 'GET': return render_template('admin/exam/exam_member.html', id = id, form = form, member_list = member_list, status=Config.STATUS, active=Config.ADMIN_PAGE_ACTIVE['exam']) #对当前页面中用户进行筛选 filter = [] if form.validate_on_submit(): if form.username.data: username = re.compile('.*'+form.username.data+'.*') if form.nickname.data: nickname = re.compile('.*'+form.nickname.data+'.*') if form.college.data: college = re.compile('.*'+form.college.data+'.*') if form.major.data: major = re.compile('.*'+form.major.data+'.*') for item in member_list: if username and username.search(item.user_name): filter.append(item) continue if nickname and nickname.search(item.nick_name): filter.append(item) continue if college and college.search(item.college_name): filter.append(item) continue if major and major.search(item.major_name): filter.append(item) continue if item.grade == form.grade.data or item.classnum == form.classnum.data: filter.append(item) continue return render_template('admin/exam/exam_member.html', id=id, form=form, member_list=filter, active=Config.ADMIN_PAGE_ACTIVE['exam'])
def edit_user(): token = request.headers.get('token') #用来校验令牌是否有效 user = UserService.get_user_by_token(token) form = EditUserForm() form.validate_for_api() id = form.id.data pwd = form.pwd.data role_id = form.role_id.data user = User.get_by_id(id) if pwd != '': user.pwd = hashlib.md5(pwd.encode(encoding='UTF-8')).hexdigest() user.role_id = role_id user.update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) user.save() return Utils.show_alert('保存成功', '/go_edit_user/' + str(id))
def create_user(): """ 创建用户 --- tags: - 用户 parameters: - name: username in: formData type: string required: true - name: fullname in: formData type: string required: true - name: email in: formData type: string required: true - name: password in: formData type: string required: true - name: project_limits in: formData type: integer required: false - name: admin in: formData type: integer required: false responses: 200: description: 用户 schema: $ref: '#/definitions/User' 400: description: 创建失败,参数错误 500: description: 创建失败,服务器错误 """ return UserService(request).validate().save()
def new_user(): token = request.headers.get('token') #用来校验令牌是否有效 user = UserService.get_user_by_token(token) form = NewUserForm() form.validate_for_api() name = form.name.data pwd = form.pwd.data role_id = form.roleId.data # 判断用户名是否重复 user = User.get_or_none(User.name == name) if user is not None: return Utils.resp_failure('用户名' + name + '已存在') user = User() user.name = name user.role_id = role_id user.pwd = hashlib.md5(pwd.encode(encoding='UTF-8')).hexdigest() user.enabled = 1 user.create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) user.update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) user.save() return Utils.resp_success(user)
def user_info(): if request.method == 'GET': userinfo = UserService.get_userinfo_by_id(current_user.user_id) return render_template('web/auth/info.html', user_info=userinfo)
def validate_email(form, field): if UserService.email_is_exist(field.data): raise ValidationError('Email already binded')
from app.validator import User from app.utils import encrypt_password from app.service import UserService if __name__ == "__main__": __user_service = UserService() user = {} user[User.FIRST_NAME] = 'kumar' user[User.LAST_NAME] = 'mrigendra' user[User.USER_NAME] = 'kumar' user[User.PASSWORD] = encrypt_password("1234") user[User.INTEREST] = ["Internet", "Science", "Music", "Logic"] __user_service.db().save(user) print "User created successfully"
def delete_users(): return UserService(request).delete_users()