def store_assessment_answers(): data = request.get_json() schema = { 'que_id': { 'required': True, 'type': 'string' }, 'opt_id': { 'required': True, 'type': 'string' }, 'map_id': { 'required': True, 'type': 'string' }, 'answer_score': { 'required': True, 'type': 'string' } } res = validator.validate(data, schema) if not res: response = Response() response.success = False response.status = 400 response.errors = "Required data not provided." store = hp.StoreAssessmentAnswers() store_response = store.insert(data) if not store_response.success: store_response.status = 400 store_response.success = False store_response.message = "Assessment Answer Not stored!!" return store_response.response_json()
def login_user(data): try: # fetch the user data user = User.query.filter_by(email=data.get('email')).first() print("user: "******"check: ", user.check_password(data.get('password'))) if user and user.check_password(data.get('password')): auth_token = User.encode_auth_token(user.id) if auth_token: response_object = { 'status': 'success', 'message': 'Successfully logged in.', 'Authorization': auth_token.decode() } # mark the token as blacklisted save_token(token=auth_token) return Response.jsonify(message=response_object) else: response_object = { 'status': 'fail', 'message': 'email or password does not match.' } return Response.jsonify(status=401, message=response_object) except Exception as e: response_object = {'status': 'fail', 'message': 'Try again'} return Response.jsonify(message=response_object)
def send_bulk_mail(): data = request.get_json() schema = { 'client_id': { 'required': True, 'type': 'string' }, 'cycle_id': { 'required': True, 'type': 'string' }, 'dept_id': { 'required': True, 'type': 'list' } } res = validator.validate(data, schema) if not res: response = Response() response.success = False response.status = 400 response.message = "Required data not found" bulk_mail = hp.BulkMailEmp() bulk_mail_resp = bulk_mail.send_alert_mail_emp(data) if not bulk_mail_resp.success: bulk_mail_resp.success = False bulk_mail_resp.status = 400 bulk_mail_resp.message = "Employee details not found" return bulk_mail_resp.response_json()
async def post(self, request): """ @api {post} /login 登录 @apiVersion 0.0.1 @apiName Login-post @apiDescription 登录 @apiGroup Auth @apiParam {string} email 邮箱 @apiParam {string} password 用户密码 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK Connection: keep-alive Content-Length: 72 Content-Type: application/json Keep-Alive: 60 { "code": 0, "message": "success", "result": { "token": "YEmBbhuVQHojIk3cxeWa" } } @apiErrorExample {json} Error-Response: HTTP/1.1 400 Bad Request Connection: keep-alive Content-Length: 62 Content-Type: application/json Keep-Alive: 60 { "code": 1002, "message": "请求参数有误" } """ current_user = request.get('current_user') if current_user: data = { "token": request.headers.get('authorization').split(" ")[1] } return json(Response.make(result=data)) self._check_request(request, UserSchema) if self.error: return self.error_resp email = self.request_arg.get('email') password = self.request_arg.get('password') user = await User.db_get(email=email) if not (user and user.verify_password(password) and user.active): return json(Response.make(code=1001), status=400) token_str = get_random_str(20) await user.gen_confirm_code(request, token=token_str) data = {"token": token_str} return json(Response.make(result=data))
def delete_user_by_public_id(public_id): user = User.query.filter_by(public_id=public_id).first() if not user: return Response.bad_request(message=constants.MESG_USER_NOT_FOUND) db.session.delete(user) db.session.commit() return Response.jsonify("OK", "User is deleted.")
async def post(self, request): """ @api {post} /register 注册 @apiVersion 0.0.1 @apiName Register @apiDescription 注册 @apiGroup Auth @apiParam {string} username 用户名 @apiParam {string} email 注册邮箱(以后登录使用,单个邮箱只能注册一个帐号) @apiParam {string} password 用户密码 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK Connection: keep-alive Content-Length: 49 Content-Type: application/json Keep-Alive: 60 { "code": 0, "message": "success", "result": "Success" } @apiErrorExample {json} Error-Response: HTTP/1.1 400 Bad Request Connection: keep-alive Content-Length: 62 Content-Type: application/json Keep-Alive: 60 { "code": 1002, "message": "请求参数有误" } """ self._check_request(request, UserSchema) if self.error: return self.error_resp email = self.request_arg.get('email') username = self.request_arg.get('username') user = await User.db_get(email=email) if user or not username: return json(Response.make(code=1002), status=400) token = get_random_str(20) current_user = await User.db_create(**self.request_arg) email_status = await email_msg(request, email, self.request_arg.get('username'), token) if not email_status: return json(Response.make(code=1000), starus=400) await current_user.gen_confirm_code(request, token) return json(Response.make(result='Success'))
def get_all_users(): user_list = User.query.all() if not user_list: return Response.bad_request() else: user_list = User.query.all() output = [user.to_json() for user in user_list] return Response.jsonify(data=output)
def employee_details(): data = request.get_json() schema = { 'emp_id': { 'required': True, 'type': 'string' }, 'client_id': { 'required': True, 'type': 'string' }, 'cycle_id': { 'required': False, 'type': 'string' } } res = validator.validate(data, schema) if not res: response = Response() response.success = False response.status = 400 response.errors = "Required data not provided." employee = hp.Employee() response = employee.delete(data) if not response.success: response.success = False response.status = 400 response.errors = "Employee relation not added" return response.response_json()
async def post(self, request): """ @api {post} /logout 登出 @apiVersion 0.0.1 @apiName Logout @apiDescription 登出用户 @apiGroup Auth @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK Connection: keep-alive Content-Length: 49 Content-Type: application/json Keep-Alive: 60 { "code": 0, "message": "success", } @apiErrorExample {json} Error-Response: HTTP/1.1 400 Bad Request Connection: keep-alive Content-Length: 62 Content-Type: application/json Keep-Alive: 60 { "code": 1002, "message": "请求参数有误" } @apiErrorExample {json} Error-Response: HTTP/1.1 401 Unauthorized Connection: keep-alive Content-Length: 68 Content-Type: application/json Keep-Alive: 60 { "code": 1001, "message": "账号或密码错误" } """ current_user = request.get('current_user') with await request.app.redis as r: key = request.app.config.TOKEN_STR + str(current_user.id) token = await r.get(key) if not token: return json(Response.make(code=1002), status=400) r.delete(token.decode()) return json(Response.make())
def save_token(token): blacklist_token = BlacklistToken(token=token) try: # insert the token db.session.add(blacklist_token) db.session.commit() response_object = { 'status': 'success', 'message': 'Successfully logged out.' } return Response.jsonify(status=200, message=response_object) except Exception as e: response_object = {'status': 'fail', 'message': e} return Response.jsonify(status=200, message=response_object)
async def get(self, request, token): """ @api {post} /confirm/<token> 用户验证 @apiVersion 0.0.1 @apiName Confirm-get @apiDescription 账户邮箱激活 @apiGroup Auth @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK Connection: keep-alive Content-Length: 49 Content-Type: application/json Keep-Alive: 60 { "code": 0, "message": "success", "result":{ "token":"pwVbZvAAdi8yEaWextkG" } } @apiErrorExample {json} Error-Response: HTTP/1.1 400 Bad Request Connection: keep-alive Content-Length: 62 Content-Type: application/json Keep-Alive: 60 { "code": 1002, "message": "请求参数有误" } """ with await request.app.redis as c: key, user_id = await c.hmget(token, 'key', 'id') user = await User.db_get(id=user_id) if not (key.decode() == token and user) or \ request.get('current_user') or \ user.active: return json(Response.make(code=1002), status=401) user.active = True await user.db_update() data = {"token": key} return json(Response.make(result=data))
def generate_token(user): try: # generate the auth token auth_token = User.encode_auth_token(user.id) response_object = { 'status': 'success', 'message': 'Successfully registered.', 'Authorization': auth_token.decode() } return Response.jsonify(message=response_object) except Exception as e: response_object = { 'status': 'fail', 'message': 'Some error occurred. Please try again.' } return Response.jsonify(message=response_object)
def logout_user(data): if data: auth_token = data.split(" ")[0] else: auth_token = '' if auth_token: resp = User.decode_auth_token(auth_token) if not isinstance(resp, str): return else: response_object = {'status': 'fail', 'message': resp} return Response.jsonify(status=401, message=response_object) else: response_object = { 'status': 'fail', 'message': 'Provide a valid auth token.' } return Response.jsonify(status=403, message=response_object)
def get_dept_details(): data = { 'client_id': request.args.get('client_id'), 'cycle_id': request.args.get('cycle_id') } response = Response() schema = { 'client_id': { 'required': True, 'type': 'string' }, 'cycle_id': { 'required': True, 'type': 'string' } } res = validator.validate(data, schema) if not res: response.success = False response.status = 400 response.message = "Required data not found" return response.response_json() department = hp.ClientDeptDetails() dept_response = department.select(data) if not dept_response.success: dept_response.success = False dept_response.status = 400 dept_response.message = "Department Details not fetched." return dept_response.response_json()
def get_assessment_status(): data = { 'client_id': request.args.get('client_id'), 'cycle_id': request.args.get('cycle_id') } schema = { 'client_id': { 'required': True, 'type': 'string' }, 'cycle_id': { 'required': True, 'type': 'string' } } res = validator.validate(data, schema) if not res: response = Response() response.success = False response.status = 400 response.errors = "Required data not provided." return response.response_json() status = hp.Participant() status_response = status.get_participant_assessment_status(data) if status_response.success: status_response.message = "Employe details added " elif not status_response.success: status_response.success = False status_response.status = 400 status_response.errors = "Participants details not fetched." return status_response.response_json()
def login(): data = request.get_json() schema = { 'emp_id': { 'required': True, 'type': 'string' }, 'client_id': { 'required': True, 'type': 'string' }, 'password': { 'required': True, 'type': 'string' }, 'user_role': { 'required': True, 'type': 'string' } } res = validator.validate(data, schema) if not res: response = Response() response.success = False response.status = 400 response.errors = "Required data not provided." login = hp.LogIn() response = login.validate(data) if response.success: response.data = { "client_id": response.data['client_id'], "cycle_id": response.data['cycle_id'], "user_type": data["user_role"], "user_info": { "name": response.data['name'], "emp_id": response.data['emp_id'], "email_id": response.data['email_id'] } } response.message = "Login Success!!" return response.response_json()
def save_new_uer(data): user = User.query.filter_by(email=data['email']).first() if not user: new_user = User( public_id=str(uuid.uuid4()), email=data['email'], username=data['username'], password=data['password'], registered_on=datetime.datetime.utcnow(), admin=data['admin'] ) save_changes(new_user) return generate_token(new_user) else: response_object = { 'status': 'fail', 'message': 'User already exists.' } return Response.jsonify(message=response_object)
class ClientAdminDetails: """To perform CRUD operations for the table client_table_m""" def __init__(self): self.response = Response() def select(self, json_data): try: admins = db.session.query( models.ClientAdminRepo, models.EmployeeDetailsRepo).join( models.EmployeeDetailsRepo, models.EmployeeDetailsRepo.emp_id == models.ClientAdminRepo.emp_id).join( models.ClientCycleRepo, models.ClientCycleRepo.cycle_id == models.ClientAdminRepo.cycle_id).filter( and_( models.ClientCycleRepo.client_id == json_data['client_id'], models.ClientCycleRepo.is_active == True, models.ClientAdminRepo.emp_id == json_data['emp_id'])).first() if admins is not None: self.response.data = { "name": admins.EmployeeDetailsRepo.emp_name, "emp_id": admins.EmployeeDetailsRepo.emp_id, "email_id": admins.EmployeeDetailsRepo.emp_email, "cycle_id": admins.ClientAdminRepo.cycle_id } print(self.response.response_json()) self.response.status = 200 else: self.response.status = 400 self.response.success = False except SQLAlchemyError as error: self.response.status = 400 self.response.message = str(error) self.response.success = False except Exception as error: db.session.rollback() logger.exception(error) self.response.status = 400 self.response.success = False self.response.message = str(error) return self.response
class BaseView(HTTPMethodView): logger = log request_arg = dict() error = dict() error_resp = Response.make(code=1002) response_arg = list() or dict() def _check_request(self, request, schema): data, error = request_loads(request, schema) if error: self.error = error self.error_resp = json(Response.make(code=1002, result=error), status=400) self.request_arg = data def _check_data(self, data, schema): result, error = data_dumps(data, schema) if error: self.error = error self.error_resp = json(Response.make(code=1000, result=error), status=400) self.response_arg = result
def get_cycle_details(): data = {'client_id': request.args.get('client_id')} response = Response() schema = {'client_id': {'required': True, 'type': 'string'}} res = validator.validate(data, schema) if not res: response.success = False response.status = 400 response.message = "Required data not found" return response.response_json() cycle_details = hp.ClientCycleDetails() cycle_response = cycle_details.select(data) if not cycle_response.success: cycle_response.success = False cycle_response.status = 400 cycle_response.data = list() cycle_response.message = "Failed to load client cycle details" return cycle_response.response_json()
def table(request): url = url_for("table") # подключаем необходимые таблицы для списков в jinja2 regions = Region.query.all() queries = Users.query.all() # инициируем и преобразуем для чтетия выгрузку таблицы Users db = sqlite3.connect('data.db', uri=True) c = db.cursor() script = """ SELECT * FROM Users """ c.execute(script) columns = [desc[0] for desc in c.description] data = c.fetchall() df = pd.DataFrame(list(data), columns=columns) writer = pd.ExcelWriter(basedir2 + r'/database.xlsx') df.to_excel(writer, sheet_name='0', index=False) writer.save() replace_id_loc2(basedir2, r'/database.xlsx') # получаем данные из формы далее записывает данные в таблицу users if request.method == "POST": # запись в db полученой информации из формы try: firstName = request.form['firstName'] middleName = request.form['middleName'] lastName = request.form['lastName'] phone = request.form['phone'] email = request.form['email'] city = request.form['city'] rel_city = City.query.filter(City.name == city).first() try: done_db = Users( firstName=firstName, middleName=middleName, lastName=lastName, phone=phone, email=email, region_id=rel_city.region_id, city_id=rel_city.id, ) session.add(done_db) session.commit() return redirect(url_for("table")) except Exception as e: # обработаем исключение если город и регин не заполнен выведим пустую ячейку try: error = e.args[0].split() error_str = error[5].replace("'", "") if error_str == 'region_id' or error_str == 'city_id': done_db = Users( firstName=firstName, middleName=middleName, lastName=lastName, phone=phone, email=email, region_id=None, city_id=None, ) session.add(done_db) session.commit() finally: return redirect(url_for("table")) except Exception as e: try: return e finally: # сереализуем post запрос в json для ajax if request.form['region']: region = request.form['region'] records = [ z.to_json() for z in Region.query.filter_by(name_region=region) ] cont = json.dumps(records[0], sort_keys=True) return Response(cont, content_type="application/json") return render_template("table.html", url=url, queries=queries, regions=regions)
def save_new_uer(): if not request.json: return Response.bad_request() return controller.save_new_uer(data=request.json)
def store_feedback(): data = request.get_json() response = Response() schema = { 'client_id': { 'required': True, 'type': 'string' }, 'cycle_id': { 'required': True, 'type': 'integer' }, 'map_id': { 'required': True, 'type': 'integer' }, 'level_id': { 'required': True, 'type': 'integer' }, 'feedback_text': { 'required': True, 'type': 'string' } } res = validator.validate(data, schema) if not res: response.success = False response.status = 400 response.message = "Required data not found" store_feed = hp.StoreFeedback() response = store_feed.create(data) if response.success: response.success = True response.status = 200 response.data = {} response.message = "Success" elif not response: response.success = False response.status = 400 response.message = "Failure" return response.response_json()
async def post(self, request): """ @api {post} /account 邮箱,密码修改 @apiVersion 0.0.1 @apiName Change-auth @apiDescription 更改邮箱,密码 @apiGroup Auth @apiParam {string} email 邮箱 @apiParam {string} password 用户密码 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK Connection: keep-alive Content-Length: 49 Content-Type: application/json Keep-Alive: 60 { "code": 0, "message": "success", "result": "Success" } @apiErrorExample {json} Error-Response: HTTP/1.1 400 Bad Request Connection: keep-alive Content-Length: 62 Content-Type: application/json Keep-Alive: 60 { "code": 1000, "message": "系统错误" } @apiErrorExample {json} Error-Response: HTTP/1.1 400 Bad Request Connection: keep-alive Content-Length: 62 Content-Type: application/json Keep-Alive: 60 { "code": 1002, "message": "请求参数有误", "result": { "email": [ "Missing data for required field." ] } } @apiErrorExample {json} Error-Response: HTTP/1.1 401 Unauthorized Connection: keep-alive Content-Length: 68 Content-Type: application/json Keep-Alive: 60 { "code": 1001, "message": "账号或密码错误" } """ current_user = request.get("current_user") self._check_request(request, UserSchema) if self.error: return self.error_resp email = self.request_arg.get('email') password = self.request_arg.get('password') exist = await User.db_get(email=email) if email == current_user.email and\ exist: return json(Response.make(result="Not Change")) with await request.app.redis as coon: token = request.headers.get('authorization').split(" ")[1] await coon.delete(token) update_status = await current_user.db_update(email=email, password=password, active=False) if not update_status: return json(Response.make(code=1000), status=400) token = get_random_str(20) email_status = await email_msg(request, email, self.request_arg.get('username'), token) await current_user.gen_confirm_code(request, token) if not email_status: return json(Response.make(code=1000), status=400) return json(Response.make(result='Success'))
def paticipant_details(): data = { 'client_id': request.args.get('client_id'), 'cycle_id': request.args.get('cycle_id') } schema = { 'client_id': { 'required': True, 'type': 'string' }, 'cycle_id': { 'required': True, 'type': 'string' } } res = validator.validate(data, schema) if not res: response = Response() response.success = False response.status = 400 response.errors = "Required data not provided." return response.response_json() data["assessment_role"] = "participant" employee = hp.Employee() response = employee.select(data) if response.success: response.message = "Employe details added " response.data = {"participant_details": response.data} elif not response.success: response.success = False response.status = 400 response.errors = "Participants details not fetched." return response.response_json()
def _check_data(self, data, schema): result, error = data_dumps(data, schema) if error: self.error = error self.error_resp = json(Response.make(code=1000, result=error), status=400) self.response_arg = result
def _check_request(self, request, schema): data, error = request_loads(request, schema) if error: self.error = error self.error_resp = json(Response.make(code=1002, result=error), status=400) self.request_arg = data
def add_emp_details(): data = request.get_json() schema = { 'emp_id': { 'required': True, 'type': 'string' }, 'client_id': { 'required': True, 'type': 'string' }, 'cycle_id': { 'required': True, 'type': 'string' }, 'emp_name': { 'required': True, 'type': 'string' }, 'emp_email': { 'required': True, 'type': 'string' }, 'function': { 'required': True, 'type': 'string' }, 'location': { 'required': True, 'type': 'string' }, 'band': { 'required': True, 'type': 'string' }, 'role': { 'required': True, 'type': 'string' }, 'assessment_role': { 'required': True, 'type': 'string' }, 'relationship': { 'required': True, 'type': 'dict', 'schema': { 'relation_type': { 'type': 'string' }, 'target_emp_id': { 'type': 'string' } } } } res = validator.validate(data, schema) if not res: response = Response() response.success = False response.status = 400 response.errors = "Required data not provided." employee = hp.Employee() response = employee.create([data]) if response.success: maping = hp.EmployeeRelationMapping() db_res = maping.create({ "emp_id": data["emp_id"], "cycle_id": data["cycle_id"], "relation_type": data['relationship']["relation_type"], "target_emp_id": data['relationship']["target_emp_id"] }) if not db_res.success: response.success = False response.status = 400 response.errors = "Employee relation not added" elif not response.success: response.success = False response.status = 400 response.errors = "Employee relation not added" return response.response_json()
def add_cycle_details(): data = request.get_json() response = Response() schema = { 'client_id': { 'required': True, 'type': 'string' }, 'cycle_name': { 'required': True, 'type': 'string' }, 'from_date': { 'required': True, 'type': 'string' }, 'to_date': { 'required': True, 'type': 'string' } } res = validator.validate(data, schema) if not res: response.success = False response.status = 400 response.message = "Required data not found" client_cycle = hp.ClientCycleDetails() response = client_cycle.create(data) if response.success: response.status = 200 response.data = { "client_id": response.data['client_id'], "cycle_id": response.data['cycle_id'] } response.message = "Success" elif not response: response.success = False response.status = 400 response.message = "Failure" return response.response_json()
def add_dept_details(): data = request.get_json() response = Response() schema = { 'client_id': { 'required': True, 'type': 'string' }, 'cycle_id': { 'required': True, 'type': 'integer' }, 'function': { 'required': True, 'type': 'string' }, 'role': { 'required': True, 'type': 'string' }, 'location': { 'required': True, 'type': 'string' }, 'band': { 'required': True, 'type': 'string' } } res = validator.validate(data, schema) if not res: response.success = False response.status = 400 response.message = "Required data not found" department = hp.ClientDeptDetails() add_dept = department.create(data) if add_dept: response.success = True response.status = 200 response.message = "Success" elif not add_dept: response.success = False response.status = 400 response.message = "Failure" return response.response_json()