def send_verification(): # Send a verification mail current_user = get_current_user() url_conf = generate_confirmation_token(current_user.email) msg = Message( "Validation de votre inscription à J4U", sender="*****@*****.**", recipients=[current_user.email], ) msg.html = """ <p> Bonjour, </p> <p> Nous vous remercions pour votre participation au projet « Job For You » (J4U). </p> <p> Suite à votre inscription, voici un email de confirmation. Afin de valider votre compte, il vous suffit de cliquer sur le lien suivant (qui n’est actif que quelques jours) : </p> <p> <a href="{}">Cliquez ici pour confirmer votre adresse email</a> </p> <p> L’équipe J4U </p> """.format( url_conf ) mail.send(msg) return jsonify(success=True)
def job_props(): current_user = get_current_user() job = request.args.get("job") if not job or len(job) < 3: return jsonify({}) res = search(job) return jsonify(res)
def fetch_profile(): """ GET endpoint that fetches the complete student profile. """ user = get_current_user() return _fetch_user_profile(user)
def add_favorite_clubs(): """ POST endpoint that adds favorite club(s) for student user. Ordering is preserved based on *when* they favorited. """ user = get_current_user() json = g.clean_json new_fav_clubs_query = NewOfficerUser.objects \ .filter(confirmed=True) \ .filter(club__link_name__in=json['clubs']) \ .only('club.link_name') potential_clubs = [ club['club']['link_name'] for club in query_to_objects(new_fav_clubs_query) ] for club in potential_clubs: if club not in user.favorited_clubs: user.favorited_clubs += [club] user.save() return jsonify(_fetch_user_profile(user)['favorited_clubs'])
def wrap(*args, **kwargs): response: Response = func(*args, **kwargs) self.response = response self.user = get_current_user() self.message = self._parse_template() self.push_message() return response
def delete(self, org_id, staff_id): """退出组织/删除雇员 --- tags: - 组织部门雇员 parameters: - name: org_id in: url type: string required: true description: 组织id - name: staff_id in: url type: string required: true description: 雇员id responses: 200: examples: response: {"data": null, "message": "退出成功"} """ user = get_current_user() current_org_staff = db.session.query(OrgStaff.id).filter( OrgStaff.user_id == user.id, OrgStaff.org_id == org_id).first() if not current_org_staff: return json_response(message="您不属于该组织", status=403) org_staff = OrgStaff.query.filter_by(id=staff_id, org_id=org_id).first_or_404() if org_staff.job_title == "组织创建人": return json_response(message="您是管理员,无法直接退出组织", status=403) else: db.session.delete(org_staff) db.session.commit() return json_response(message="退出成功")
def get(self, org_id): """获取组织下的所有部门 --- tags: - 组织部门 parameters: - name: org_id in: url type: string required: true responses: 200: examples: response: {"data": [], "message": "ok"} """ user = get_current_user() org_department_list = db.session.query(OrgDepartment) \ .filter(OrgDepartment.org_id == org_id, OrgStaff.org_id == org_id, OrgStaff.user_id == user.id, OrgDepartment.parent_id.is_(None)) \ .all() org_department_schema = OrgDepartmentSchema(many=True) org_department_data = org_department_schema.dump( org_department_list).data return json_response(data=org_department_data, message="ok")
def change_password(): """ POST endpoint that changes the current user's password without revoking all the access and refresh tokens. """ user = get_current_user() club = user.club json = g.clean_json old_password = json['old_password'] new_password = json['new_password'] if not hash_manager.verify(old_password, user.password): raise JsonError(status='error', reason='The old password is incorrect.') # Check if the password is the same if old_password == new_password: raise JsonError(status='error', reason='The old and new passwords are identical.') # Check if the password is strong enough is_password_strong = flask_exts.password_checker.check(new_password) if not is_password_strong: raise JsonError(status='error', reason='The new password is not strong enough') # Only set the new password if the old password is verified user.password = hash_manager.hash(new_password) user.save() return {'status': 'success'}
def add_gallery_media_pic(): """ POST endpoint that adds a new gallery picture to the club with an image upload and a caption. """ user = get_current_user() json = g.clean_json gallery_pic_file = request.files.get('photo', None) if gallery_pic_file is not None: gallery_pic_url, pic_id = flask_exts.img_manager.upload_img_asset_s3( user.club.link_name, gallery_pic_file, 'gallery', file_size_limit = 2 * 1024 * 1024 ) gallery_pic = GalleryPic( id = pic_id, url = gallery_pic_url, caption = json['caption'] ) user.club.gallery_media += [gallery_pic] user.club.last_updated = pst_right_now() user.save() return _fetch_gallery_media_list(user) else: raise JsonError(status='error', reason='A gallery picture was not provided for uploading.')
def getCurrentUser(userClass=None, apiInstance=None): currentUsert = get_current_user() if ObjectHelper.isNotNone(currentUsert): return currentUsert else: rawJwt = getJwtBody() identity = getIdentity(rawJwt=rawJwt) context = getContext(rawJwt=rawJwt) data = getData(rawJwt=rawJwt) if ObjectHelper.isNone(userClass): return { JwtConstant.KW_IDENTITY: identity, JwtConstant.KW_CONTEXT: context, JwtConstant.KW_DATA: data } else: currentUsert = userClass() currentUsert._contextInfo = { JwtConstant.KW_IDENTITY: identity, JwtConstant.KW_CONTEXT: context } for attributeName in data: if ReflectionHelper.hasAttributeOrMethod( currentUsert, attributeName): ReflectionHelper.setAttributeOrMethod( currentUsert, attributeName, data.get(attributeName)) return currentUsert
def get(self, org_id, org_department_id): """组织部门信息获取 --- tags: - 组织部门 parameters: - name: org_id in: url type: string required: true description: 组织id - name: org_department_id in: url type: string required: true description: 部门id responses: 200: description: A list of colors (may be filtered by palette) examples: response: {"data": {}, "message": "ok"} """ user = get_current_user() org_staff = db.session.query(OrgStaff.id).filter( OrgStaff.user_id == user.id, OrgStaff.org_id == org_id).first() if not org_staff: return json_response(message="您不属于该组织", status=403) org_department = OrgDepartment.query.filter_by( id=org_department_id).first_or_404() org_department_schema = OrgDepartmentSchema() data = org_department_schema.dump(org_department).data return json_response(data=data, message="ok")
def modify_gallery_pic(pic_id): """ PUT endpoint that either replaces an existing gallery picture, changes the image's caption or does both at the same time. """ user = get_current_user() json = g.clean_json gallery_pic = user.club.gallery_media.filter(id=pic_id).first() if gallery_pic is None: raise JsonError(status='error', reason='Specified gallery picture does not exist.') new_caption = json.get('caption', None) if new_caption is not None: gallery_pic.caption = new_caption gallery_pic_file = request.files.get('photo', None) if gallery_pic_file is not None: gallery_pic_url, new_pic_id = flask_exts.img_manager.upload_img_asset_s3( user.club.link_name, gallery_pic_file, 'gallery', file_size_limit = 2 * 1024 * 1024 ) gallery_pic.id = new_pic_id gallery_pic.url = gallery_pic_url user.club.last_updated = pst_right_now() user.save() return _fetch_gallery_media_list(user)
def route_test_celery(word): current_user = get_current_user() # type: User if not current_user: abort(400, "Could not authenticate user with provided token") elif not check_if_user_is_superuser(current_user): abort(400, "Not a superuser") celery_app.send_task("app.worker.test_celery", args=[word]) return ({"msg": "Word received"}, 201)
def gcode_create(org_uuid): if "file" not in request.files: return abort(make_response(jsonify(message="No file uploaded"), 400)) incoming = request.files["file"] if incoming.filename == "": return abort( make_response(jsonify(message="Uploaded file has to have a name"), 400)) if not re.search(r"\.gco(de)?$", incoming.filename): return abort( make_response( jsonify(message="Uploaded file does not look like gcode"), 415)) try: saved = files.save(org_uuid, incoming, request.form.get("path", "/")) gcode_id = gcodes.add_gcode( uuid=guid.uuid4(), path=saved["path"], filename=saved["filename"], display=saved["display"], absolute_path=saved["absolute_path"], size=saved["size"], user_uuid=get_current_user()["uuid"], organization_uuid=org_uuid, ) analyze_gcode.delay(gcode_id) except (IOError, OSError) as e: return abort(make_response(jsonify(message=str(e)), 500)) return ( jsonify( make_gcode_response({ "uuid": gcode_id, "organization_uuid": org_uuid, "user_uuid": get_current_user()["uuid"], "username": get_current_user()["username"], "path": saved["path"], "filename": saved["filename"], "display": saved["display"], "absolute_path": saved["absolute_path"], "uploaded": datetime.datetime.now(), "size": saved["size"], })), 201, )
def delete(self, pid): patient = PatientsModel.objects.get_or_404(id=pid, added_by=get_current_user()) patient.delete() return {'message': 'Patient deleted'}
def get(self, pid): schema = PatientsSchema() patient = PatientsModel.objects.get_or_404(id=pid, added_by=get_current_user()) return schema.jsonify(patient)
def decorated_function(*args, **kwargs): user = get_current_user() if not user.get_admin(): current_app.logger.warning( f'{f.__name__}() failed. userid={user.userid} is not admin' ) return make_response('Unathorized', 401) return f(*args, **kwargs)
def project_detail(project_id): user = get_current_user() project = Project.query.get(project_id) if not project: return jsonify({'msg':f'Project with id {project_id} not found'}), 404 if not (user.is_admin or user.is_project_admin(project_id)): return jsonify({'msg':'Not allowed.'}), 403 return project_schema.dumps(project)
def get_context(self): user = None try: verify_fresh_jwt_in_request() user = get_current_user() except Exception: logger.info("Failed to verify JWT") return {"request": request, "user": user}
def post(self): """ Create a real account from an anonymous user """ user = fjwt.get_current_user() username, password_hash = getNewUserFields() user.username = username user.password_hash = password_hash user.save() return user
def route_test_email(email_to): current_user = get_current_user() # type: User if not current_user: abort(400, "Could not authenticate user with provided token") elif not check_if_user_is_superuser(current_user): abort(400, "Not a superuser") send_test_email(email_to=email_to) return ({"msg": "Test email sent"}, 201)
def post(self, arch_id): arch = Architecture.query \ .filter_by(user_id=get_current_user(), id=arch_id) if arch is None: abort(403, message='This Architecture doesn\'t exists') args = request.get_json(force=True) if 'name' not in args: abort(403, message='No name provided') for name in ARGS_LIST: if name not in args: abort(403, message='No {} selected'.format(name)) name = args['name'] desc = args.get('description') dataset_id = args['dataset_id'] if Dataset.query.filter_by( user_id=get_current_user(), id=dataset_id) is None: abort(403, message='Selected dataset doesn\'t exists') if len(Model.query.filter_by(arch_id=arch_id, name=name).all()) > 0: abort(403, message='Model with this name already exists') model = Model(name=name, description=desc, weights_path='', arch_id=arch_id, dataset_id=dataset_id) model.add() try: optparams = {} for param in args['optimizer']['params']: optparams[param['id']] = float(param['value']) params = { 'nepochs': int(args['nepochs']), 'batch_size': int(args['batch_size']), 'loss': args['loss']['id'], 'optimizer': args['optimizer']['id'], 'optimizer_params': optparams } thread1 = TrainThread(model.arch_id, model.id, model.dataset_id, params) thread1.start() except Exception as e: print('Unable to start thread: {}'.format(e)) abort(500, message=e) return {'message': 'Training started succesfully'}, 200
def get_gallery_media(): """ GET endpoint that fetches all gallery pictures' metadata from a club. Each media object has an ID, URL, and caption. """ user = get_current_user() return _fetch_gallery_media_list(user)
def get(self): schema = JobSchema(many=True) previous = ['accepted', 'completed', 'declined', 'cancelled'] jobs = Jobs.objects(valet=get_current_user(), status__in=previous) by_status = request.args.get('status') if by_status: jobs = jobs.filter(status=by_status) return paginate(jobs, schema)
def _create(cls, folder, **properties): return cls.model( folder=folder, title=properties["title"], payload=properties.get("payload"), description=properties.get("description"), author=get_current_user(), )
def recipe(pk): recipe_model = get_recipe(pk) if recipe_model.status == StatusEnum.accepted or recipe_model.is_author_or_admin( get_current_user()): result = recipe_schema.dump(recipe_model) return jsonify({'recipe': result}) else: return error_response(401, "Unauthorized")
def get_authenticated_user(): try: flask_jwt_extended.verify_jwt_in_request() user = flask_jwt_extended.get_current_user() flask_login.login_user(user) return user except flask_jwt_extended.exceptions.JWTExtendedException: return None
def refresh(): """Uses a refresh token to generate a new access token""" current_user = get_current_user() return jsonify({ "status": "OK", "detail": { "access_token": create_access_token(identity=current_user.username) } }), 200
def delete(cls, _id): post = Post.query.get_or_404(_id) user = get_current_user() if post.author != user and user.is_admin is not True: return response_with( resp.FORBIDDEN_403, message="You are not the author of this post.") post.delete_from_db() return response_with(resp.SUCCESS_204)
def change_password(): form = ChangePasswordForm().validate_for_api() user = get_current_user() ok = user.change_password(form.old_password.data, form.new_password.data) if ok: db.session.commit() return Success(msg='密码修改成功') else: return Failed(msg='修改密码失败')