def create_email(): """ Create email :return: """ params = { 'email': fields.Email(), 'password': FieldString(), 'recovery_email': fields.Email(), 'date': FieldString() } try: json_data = parse_req(params) new_email = json_data.get('email').strip().lower() except Exception as ex: return send_error(message='Json parser error', code=442) email = client.db.email.find_one({'email': new_email}) if email is not None: return send_error(message='Duplicate email') keys = ('email', 'password', 'recovery_email', 'date') email = dict() for k in keys: v = json_data.get(k, None) if v is not None or v != '': email[k] = v email['create_date'] = int(time.time()) email['status'] = True client.db.email.insert_one(email) return send_result(message='Create email successfully')
def update_user(): """ Update user data :return: """ params = { '_id': FieldString(), 'address': FieldString(), 'phone': FieldString(), 'fullname': FieldString(), 'role': FieldString(), } try: json_data = parse_req(params) _id = json_data.get('_id') except Exception as ex: return send_error(message='Json parser error', code=442) user = client.db.user.find_one({'_id': ObjectId(_id)}) if user is None: return send_error(message='Not found user') keys = ('address', 'phone', 'fullname', 'role') for k in keys: v = json_data.get(k, None) if v is not None or v != '': user[k] = v client.db.user.update({'_id': ObjectId(_id)}, user) return send_result(message='Update user successfully')
def update_multiple(): params = { 'login_failed_attempts': fields.Number(), 'logout_after_inactivate': fields.Number(), 'password_expiration': fields.Number(), 'password_password_min_length': fields.Number(), 'password_min_length': fields.Number(), 'password_include_symbol': fields.Bool(), 'password_include_number': fields.Bool(), 'password_include_lower_case': fields.Bool(), 'password_include_upper_case': fields.Bool(), } try: json_data = parse_req(params) # Check valid params validate(instance=json_data, schema=schema_security_policy) login_failed_attempts = json_data.get('login_failed_attempts', None) logout_after_inactivate = json_data.get('logout_after_inactivate', None) password_expiration = json_data.get('password_expiration', None) password_min_length = json_data.get('password_min_length', None) password_include_symbol = json_data.get('password_include_symbol', None) password_include_number = json_data.get('password_include_number', None) password_include_lower_case = json_data.get('password_include_lower_case', None) password_include_upper_case = json_data.get('password_include_upper_case', None) except Exception as ex: return send_error(message=str(ex)) modified_by = get_jwt_identity() modified_date = get_datetime_now_s() try: db.session.query(SecurityPolicy).update( {SecurityPolicy.login_failed_attempts: login_failed_attempts, SecurityPolicy.logout_after_inactivate: logout_after_inactivate, SecurityPolicy.password_expiration: password_expiration, SecurityPolicy.password_min_length: password_min_length, SecurityPolicy.password_include_symbol: password_include_symbol, SecurityPolicy.password_include_number: password_include_number, SecurityPolicy.password_include_lower_case: password_include_lower_case, SecurityPolicy.password_include_upper_case: password_include_upper_case, SecurityPolicy.modified_by: modified_by, SecurityPolicy.modified_date: modified_date}, synchronize_session=False) db.session.commit() except Exception as ex: return send_error(message=str(ex)) data = { 'login_failed_attempts': login_failed_attempts, 'logout_after_inactivate': logout_after_inactivate, 'password_expiration': password_expiration, 'password_min_length': password_min_length, 'password_include_symbol': password_include_symbol, 'password_include_number': password_include_number, 'password_include_lower_case': password_include_lower_case, 'password_include_upper_case': password_include_upper_case, } return send_result(data=data, message="Update security policy successfully!")
def update_password(): """ Update user password :return: """ params = { '_id': FieldString(), 'password': FieldString(), } try: json_data = parse_req(params) _id = json_data.get('_id') except Exception as ex: return send_error(message='Json parser error', code=442) user = client.db.user.find_one({'_id': ObjectId(_id)}) if user is None: return send_error(message='Không tìm thấy người dùng, tải lại trang.') if user['username'] != 'Administrator': return send_error( message='Bạn không thể đổi mật khẩu, chỉ admin mới có quyền đổi.') client.db.user.update({'_id': ObjectId(_id)}, user) return send_result(message='Thay đổi mật khẩu thành công.')
def update_channel(): """ Update email data :return: """ params = { '_id': FieldString(), 'name': FieldString(), 'channel': FieldString(), 'strategy': FieldString(), 'status': FieldString(), } try: json_data = parse_req(params) _id = json_data.get('_id') except Exception as ex: return send_error(message='Json parser error', code=442) channel = client.db.channel.find_one({'_id': ObjectId(_id)}) if channel is None: return send_error(message='Not found') keys = ('name', 'channel', 'strategy', 'status') for k in keys: v = json_data.get(k, None) if v is not None or v != '': channel[k] = v client.db.channel.update({'_id': ObjectId(_id)}, channel) return send_result(message='Cập nhật kênh thành công.')
def post(): params = { 'name': FieldString(requirement=True), 'descriptions': FieldString() } try: json_data = parse_req(params) # Check regex params validate(instance=json_data, schema=schema_permission) name = json_data.get('name', None) descriptions = json_data.get('descriptions', None) except Exception as ex: return send_error(message="Parameters error:" + str(ex)) row = PermissionDetail.query.filter_by(name=name).first() if row is not None: return send_error(message='The permission name has existed!') create_date = get_datetime_now_s() _id = str(uuid.uuid1()) new_values = PermissionDetail(id=_id, descriptions=descriptions, name=name, create_date=create_date) try: db.session.add(new_values) db.session.commit() except Exception as ex: return send_error(message=str(ex)) return send_result(message="Create permission successfully!")
def check_answer(): """ check answer url: /api/questions :return: data answer """ params = {'answer': fields.List(fields.Dict())} try: json_data = parse_req(params) data = json_data.get('answer') except Exception as ex: return send_error(message='{}'.format(str(ex)), code=442) try: list_data = [] conn = sqlite3.connect('./test.db') conn.row_factory = lambda c, r: dict( zip([col[0] for col in c.description], r)) c = conn.execute('SELECT qa.id, qa.answer FROM qa;') list_answer = c.fetchall() for item in list_answer: a = False for dic in data: if dic['id'] == item['id']: if dic['value'] == int(item['answer']): a = True break list_data.append({'id': item['id'], 'answer': a}) except Exception as e: return send_error(message='DB error') finally: conn.close() return send_result(data=list_data)
def update_info(): """ This is api for all user edit their profile. Request Body: Returns: Examples:: """ try: json_data = request.get_json() # Check valid params validate(instance=json_data, schema=user_validator) except Exception as ex: return send_error(message=str(ex)) keys = ["name", "gender", "phone", "email"] data = {} for key in keys: if key in json_data: data[key] = json_data.get(key) new_values = { "$set": data } try: client.db.users.update_many({"_id": get_jwt_identity()}, new_values) except Exception as ex: return send_error(message="Database error: " + str(ex)) return send_result(data=data, message="Update user successfully!")
def post(): params = {'name': FieldString(requirement=True)} try: json_data = parse_req(params) # Check valid params validate(instance=json_data, schema=schema_group) name = json_data.get('name', None) except Exception as ex: return send_error(message="Parameters error:" + str(ex)) row = Group.query.filter_by(name=name).first() if row is not None: return send_error(message='The group name has existed!') create_date = get_datetime_now_s() _id = str(uuid.uuid1()) new_group = Group(id=_id, name=name, create_date=create_date) try: db.session.add(new_group) db.session.commit() except Exception as ex: return send_error(message=str(ex)) data = {'name': name} return send_result(data=data, message="Create the group successfully!")
def update_strategy(): """ Update email data :return: """ params = { '_id': FieldString(), 'name': FieldString(), 'issue': FieldString(), 'sub_issue': FieldString(), 'note': FieldString() } try: json_data = parse_req(params) _id = json_data.get('_id') except Exception as ex: return send_error(message='Json parser error', code=442) strategy = client.db.strategy.find_one({'_id': ObjectId(_id)}) if strategy is None: return send_error(message='Not found') keys = ('name', 'issue', 'sub_issue', 'note') for k in keys: v = json_data.get(k, None) if v is not None or v != '': strategy[k] = v client.db.strategy.update({'_id': ObjectId(_id)}, strategy) return send_result(message='Cập nhật chiến dịch thành công.')
def update_email(): """ Update email data :return: """ params = { '_id': FieldString(), 'email': FieldString(), 'password': FieldString(), 'recovery_email': FieldString(), 'date': FieldString() } try: json_data = parse_req(params) _id = json_data.get('_id') except Exception as ex: return send_error(message='Json parser error', code=442) email = client.db.email.find_one({'_id': ObjectId(_id)}) if email is None: return send_error(message='Not found email') keys = ('email', 'password', 'recovery_email', 'date') for k in keys: v = json_data.get(k, None) if v is not None or v != '': email[k] = v client.db.email.update({'_id': ObjectId(_id)}, email) return send_result(message='Update email successfully')
def create_strategy(): """ Create email :return: """ params = { 'name': FieldString(), 'issue': FieldString(), 'sub_issue': FieldString(), 'note': FieldString() } try: json_data = parse_req(params) new_name = json_data.get('name').strip().lower() except Exception as ex: return send_error(message='Json parser error', code=442) strategy = client.db.strategy.find_one({'email': new_name}) if strategy is not None: return send_error(message='Duplicate strategy') keys = ('name', 'issue', 'sub_issue', 'note') strategy = dict() for k in keys: v = json_data.get(k, None) if v is not None or v != '': strategy[k] = v strategy['create_date'] = int(time.time()) client.db.strategy.insert_one(strategy) return send_result(message='Tạo chiến dịch thành công.')
def put(): claims = get_jwt_claims() if not claims['is_admin']: return send_error( message="Bạn không đủ quyền để thực hiện thao tác này") user_id = request.args.get('user_id') user = client.db.user.find_one({'_id': user_id}) if user is None: return send_error(message='Không tìm thấy người dùng.') params = { 'user_name': FieldString(requirement=True), 'password': FieldString(requirement=True), 'email': FieldString(requirement=True), 'full_name': FieldString(requirement=True), 'group_role_id': fields.Number(), 'status': fields.Number() } try: json_data = parse_req(params) full_name = json_data.get('full_name', None) email = json_data.get('email', None).lower() user_name = json_data.get('user_name', None) password = json_data.get('password', None) group_role_id = json_data.get('group_role_id', 0) status = json_data.get('status', 0) except Exception: return send_error(message='Lỗi dữ liệu đầu vào') '''Check ''' if status == USER_ACTIVATED: status = USER_ACTIVATED elif status == USER_DEACTIVATED: status = USER_DEACTIVATED else: return send_error(message="Bạn chưa nhập trạng thái") '''End check''' _id = str(ObjectId()) new_user = { '$set': { 'full_name': full_name, 'user_name': user_name, 'password': hash_password(password), 'email': email, 'group_role_id': int(group_role_id), 'status': int(status), } } try: client.db.user.update_one({'_id': user_id}, new_user) except Exception: return send_error(message='có lỗi ngoại lệ sảy ra') return send_result(message="Cập nhật thành công", data=user)
def delete(): user_id = request.args.get('user_id') user = client.db.user.find_one({'_id': user_id}) if user is None: return send_error( message="Không tìm thấy dự liệu đầu vào trong cơ sở dữ liệu") try: client.db.user.delete_one({'_id': user_id}) except Exception: return send_error(message="Lỗi xóa không thành công") return send_result(message="Xóa thành công")
def create_property(): """ This is api for the property management registers property. Request Body: Returns: Examples:: """ try: json_data = request.get_json() # Check valid params validate(instance=json_data, schema=property_validator) except Exception as ex: return send_error(message=str(ex)) property_duplicated = client.db.properties.find_one( {"name": json_data.get("name", None)}) if property_duplicated: return send_error(message="The property name has existed!") keys = [ "name", "address", "phone", "distance_from_center", "description", "is_near_beach", "rank", "meal", "city_id", "property_type_id" ] property_type = client.db.property_types.find_one( {"_id": json_data.get("property_type_id", None)}) if not property_type: return send_error(message="Not found the property type") city = client.db.cities.find_one({"_id": json_data.get("city_id", None)}) if not city: return send_error(message="Not found the city") property_id = str(ObjectId()) new_property = {"_id": property_id} for key in keys: if key in json_data: new_property[key] = json_data.get(key) try: client.db.properties.insert_one(new_property) except Exception as ex: return send_error(message="Insert to database error: " + str(ex)) return send_result(data=new_property, message="Create property successfully!")
def update_property(property_id): """ This is api for the property management edit the property. Request Body: Returns: Examples:: """ _property = client.db.properties.find_one({"_id": property_id}) if _property is None: return send_error(message="Not found property!") try: json_data = request.get_json() # Check valid params validate(instance=json_data, schema=property_validator) except Exception as ex: return send_error(message=str(ex)) keys = [ "name", "address", "phone", "distance_from_center", "description", "is_near_beach", "rank", "meal", "city_id", "property_type_id" ] property_type = client.db.property_types.find_one( {"_id": json_data.get("property_type_id", None)}) if not property_type: return send_error(message="Not found the property type") city = client.db.cities.find_one({"_id": json_data.get("city_id", None)}) if not city: return send_error(message="Not found the city") data = {} for key in keys: if key in json_data: data[key] = json_data.get(key) new_values = {"$set": data} try: client.db.properties.update_many({"_id": property_id}, new_values) except Exception as ex: return send_error(message="Database error: " + str(ex)) return send_result(data=data, message="Update property successfully!")
def login(): """ This is controller of the login api Requests Body: Returns: Examples:: """ params = { 'username': FieldString(), 'password': FieldString() } try: json_data = parse_req(params) username = json_data.get('username', None).strip() password = json_data.get('password') except Exception as ex: logger.error('{} Parameters error: '.format(get_datetime_now().strftime('%Y-%b-%d %H:%M:%S')) + str(ex)) return send_error(message='Invalid username or password.\nPlease try again') user = client.db.users.find_one({'username': username}) if user is None: return send_error(message='Invalid username or password.\nPlease try again') if not check_password_hash(user["password_hash"], password): return send_error(message='Invalid username or password.\nPlease try again') access_token = create_access_token(identity=user["_id"], expires_delta=ACCESS_EXPIRES) refresh_token = create_refresh_token(identity=user["_id"], expires_delta=REFRESH_EXPIRES) # Store the tokens in our store with a status of not currently revoked. add_token_to_database(access_token, user["_id"]) add_token_to_database(refresh_token, user["_id"]) data = { 'access_token': access_token, 'refresh_token': refresh_token, 'username': user["username"], 'is_admin': user["is_admin"], 'user_id': user["_id"], 'name': user["name"], } return send_result(data=data, message="Logged in successfully!")
def get_permission_by_id(permission_id): try: row = PermissionDetail.query.get(permission_id) except Exception as ex: return send_error(message=str(ex)) rs = permission_schema.dump(row).data return send_result(data=rs)
def get_all(): try: list_items = PermissionDetail.query.all() except Exception as ex: return send_error(message=str(ex)) results = permissions_schema.dump(list_items).data return send_result(data=results)
def get_data(): """ get data questions url: /api/questions :return: data questions """ try: list_data = [] conn = sqlite3.connect('./test.db') c = conn.execute('SELECT * FROM qa;') data = c.fetchall() for item in data: list_data.append({ 'id': item[0], 'questions': item[1], 'a': item[2], 'b': item[3], 'c': item[4], 'd': item[5], 'description': item[7] }) except Exception as e: return send_error(message='DB error') finally: conn.close() return send_result(data=list_data)
def get(): try: setting = SecurityPolicy.query.first() except Exception as ex: return send_error(message=str(ex)) results = security_policy_schema.dump(setting).data return send_result(data=results)
def get_channel(): """ Using for get all data of emails :return: """ try: page = int(request.args.get('page', 0)) page_size = int(request.args.get('size', 10)) search = request.args.get('search', '') except Exception as ex: return send_error(message='Parser params error') query = dict() if search and search != '': query['name'] = {"$regex": search} data = client.db.channel.find(query).skip(page_size * page).limit(page_size) totals = client.db.channel.count(query) data = list(data) for item in data: item['_id'] = str(item['_id']) strategy = client.db.strategy.find_one( {'_id': ObjectId(item['strategy'])}) if strategy is not None: strategy['_id'] = str(strategy['_id']) item['strategy'] = strategy return_data = dict(rows=data, totals=totals) return send_result(data=return_data)
def predictions(): """ This api predict price of a room. Returns: Examples:: """ _type = request.args.get('type', "linear") try: json_data = request.get_json() # Check valid params validate(instance=json_data, schema=feature_validator) except Exception as ex: return send_error(message=str(ex)) json_data["city_id"] = float(json_data["city_id"]) json_data["property_type_id"] = float(json_data["property_type_id"]) x = np.array([[ json_data["acreage"], json_data["bed_type"], json_data["distance_from_center"], json_data["is_near_beach"], json_data["rank"], json_data["meal"], json_data["city_id"], json_data["property_type_id"] ]]) # standardized data x = scaler_x.transform(x) price = linear.predict(x)[0] price = scaler_y.revert(price) return send_result(data=round(price, 2))
def get_users(): """ Using for get all data of user :return: """ try: page = int(request.args.get('page')) page_size = int(request.args.get('size')) search = request.args.get('search', '') except Exception as ex: return send_error(message='Json parse error') query = dict() if search and search != '': query['username'] = {"$regex": search} data = client.db.user.find(query).skip(page_size * page).limit(page_size) totals = client.db.user.count({}) data = list(data) for item in data: item['_id'] = str(item['_id']) del item['password'] return_data = dict(rows=data, totals=totals) return send_result(data=return_data)
def delete_channel(): """ DELETE email :return: """ try: _id = request.args.get('id', '') except Exception as ex: return send_error(message='Json parser error', code=442) channel = client.db.channel.find_one({'_id': ObjectId(_id)}) if channel is None: return send_error(message='Không thể tìm thấy vui lòng thử lại.') client.db.channel.remove({'_id': ObjectId(_id)}) return send_result(message='Đã xóa thành công.')
def delete(group_id): try: get_group = Group.query.get(group_id) except Exception as ex: return send_error(message="Database error: " + str(ex)) if get_group is None: return send_error(message='Not found group to delete!') try: db.session.delete(get_group) db.session.commit() except Exception as ex: return send_error(message=str(ex)) group_json = user_group_schema.dump(get_group).data return send_result(data=group_json, message="Delete group successfully!")
def start_report(): """ Start report :return: """ try: _id = request.args.get('id', '') except Exception as ex: return send_error(message='Json parser error', code=442) channel = client.db.channel.find_one({'_id': ObjectId(_id)}) if channel is None: return send_error(message='Không thể tìm thấy vui lòng thử lại.') start_report.delay() return send_result(message='Khởi tạo thành công')
def create_user(): """ This is api for the user management registers user. Request Body: Returns: Examples:: """ try: json_data = request.get_json() # Check valid params validate(instance=json_data, schema=user_validator) username = json_data.get('username', None).strip() password = json_data.get('password', None) except Exception as ex: logger.error('{} Parameters error: '.format(get_datetime_now().strftime('%Y-%b-%d %H:%M:%S')) + str(ex)) return send_error(message="Parameters error: " + str(ex)) user_duplicated = client.db.users.find_one({"username": username}) if user_duplicated: return send_error(message="The username has existed!") if is_password_contain_space(password): return send_error(message='Password cannot contain spaces') keys = ["username", "name", "gender", "phone", "email", "is_admin"] user_id = str(ObjectId()) new_user = { "_id": user_id, 'password_hash': hash_password(password) } for key in keys: if key in json_data: new_user[key] = json_data.get(key) try: client.db.users.insert_one(new_user) except Exception as ex: return send_error(message="Insert to database error: " + str(ex)) return send_result(data=new_user, message="Create user successfully!")
def change_password(): """ This api for all user change their password. Request Body: Returns: Examples:: """ user_id = get_jwt_identity() current_user = client.db.users.find_one({"_id": user_id}) try: json_data = request.get_json() # Check valid params validate(instance=json_data, schema=password_validator) current_password = json_data.get('current_password', None) new_password = json_data.get('new_password', None) except Exception as ex: logger.error('{} Parameters error: '.format(get_datetime_now().strftime('%Y-%b-%d %H:%M:%S')) + str(ex)) return send_error(message='Parse error ' + str(ex)) if not check_password_hash(current_user["password_hash"], current_password): return send_error(message="Current password incorrect!") if is_password_contain_space(new_password): return send_error(message='Password cannot contain spaces') new_value = { '$set': { 'password_hash': hash_password(new_password) } } try: client.db.users.update_many({'_id': user_id}, new_value) except Exception as ex: return send_error(message='Database error: ' + str(ex)) # revoke all token of current user from database except current token revoke_all_token2(user_id) return send_result(message="Change password successfully!")
def delete_strategy(): """ DELETE email :return: """ try: _id = request.args.get('id', '') except Exception as ex: return send_error(message='Json parser error', code=442) strategy = client.db.strategy.find_one({'_id': ObjectId(_id)}) if strategy is None: return send_error( message='Không thể tìm thấy chiến dịch, vui lòng thử lại.') client.db.strategy.remove({'_id': ObjectId(_id)}) return send_result(message='Đã xóa thành công.')