def getGroup(request=None): uid = auth.current_user(request) if uid is not None: page = request.args.get("page", None) or 1 results_per_page = request.args.get("results_per_page", 50) offset = (int(page) - 1) * int(results_per_page) filters = ujson.loads(request.args.get("q")).get("filters", {}).get("$or", []) search_args = [] if (len(filters) != 0): for filter in filters: for key, value in filter.items(): search_args.append( getattr(Group, key).ilike('%%%s%%' % value.get("$like"))) list_groups = db.session.query(Group.id,Group.group_name,Group.description)\ .filter(Group.deleted == False, Group.parent_id == None, or_(*search_args))\ .limit(results_per_page).offset(offset).all() result = format_list_group(list_groups, uid) return json({ "num_results": len(result), "objects": result, "page": page }) else: return json( { "error_code": "USER_NOT_FOUND", "error_message": "USER_NOT_FOUND" }, status=520)
async def set_notify_token(request): data = request.json if data is None: return json( { 'error_code': 'PARAMS_ERROR', 'error_message': 'PARAMS_ERROR' }, status=520) firebase_access_token = request.headers.get('UPSTART-FIREBASE-KEY', None) # CHECK REQUEST ACCESS PERMISSION if firebase_access_token != Config.UPSTART_FIREBASE_KEY: return json( { 'error_code': 'AUTH_ERROR', 'error_message': 'Authentication Error' }, status=523) app = data.get("app", None) device_id = data.get("device_id", None) token = data.get("token", None) if app is None or app not in Config.ALLOWED_APPS: return json( { 'error_code': 'APP PERMISSION DENIED', 'error_message': 'Authentication App Error' }, status=520) notify_redisdb.set(app + "_" + str(device_id), token) return json({'ok': True}, status=200)
def getGroup(request=None): uid = auth.current_user(request) if uid is not None: page = request.args.get("page", None) or 1 results_per_page = request.args.get("results_per_page", None) or 50 offset = (int(page) - 1) * int(results_per_page) list_groups = db.session.query(Group.id,Group.group_name,Group.description)\ .join(GroupsUsers)\ .filter(GroupsUsers.user_id == uid,Group.deleted == False)\ .order_by(GroupsUsers.created_at.desc()).limit(results_per_page).offset(offset).all() result = format_list_group(list_groups, uid) return json({ "num_results": len(result), "objects": result, "page": page }) else: return json( { "error_code": "USER_NOT_FOUND", "error_message": "USER_NOT_FOUND" }, status=520)
def checkContactHasBeenAccount(request=None): uid = auth.current_user(request) if uid is not None: data = request.json list_contact = data.get('contacts', []) group = data.get('group', {}) # print(group) list_contact_convert = convertListContact(list_contact) list_phone = [] for contact in list_contact_convert: list_phone.append(contact['phone']) users_match = db.session.query(User).filter( User.phone.in_(list_phone)).all() # print(users_match) response = [] for contact in list_contact_convert: contact['is_member'] = False for user in users_match: if (user.phone == contact['phone']): contact['display_name_server'] = user.display_name contact['is_member'] = checkUserIsMember(user, group) contact['id'] = str(user.id) # print(contact) response.append(contact) return json(response) else: return json( { "error_code": "USER_NOT_FOUND", "error_message": "USER_NOT_FOUND" }, status=520)
async def user_current_user(request): user_id = auth.current_user(request) print(user_id) user = User.query.filter(User.id == user_id).first() if user is not None: print(user.roles[0]) return json({ "id": user.id, "user_name": user.user_name, "full_name": user.full_name, "employee_id": user.employee_id, "role": user.roles[0].role_name }) else: return json( { "error_code": "NOT_FOUND", "error_message": "User not found" }, status=520) return json({ "error_code": "UNKNOWN", "error_message": "Unknown error" }, status=520)
def join_to_group(request=None): uid = auth.current_user(request) if uid is not None: data = request.json group_id = data.get('group_id') user_id = data.get('user_id') check_is_member = db.session.query(GroupsUsers.id).filter( GroupsUsers.group_id == group_id, GroupsUsers.user_id == user_id).first() if check_is_member is None: id_role_member = db.session.query( Role.id).filter(Role.role_name == 'member').first() new_relation = GroupsUsers(user_id=user_id, group_id=group_id, role_id=id_role_member) db.session.add(new_relation) db.session.commit() group_after_join = db.session.query(Group.id,Group.group_name,Group.description)\ .filter(Group.id == group_id, Group.deleted == False).first() group_after_join = format_list_group([group_after_join], uid) return json(group_after_join[0], status=201) else: return json({}, status=500) else: return json( { "error_code": "USER_NOT_FOUND", "error_message": "USER_NOT_FOUND" }, status=520)
async def get_contact_by_tags(request): verify_access(request) current_tenant = get_current_tenant(request) if current_tenant is None or 'error_code' in current_tenant: return json({ 'error_code': 'TENANT_UNKNOWN', 'error_message': 'Thông tin request không xác định' }, status=523) tenant_id = current_tenant.get('id') body_data = request.json if body_data is None or isinstance(body_data, list) == False or len(body_data) == 0: return json({ 'error_code': 'BODY_DATA_ERROR', 'error_message': 'Dữ liệu không đúng định dạng' }, status=520) tags_ids = [_.get('id') for _ in body_data] contact_tags_details = db.session.query(ContactTagsDetails.contact_id,\ func.count(ContactTagsDetails.id)).filter(and_(ContactTagsDetails.tenant_id == tenant_id,\ ContactTagsDetails.contact_tags_id.in_(tags_ids))).group_by(ContactTagsDetails.contact_id).all() results = [] if contact_tags_details is not None and isinstance(contact_tags_details, list): for tag_detail in contact_tags_details: if tag_detail[1] == len(tags_ids): results.append(str(tag_detail[0])) return json(results)
async def luucacbuoc(request): data = request.json print("---------------------buoc kiem tra-------------------", data['step']) print("---------------------equipmentinspectionform_id-------------------", data['equipmentinspectionform_id']) buoc = data['step'] idbangkiemtra = data['equipmentinspectionform_id'] step = db.session.query(Step).filter( and_(Step.equipmentinspectionform_id == idbangkiemtra, Step.step == buoc)).first() print("---------------------to_dict(step)-------------------", to_dict(step)) if step is not None: step.note = data["note"] step.status = data["status"] step.time = data["time"] step.picture = data["picture"] db.session.commit() return json(to_dict(step)) else: new_buockiemtra = Step() new_buockiemtra.note = data["note"] new_buockiemtra.step = data["step"] new_buockiemtra.status = data["status"] new_buockiemtra.picture = data["picture"] new_buockiemtra.time = data["time"] new_buockiemtra.equipmentinspectionform_id = data[ "equipmentinspectionform_id"] db.session.add(new_buockiemtra) db.session.commit() return json(to_dict(new_buockiemtra))
def register(request): data = request.json print("===================", data) user = db.session.query(User).filter( or_(User.email == data["email"], User.phone_number == data["phone_number"])).first() if user is not None: return json( { "error_code": "USER_EXISTED", "error_message": "Email hoặc phone đã tồn tại" }, status=520) else: new_user = User() new_user.name = data["name"] new_user.email = data["email"] new_user.phone_number = data["phone_number"] # new_user.user_image = data["user_image"] new_user.password = auth.encrypt_password(data["password"]) new_user.rank = data["rank"] db.session.add(new_user) db.session.commit() result = user_to_dict(new_user) return json(result)
async def save_config(request): data = request.json # try: if data is None: return json( { "error_code": ERROR_CODE['NULL_ERROR'], "error_message": ERROR_MSG['NULL_ERROR'] }, status=STATUS_CODE['ERROR']) config = Configuration.query.filter().first() if config is None: config = Configuration() if config is not None and (config.app_key is None\ or ('app_key' is data and data['app_key'] is not None and config.app_key == data['app_key'])): if config.app_key is None and 'app_key' in data and data[ 'app_key'] is not None: config.app_key = data['app_key'] if 'app_secret' in data and data['app_secret'] is not None: config.app_secret = data['app_secret'] if 'category' in data and data['category'] is not None: config.category = data['category'] if 'token' in data and data['token'] is not None: config.token = data['token'] if 'data' in data: config.data = data['data'] db.session.add(config) db.session.commit() return json({"message": "success"}, status=STATUS_CODE['OK'])
async def reset_password(request): if request.method == 'GET': token = request.args.get("token", None) static_url = app.config.get("DOMAIN_URL")+"/"+app.config.get("STATIC_URL", "") return jinja.render('email/reset_password.html', request, static_url = static_url, token=token) if request.method == 'POST': token = request.form.get("token", None) password = request.form.get("password", None) confirm_password = request.form.get("confirm_password", None) if token is None or password is None: return json({"error_code": "PARAM_ERROR", "error_message": "Invalid value, please check again"}, status=520) uid_current = redisdb.get("sessions:" + token) if uid_current is None: return json({"error_code": "SESSION_EXPIRED", "error_message": "Timeout to change password, please select again"}, status=520) redisdb.delete("sessions:" + token) user = User.query.filter(User.id == str(uid_current.decode('ascii'))).first() if (user is not None): user.password = auth.encrypt_password(password) auth.login_user(request, user) db.session.commit() return text(u'Password change was successful.') else: return text('User account not found, please select again!')
async def write_file(file, fileId, attrs, uid_current): url = app.config['FILE_SERVICE_URL'] fsroot = app.config['FS_ROOT_FILE'] if not os.path.exists(fsroot): os.makedirs(fsroot) file_name = os.path.splitext(file.name)[0] extname = os.path.splitext(file.name)[1] BLOCKSIZE = 65536 sha256 = hashlib.sha256() file_data = file.body data_length = len(file_data) if (data_length <= 0): return json( { "error_code": "Error", "error_message": "File không hợp lệ" }, status=520) elif (data_length < BLOCKSIZE): BLOCKSIZE = data_length # f = file.body.open('rb') # if f.multiple_chunks(): # for chunk in f.chunks(): # sha256.update(chunk) # else: # sha256.update(f.read()) # f.close() sha256.update(file_data) # file_buffer = file_data.read(BLOCKSIZE) # while len(file_buffer) > 0: # sha256.update(file_buffer) # file_buffer = file_data.read(BLOCKSIZE) str_sha256 = sha256.hexdigest() check_exist = db.session.query(FileInfo).filter( FileInfo.sha256 == str_sha256).first() if check_exist is not None: return json(to_dict(check_exist)) async with aiofiles.open(fsroot + str_sha256 + extname, 'wb+') as f: await f.write(file.body) f.close() if fileId is None: fileId = str(uuid.uuid4()) fileInfo = FileInfo() fileInfo.id = fileId fileInfo.sha256 = str_sha256 fileInfo.user_id = uid_current fileInfo.name = file_name fileInfo.extname = extname fileInfo.link = str(url) + "/" + str(str_sha256) + str(extname) fileInfo.attrs = attrs fileInfo.size = data_length fileInfo.kind = "normal" db.session.add(fileInfo) db.session.commit() return json(to_dict(fileInfo), status=200)
async def upload_file(request): ret = None uid_current = current_uid(request) if uid_current is None: return json( { "error_code": "SESSION_EXPIRED", "error_message": "Hết phiên làm việc, vui lòng đăng nhập lại" }, status=520) if request.method == 'POST': # try: fileId = request.headers.get("fileId", None) file_data = request.files.get('file', None) attrs = request.form.get('attrs', None) print(attrs) if file_data: response = await write_file(file_data, fileId, attrs, uid_current) return response # except Exception as e: # raise e return json( { "error_code": "Upload Error", "error_message": "Could not upload file to store" }, status=520)
async def upload_file(request): url = app.config['FILE_SERVICE_URL'] fsroot = app.config['FS_ROOT'] print('____________fsroot________________', fsroot) if request.method == 'POST': file = request.files.get('file', None) if file: rand = ''.join(random.choice(string.digits) for _ in range(15)) file_name = os.path.splitext(file.name)[0] extname = os.path.splitext(file.name)[1] newfilename = file_name + "-" + rand + extname new_filename = newfilename.replace(" ", "_") async with aiofiles.open(fsroot + new_filename, 'wb+') as f: await f.write(file.body) return json( { "error_code": "OK", "error_message": "successful", "id": rand, "link": url + "/" + new_filename, "filename": newfilename, "filename_organization": file_name, "extname": extname }, status=200) return json( { "error_code": "Upload Error", "error_message": "Could not upload file to store" }, status=520)
def addMembers(request=None, group_id=None): uid = auth.current_user(request) if uid is not None: data = request.json id_role_member = db.session.query( Role.id).filter(Role.role_name == "member").first() for member in data['members']: if member.get('id', None) is None: new_user = createUser(member) db.session.add(new_user) db.session.flush() new_relation = GroupsUsers(user_id=new_user.id, group_id=data['group_id'], role_id=id_role_member) db.session.add(new_relation) db.session.commit() else: new_relation = GroupsUsers(user_id=member['id'], group_id=data['group_id'], role_id=id_role_member) db.session.add(new_relation) db.session.commit() return json({}, status=201) else: return json( { "error_code": "USER_NOT_FOUND", "error_message": "USER_NOT_FOUND" }, status=520)
async def reset_password(request): if request.method == 'GET': token = request.args.get("token", None) static_url = app.config.get("DOMAIN_URL")+"/"+app.config.get("STATIC_URL", "") return jinja.render('email/reset_password.html', request, static_url = static_url, token=token) if request.method == 'POST': token = request.form.get("token", None) password = request.form.get("password", None) confirm_password = request.form.get("confirm_password", None) if token is None or password is None: return json({"error_code": "PARAM_ERROR", "error_message": "Tham số không hợp lệ, vui lòng thực hiện lại"}, status=520) uid_current = redisdb.get("sessions:" + token) if uid_current is None: return json({"error_code": "SESSION_EXPIRED", "error_message": "Hết thời gian thay đổi mật khẩu, vui lòng thực hiện lại"}, status=520) redisdb.delete("sessions:" + token) user = User.query.filter(User.id == str(uid_current.decode('ascii'))).first() if (user is not None): user.password = auth.encrypt_password(password) auth.login_user(request, user) db.session.commit() return text(u'bạn đã lấy lại mật khẩu thành công. mời bạn đăng nhập lại để sử dụng!') else: return text('Không tìm thấy tài khoản trong hệ thống, vui lòng thử lại sau!')
async def cancel_kehoach(request): makehoach = request.json.get("id", None) currentUser = await current_user(request) if (currentUser is None): return json({"error_code":"SESSION_EXPIRED","error_message":"End of session, please log in again!"}, status=520) if (makehoach is None or makehoach == ""): return json({"error_code":"ERROR_PARAMS","error_message":"Invalid value, please check again"}, status=520) kehoach = db.session.query(KeHoachThanhTra).filter(KeHoachThanhTra.id == makehoach).first() if kehoach is not None: if currentUser.has_role("CucTruong"): kehoach.trangthai = KeHoach_ThanhTra_TrangThai["cancel_approved"] elif currentUser.has_role("CucPho"): kehoach.trangthai = KeHoach_ThanhTra_TrangThai["cancel_reviewed_pct"] elif currentUser.has_role("TruongPhong"): kehoach.trangthai = KeHoach_ThanhTra_TrangThai["cancel_reviewed_truongphong"] else: return json({"error_code":"PERMISSION_DENY","error_message":"There is no right to perform this action"}, status=520) db.session.commit() return json(to_dict(kehoach)) else: return json({"error_code":"NOT_FOUND","error_message":"Invalid value, please check again"}, status=520)
async def upload_file(request): url = app.config['FILE_SERVICE_URL'] fsroot = app.config['FS_ROOT'] if request.method == 'POST': data = request.json file = data['files'] if file: encoded = file nameImage = random.randint(100000000000000000000, 999999999999999999999) nameImagedirect = fsroot + str(nameImage) + '.png' print("-----------------Hello World------------------------", nameImagedirect) async with aiofiles.open(nameImagedirect, 'wb+') as f: data2 = base64.b64decode(encoded) await f.write(data2) return json( { "error_code": "OK", "url_img": str(nameImage) + '.png', }, status=200) return json( { "error_code": "Upload Error", "error_message": "Could not upload file to store" }, status=520)
def join_to_group(request=None): uid = auth.current_user(request) if uid is not None: data = request.json group_id = data.get('group_id') user_id = data.get('user_id') relation = db.session.query(GroupsUsers).filter( GroupsUsers.group_id == group_id, GroupsUsers.user_id == user_id).first() if relation is not None: db.session.delete(relation) db.session.commit() group_after_leave = db.session.query(Group.id,Group.group_name,Group.description)\ .filter(Group.id == group_id, Group.deleted == False).first() group_after_leave = format_list_group([group_after_leave], uid) return json(group_after_leave[0], status=201) else: return json({}, status=500) else: return json( { "error_code": "USER_NOT_FOUND", "error_message": "USER_NOT_FOUND" }, status=520)
async def get_room_available(request): current_tenant = get_current_tenant(request) if current_tenant is None or 'error_code' in current_tenant: return json( { 'error_code': 'TENANT_UNKNOWN', 'error_message': 'Thông tin request không xác định' }, status=523) tenant_id = current_tenant.get('id') now_time = now_timestamp() list_room_busy_ids = db.session.query(ContactRoomSession.room_id).filter( ContactRoomSession.end_time >= now_time, ContactRoomSession.checkout == True, ContactRoomSession.tenant_id == tenant_id, ).distinct(ContactRoomSession.room_id).all() rooms_availabel = db.session.query(Room).filter( Room.active == True, ~Room.id.in_(list_room_busy_ids)).all() results = [] for room in rooms_availabel: results.append(to_dict(room)) return json({'results': results}, status=200)
async def user_login(request): param = request.json user_name = param.get("phone") password = param.get("password") # print(param) if (user_name is not None) and (password is not None): user = getUser(user_name) # print(user) if (user is not None) and auth.verify_password(password, user.password, user.salt): auth.login_user(request, user) result = response_userinfo(user) # print('result==========',result) return json(result, status=201) return json( { "error_code": "LOGIN_FAILED", "error_message": "user does not exist or incorrect password" }, status=520) else: return json( { "error_code": "PARAM_ERROR", "error_message": "param error" }, status=520) return text("user_login api")
async def DonVitree(request): currentuser = await current_user(request) if currentuser is None: return json( { "error_code": "SESSION_EXPIRED", "error_message": "Hết phiên hoạt động, vui lòng đăng nhập lại" }, status=520) is_admin = await hasRole(request, "Admin") data = None if (is_admin == True): data = db.session.query(DonVi).\ options(joinedload_all("children", "children", "children", "children")).\ filter(DonVi.id == currentuser.donvi_id).\ first() else: data = db.session.query(DonVi).\ options(joinedload_all("children", "children", "children", "children")).\ join(TuyenDonVi, DonVi.tuyendonvi).filter(TuyenDonVi.ma == 'TW').first() if data is not None: obj = data.dump() return json(to_dict(obj)) else: return json({})
async def import_excel_medicine(request): # data = request.json uid_current = current_uid(request) if uid_current is None: return json( { "error_code": "SESSION_EXPIRED", "error_message": "Hết phiên làm việc, vui lòng đăng nhập lại" }, status=520) fileId = request.headers.get("fileId", None) file_data = request.files.get('file', None) attrs = request.form.get('attrs', None) if file_data: response = await write_file_excel_thuoc(file_data, fileId, attrs, uid_current) print("respone", response) return response return json( { "error_code": "UPLOAD_ERROR", "error_message": "Không thể tải file lên hệ thống" }, status=520)
async def addMembers(request=None, group_id=None): uid = auth.current_user(request) if uid is not None: data = request.json phone = data.get("phone") group_id = data.get("group_id") user_id = db.session.query(User.id).filter( User.phone == phone, User.is_active == True).first() if user_id is not None: id_role_member = db.session.query( Role.id).filter(Role.role_name == "member").first() check_is_member = db.session.query(GroupsUsers.id).filter( GroupsUsers.user_id == user_id, GroupsUsers.group_id == group_id).first() if check_is_member is None: new_relation = GroupsUsers(user_id=user_id, group_id=group_id, role_id=id_role_member) db.session.add(new_relation) db.session.commit() return json({}, status=201) else: return json({"error_message": "Không tìm được số điện thoại này"}, status=520) else: return json( { "error_code": "USER_NOT_FOUND", "error_message": "USER_NOT_FOUND" }, status=520)
def add_item_in_warehouse(request): data = request.json warehouse_id = data["warehouse_id"] if data is None: return json({ "error_code": ERROR_CODE['INPUT_DATA_ERROR'], "error_message": ERROR_MSG['INPUT_DATA_ERROR'] }, status=STATUS_CODE['ERROR']) quantity_reduction = [] for _ in data["items"]: itembalances = db.session.query(ItemBalances).filter(and_(ItemBalances.warehouse_id == warehouse_id, ItemBalances.item_no == _["item_no"])).first() if itembalances is None: return json({"error_code":"ERROR_CODE","error_message":"Hàng hóa không có trong kho"}, status=520) # if itembalances.quantity < _["quantity"]: # return json({"error_code":"ERROR_CODE","error_message":"Số lượng trong kho không đủ"}, status=520) if itembalances.quantity >= _['quantity']: itembalances.quantity -= _["quantity"] if 'quantity' in _ and _["quantity"] is not None else 0 # print("===============================", _) del _['item_image'] quantity_reduction.append(_) db.session.commit() print("========================================", quantity_reduction) return json({ "ok": True, "message": "Hàng hóa: " + str(_['item_name']) + " " + " Đã giảm SL: " + str(_['quantity']) })
def createChecklist(request=None, checklist_id=None): uid = auth.current_user(request) # print(createTaskInfo) if uid is not None: # checklist = request.json checklist = db.session.query(Checklist).filter( Checklist.id == checklist_id).first() response = to_dict(checklist) or {} tasks_info = db.session.query(TaskInfo).filter( TaskInfo.checklist_id == checklist.id, TaskInfo.deleted == False).all() response['tasks_info'] = [] response['groups'] = [] response['shifts'] = [] for group in checklist.groups: response['groups'].append(to_dict(group)) for shift in checklist.shifts: response['shifts'].append(to_dict(shift)) for task_info in tasks_info: task_info_add = {} task_info_add = to_dict(task_info) task_info_add['group'] = to_dict(task_info.group) task_info_add['assignee'] = to_dict(task_info.assignee) response['tasks_info'].append(task_info_add) return json(response, status=200) else: return json( { "error_code": "USER_NOT_FOUND", "error_message": "USER_NOT_FOUND" }, status=520)
async def update_properties(request): verify_access(request) try: data = request.json if data is None or 'id' not in data or data['id'] is None: return json( { "error_code": ERROR_CODE['DATA_FORMAT'], "error_message": ERROR_MSG['DATA_FORMAT'] }, status=STATUS_CODE['ERROR']) contact = User.query.get(data['id']) if contact is not None: for name, value in data.items(): if name != 'id': setattr(contact, name, value) db.session.add(contact) db.session.commit() return json({"message": "success"}) except: return json( { "error_code": ERROR_CODE['EXCEPTION'], "error_message": ERROR_MSG['EXCEPTION'] }, status=STATUS_CODE['ERROR'])
async def set_current_user(request, data, **kw): current_user = auth.current_user(request) if current_user is None: return json( { 'error_code': 'E523', 'error_message': 'Phiên làm việc hết hạn, đăng nhập lại.' }, status=523) uid = current_user['uid'] if uid is None or uid.find(".") <= 0: auth.logout_user(request) return json( { 'error_code': 'E523', 'error_message': 'Phiên làm việc hết hạn, đăng nhập lại.' }, status=523) current_tenant_id = uid.split('.')[0] current_user_id = uid.split('.')[1] user_info = await motordb.db['user'].find_one({ 'tenant_id': current_tenant_id, 'id': str(current_user_id) }) if user_info is not None: data["owner_id"] = str(user_info['_id'])
def login(request): data = request.json if data is None or data.get('txtusername', None) is None or data.get( 'txtpassword', None) is None: return json( { 'error_code': 'AUTH_FAILED', 'error_message': 'Username, password are required' }, status=523) txtUserName = data.get('txtusername', None) txtPassword = data.get('txtpassword', None) # cookies = LoginKMA(txtUserName,txtPassword) if LoginKMA(txtUserName, txtPassword)['SignIn'] is None: return json( { 'error_code': 'AUTH_FAILED', 'error_message': 'Username, password false' }, status=523) if LoginKMA(txtUserName, txtPassword) is not None: AddCookie = Cookie() AddCookie.student_code = txtUserName AddCookie.password = txtPassword AddCookie.cookie = LoginKMA(txtUserName, txtPassword).get("SignIn") #Luu vao db db.session.add(AddCookie) db.session.commit() return json(txtUserName)
async def user_login(request): param = request.json user_name = param.get("user_name") password = param.get("password") print(user_name, password) if (user_name is not None) and (password is not None): user = db.session.query(User).filter( User.user_name == user_name).first() if (user is not None) and auth.verify_password(password, user.password, user.salt): auth.login_user(request, user) return json({ "id": user.id, "user_name": user.user_name, "full_name": user.full_name }) return json( { "error_code": "LOGIN_FAILED", "error_message": "user does not exist or incorrect password" }, status=520) else: return json( { "error_code": "PARAM_ERROR", "error_message": "param error" }, status=520) return text("user_login api")
async def put(self, request, instid=None): content_type = request.headers.get('Content-Type', "") content_is_json = content_type.startswith('application/json') if not content_is_json: msg = 'Request must have "Content-Type: application/json" header' return json(dict(message=msg),status=520) try: data = request.json or {} except (ServerError, TypeError, ValueError, OverflowError) as exception: #current_app.logger.exception(str(exception)) return json(dict(error_code='PARAM_ERROR', error_message='Unable to decode data'),status=520) for preprocess in self.preprocess['PATCH_SINGLE']: try: if asyncio.iscoroutinefunction(preprocess): resp = await preprocess(request=request, instance_id=instid, data=data, collection_name=self.collection_name) else: resp = preprocess(request=request, instance_id=instid, data=data,collection_name=self.collection_name) if (resp is not None) and isinstance(resp, HTTPResponse): return resp # See the note under the preprocess in the get() method. if resp is not None: instid = resp except Exception as exception: return response_exception(exception) result = await self._put(request, data, instid) if result is None: return json(dict(error_code='UNKNOWN_ERROR', error_message=''),status=520) headers = {} try: for postprocess in self.postprocess['PATCH_SINGLE']: if asyncio.iscoroutinefunction(postprocess): resp = await postprocess(request=request, result=result, collection_name=self.collection_name, headers=headers) else: resp = postprocess(request=request, result=result, collection_name=self.collection_name, headers=headers) if (resp is not None) and isinstance(resp, HTTPResponse): return resp except Exception as exception: return response_exception(exception) return json(result, headers=headers, status=200)
async def search(self, request): try: search_params = json_loads(request.args.get('q', '{}')) except (TypeError, ValueError, OverflowError) as exception: #current_app.logger.exception(str(exception)) return json(dict(error_code="PARAM_ERROR", error_message='Unable to decode data'), status=520) try: for preprocess in self.preprocess['GET_MANY']: if asyncio.iscoroutinefunction(preprocess): resp = await preprocess(request=request,search_params=search_params, collection_name=self.collection_name) else: resp = preprocess(request=request,search_params=search_params, collection_name=self.collection_name) if (resp is not None) and isinstance(resp, HTTPResponse): return resp except Exception as exception: return response_exception(exception) result = await self._search(request, search_params) if result is None: return json(dict(error_code="NOT_FOUND", error_message='No result found'), status=520) try: headers = {} for postprocess in self.postprocess['GET_MANY']: if asyncio.iscoroutinefunction(postprocess): resp = await postprocess(request=request, result=result, search_params=search_params, collection_name=self.collection_name, headers=headers) else: resp = postprocess(request=request, result=result, search_params=search_params, collection_name=self.collection_name, headers=headers) if (resp is not None) and isinstance(resp, HTTPResponse): return resp except Exception as exception: return response_exception(exception) return json(result, headers=headers, status=200)
async def delete(self, request, instid=None): try: for preprocess in self.preprocess['DELETE_SINGLE']: if asyncio.iscoroutinefunction(preprocess): resp = await preprocess(request=request, instance_id=instid, collection_name=self.collection_name) else: resp = preprocess(request=request, instance_id=instid, collection_name=self.collection_name) if (resp is not None) and isinstance(resp, HTTPResponse): return resp # See the note under the preprocess in the get() method. if resp is not None: instid = resp except Exception as exception: return response_exception(exception) was_deleted = False if instid is not None: #result = await self.db.db[self.collection_name].delete_one({'_id': {'$eq': ObjectId(instid)}}) result = await self.db.db[self.collection_name].delete_one({'_id': {'$in': [ObjectId(instid), instid]}}) was_deleted = result.deleted_count > 0 try: headers = {} for postprocess in self.postprocess['DELETE_SINGLE']: if asyncio.iscoroutinefunction(postprocess): resp = await postprocess(request=request, was_deleted=was_deleted, collection_name=self.collection_name, headers=headers) else: resp = postprocess(request=request, was_deleted=was_deleted, collection_name=self.collection_name, headers=headers) if (resp is not None) and isinstance(resp, HTTPResponse): return resp except Exception as exception: return response_exception(exception) return json({}, headers=headers, status=200) if was_deleted else json({}, headers=headers, status=520)
async def get(self, request, instid=None): if instid is None: return await self.search(request) try: for preprocess in self.preprocess['GET_SINGLE']: if asyncio.iscoroutinefunction(preprocess): resp = await preprocess(request=request, instance_id=instid, collection_name=self.collection_name) else: resp = preprocess(request=request, instance_id=instid, collection_name=self.collection_name) if (resp is not None) and isinstance(resp, HTTPResponse): return resp if resp is not None: instid = resp except Exception as exception: return response_exception(exception) result = await self._get(request, instid) if result is None: return json(dict(error_code="NOT_FOUND", error_message='No result found'), status=520) try: headers = {} for postprocess in self.postprocess['GET_SINGLE']: if asyncio.iscoroutinefunction(postprocess): resp = await postprocess(request=request, result=result, collection_name=self.collection_name, headers=headers) else: resp = postprocess(request=request, result=result, collection_name=self.collection_name, headers=headers) if (resp is not None) and isinstance(resp, HTTPResponse): return resp except Exception as exception: return response_exception(exception) return json(result, headers=headers, status=200)
def response_exception(exception): if type(exception.message) is dict: return json(exception.message, status=exception.status_code) else: return json({"error_code": "UNKNOWN_ERROR", "error_message": exception.message}, status=520)