def get_user_by_raw_input(user_data: str or int) -> None or User: """ :param user_data: Use user data rather than username because in real cases, user may login using his phone, or email address. As for efficiency of the user interface, we don't suggest out user to input specific data in specific area, you can enter your ident in just one place. :return: App.Models.User """ if not user_data: return None session = get_session() # 用户名检测 user = session.query(User).filter_by(name=user_data).first() if user is not None: return user # 用户id检测 if isinstance(user_data, int): user = session.query(User).get(user_data) if user: return user # 检测用户手机号 user = session.query(User).filter_by(phone=user_data).first() if user: return user # 检测用户邮箱 user = session.query(User).filter_by(e_mail=user_data).first() if user: return user return None
def _verify(user_type: str): token = request.args.get('token') or request.form.get('token') if not token: abort(401, msg="Not Logged In.") # 验证超级管理员权限 if user_type == TokenPrefix.ADMIN_USER and not token.startswith( TokenPrefix.ADMIN_USER): abort(401, msg="Use Normal Privilege As Admin.") # 验证普通用户权限 if user_type == TokenPrefix.NORMAL_USER and not token.startswith( TokenPrefix.NORMAL_USER): abort(401, msg="Privilege Error.") # 如果两者都可以 if user_type == TokenPrefix.BOTH: if not any( (token.startswith(getattr(TokenPrefix, prefix)) for prefix in dir(TokenPrefix) if not prefix.startswith('__') and not isinstance(getattr(TokenPrefix, prefix), Callable))): abort(401, msg="Invalid token.") # 获取user id 根据token user_id = cache.get(token) if user_id is None: abort(401, msg="Invalid Token.") session = get_session() user_instance = session.query(User).get(user_id) if user_instance is None: abort(401, msg="Invalid ID") g.user = user_instance g.token = token
def post(): session = get_session() args_att = base_parse.parse_args() action = args_att.get('action') method = args_att.get('method') uid = args_att.get('uid') if action is None: abort(400, msg='Method not allowed.') if action == ApiConstant.ATT_ADD: if method == ApiConstant.ATT_ADD_SUP: att = UserAttendanceResource.add_manually(uid=uid) elif method == ApiConstant.ATT_ADD_FRC: att = UserAttendanceResource.add_automatically() elif method == ApiConstant.ATT_ADD_TRA: att = UserAttendanceResource.add_traditionally() else: abort(400, msg='Method not allowed.') return session.add(att) raw_data = db_event_commit(session) msg = 'Success' if raw_data else 'Failed' status = ApiConstant.HTTP_OK if raw_data else ApiConstant.HTTP_FAILED return get_common_marshaled(msg=msg, status=status) elif action == ApiConstant.ATT_DEL: # TODO 删除考勤记录接口 pass else: abort(400, msg='Invalid Action.')
def get(): args_get = get_parse.parse_args() action = args_get.get('action') if action is None: abort(500, msg='Bad request.') return if action == ApiConstant.PRT_AUTH: # 执行 收集令牌发放逻辑 amt = auth_parse.parse_args().get('amt') if amt is None: abort(500, msg='Bad request.') return token = generate_token(TokenPrefix.PORTRAIT_COLLECT) cache.set(token, amt, timeout=ApiConstant.PRT_TOKEN_TIMEOUT) feedback = { 'msg': 'Success', 'status': ApiConstant.HTTP_OK, 'token': token } return marshal(feedback, auth_feedback_fields) elif action == ApiConstant.PRT_GET: args_content = content_get_parse.parse_args() # 在使用argparser后,若不给参数,无法执行到此处 _id = args_content.get('id') limit = args_content.get('length-limit') if not g.user.is_super and g.user.id != _id: abort(401, msg='You can\'t look up other\'s portrait.') # 执行 图片静态地址映射逻辑 session = get_session() if limit is None: prf = session.query(PortraitFileNames).filter_by(staff_id=_id) elif limit <= 0: abort(403, msg='Invalid limit.') return else: prf = session.query(PortraitFileNames).filter_by( staff_id=_id).limit(limit) if prf is None: abort(404, msg='Not Found.') outer_url = urljoin(NGINX_STATIC_PORTRAIT_URL, str(_id)) url_list = [join(outer_url, fn.staff_portrait_md5) for fn in prf] feedback = { 'msg': 'Success', 'status': ApiConstant.HTTP_OK, 'data': url_list } return marshal(feedback, get_feedback_fields) else: abort(500, msg='Bad request.')
def createsuperuser(username, password): if not all([username, password]): print('请提供足够的参数。') return -1 user = User.create_admin(username=username, password=password) session = get_session() session.add(user) admin_register_feedback = db_event_commit(session) if admin_register_feedback: print('Register Successfully.') else: print('Error occurred when write into the database.') return 0
def post(): args_post = post_parse.parse_args() prt_token = args_post.get('prt_token') _id = args_post.get('id') if prt_token is None: abort(401, msg='No Prt Session Token.') if _id is None: abort(401, msg='Invalid id.') data = request.files.get('data') if data is None: abort(500, msg='No data uploaded or received.') # 使用时间戳和id的方式对文件命名 fn = str(time.time()) + str(_id) fn = md5(fn.encode('utf-8')).hexdigest() prefix = os.path.join(PORTRAIT_DIR, str(_id)) if not os.path.exists(prefix): os.mkdir(prefix) pr = PortraitRecords(staff_id=_id, staff_portrait_prefix=prefix) pfn = PortraitFileNames(staff_id=_id, staff_portrait_md5=fn) session = get_session() session.add(pr) session.add(pfn) db_feedback = db_event_commit(session) f_abs_name = os.path.join(prefix, fn) data.save(f_abs_name) # 检测文件是否存在 save_feedback = os.path.exists(f_abs_name) return marshal( { 'msg': 'Success' if save_feedback and db_feedback else 'Failed', 'status': ApiConstant.HTTP_OK if save_feedback and db_feedback else ApiConstant.HTTP_FAILED # TODO get portrait amount. }, post_feedback_fields)
def decorate(*args, **kwargs): # 获取面容token frc_token = request.args.get('frc_token') if frc_token is None: abort(403, msg='Forbidden') return user_id = cache.get(frc_token) if not frc_token.startswith( TokenPrefix.FACE_RECOGNITION_SESSION) or user_id is None: abort(401, msg='Invalid token.') return # 删除frc_token cache.delete(frc_token) # 获取用户实例 session = get_session() user_instance = session.query(User).get(user_id) if user_instance is None: abort(401, msg="Invalid ID") g.user = user_instance # 执行被装饰逻辑 return fun(*args, **kwargs)
def get_user_by_phone(phone: str) -> User or None: session = get_session() return session.query(User).filter_by(phone=phone).first()
def get_user_by_email(email: str) -> User or None: session = get_session() return session.query(User).filter_by(e_mail=email).first()
def get_user_by_name(name: str) -> User or None: session = get_session() return session.query(User).filter_by(name=name).first()
def get(): if g.user is None: abort(401, msg='Please login.') current_user = g.user assert isinstance(current_user, User) current_user_id = g.user.id args_get = get_parse.parse_args() # TODO 增加限定时间范围的查询 # start = args_get.get('start') # end = args_get.get('end') _all = args_get.get('all') _id = args_get.get('id') if _id is not None: # 判断用户id与给定id是否相等 if current_user_id != _id: if not current_user.is_super and not current_user.check_permission('ATTENDANCE_QUERY_ALL'): abort(403, msg='Forbidden') return None # 当前用户是超级管理员或有权限查看全部 # 可以查询当前给定id的内容 session = get_session() results = session.query(User.id, User.name, User.gender, Attendance.check_datetime) \ .join(User, Attendance.staff_id == User.id).filter_by(id=_id) feedback_list = list() result = None for result in results: feedback_list.append(datetime_to_str(result.check_datetime)) feedback_data = { 'msg': 'Success', 'status': ApiConstant.HTTP_OK, 'data': { 'uid': result.id, 'gender': result.gender, 'username': result.name, 'data': feedback_list } } return marshal(feedback_data, multi_att_feedback_fields) elif _all is not None and _all == 1: if current_user.is_super or current_user.check_permission('ATTENDANCE_QUERY_ALL'): # 给返回全部数据 uid_set = set() session = get_session() results = session.query(User.id, User.name, User.gender, Attendance.check_datetime). \ join(User, Attendance.staff_id == User.id) feedback_dict = dict() # for result in results: # print(type(result)) # print(result) # print(str(list(k for k in dir(result) if not k.startswith('__')))) # """ (2, 'steven', datetime.datetime(2020, 7, 2, 10, 52, 33)) ['check_datetime', 'count', 'id', 'index', 'keys', 'name'] 如上连接查询会返回上面的结果,只需要使用result.name, result.id, result.check_datetime即可使用 """ for result in results: if result.id not in uid_set: # 如果不在,则加入用户id uid_set.add(result.id) feedback_dict.setdefault(result.id, init_single_user_dict(result.id, result.name, result.gender)) # 执行添加逻辑 feedback_dict.get(result.id).get('data').append(datetime_to_str(result.check_datetime)) feedback_data = { 'msg': 'Success', 'status': ApiConstant.HTTP_OK, 'data': list(feedback_dict.values()) } return marshal(feedback_data, multi_att_users_feedback_fields) else: abort(403, msg='Forbidden')