def get_by_user(self, user: str): conn = self.db.get_connection() cur = conn.cursor() cur.execute("SELECT * FROM user where username='******'".format(user)) result = cur.fetchone() user = User(result[0], result[1]) return user
def logout(): '''Logout user. If sent token is valid, blacklist it (causing user logout). Returns: dict: returns dict with status. 400 status code if token is invalid. Example: { 'status': 'success' } ''' user_id = User.is_token_valid(request.headers) print(request.headers) if not user_id: return jsonify(ResponseMessages.INVALID_TOKEN.value), 400 blacklist_token = TokenBlacklist(token=request.headers.get('token')) db.session.add(blacklist_token) db.session.commit() return jsonify({ ResponseStrings.STATUS.value: ResponseStrings.SUCCESS.value, }), 200
def get_user_info(): '''Send information about user. If token in header is correct sends user information. Returns: dict: returns fict with information about user. 400 status code if token is invalid. ''' user_id = User.is_token_valid(request.headers) if not user_id: return jsonify(ResponseMessages.INVALID_TOKEN.value), 400 user = User.query.get(user_id) if not user: return jsonify({ ResponseStrings.STATUS.value: ResponseStrings.FAILED.value, ResponseStrings.MESSAGE.value: "You are not logged in" }), 400 return jsonify({ ResponseStrings.STATUS.value: ResponseStrings.SUCCESS.value, ResponseStrings.NAME.value: user.login, 'date': user.date_created }), 201
def insert_user(): uc.insert_user( User( username = request.form.get('username'), password = request.form.get('password') ) ) return "USER CREATED"
def register(): '''Register user with login and password. Login has min length of 3 symbols and password has 6 symbols. Login must also be unique. Returns: dict: returns dict with status, token and user name if user is registered successfully, otherwise send dict with status 'failed'. Example: { 'status': 'success', 'token': 'TokenString', 'name': 'admin' } ''' data = request.get_json() user = User.query.filter_by(login=data.get('login')).first() if user: return jsonify({ ResponseStrings.STATUS.value: ResponseStrings.FAILED.value, ResponseStrings.MESSAGE.value: 'Login is not unique' }), 400 if len(data.get('login')) < 3 and len(data.get('password')) < 6: return jsonify({ ResponseStrings.STATUS.value: ResponseStrings.FAILED.value, ResponseStrings.MESSAGE.value: "Credentials doesn't met requirements" }), 400 user = User(login=data.get('login'), password=data.get('password')) db.session.add(user) db.session.commit() token = user.encode_auth_token().decode('utf8') return jsonify({ ResponseStrings.STATUS.value: ResponseStrings.SUCCESS.value, ResponseStrings.TOKEN.value: token, ResponseStrings.NAME.value: user.login }), 201
def post(self): data = request.get_json() user = User.authenticate(**data) if not user: abort(401, message='Invalid credentials', authenticated=False) token = jwt.encode({ 'sub': user.email, 'iat': datetime.utcnow(), 'exp': datetime.utcnow() + timedelta(days=30) # TODO: This is a hack until the pythonanywhere server issue resolved }, os.getenv('SECRET_KEY') ) return jsonify({'token': token.decode('UTF-8')})
def manage_tournament(): '''Creates tournament or get summary info of all tournaments. Post methods expect tournament data. Example: { "name": "Grand Clash", } Returns: 201 status code with success message and tournament uuid. 400 status code if token or name is invalid. ''' if request.method == 'POST': user_id = User.is_token_valid(request.headers) if not user_id: return jsonify(ResponseMessages.INVALID_TOKEN.value), 400 name = request.json['name'] if not isinstance(name, str): return jsonify({ ResponseStrings.STATUS.value: ResponseStrings.FAILED.value, ResponseStrings.MESSAGE.value: "Invalid name" }), 400 tournament = Tournament( name=name, user_id=user_id, ) db.session.add(tournament) db.session.commit() return jsonify({ ResponseStrings.STATUS.value: ResponseStrings.SUCCESS.value, 'uuid': tournament.uuid, }), 201 if request.method == 'GET': tournaments = Tournament.query.all() result = [] for t in tournaments: participants = Participant.query.filter_by(tournament_id = t.id).all() result.append({ 'name': t.name, 'date': t.date, 'uuid': t.uuid, 'participants': len(participants) }) return jsonify(result)
def add(): data = request.get_json() if data is None: raise BadRequest() allow_fields = {'id', 'name', 'email', 'password'} if not data.keys() >= allow_fields: raise BadRequest() user = User(**data) saved = UserMapper.save(user) if not saved: raise Conflict(description='Failed add data') body = ApiResponseBody() body.message = 'created' body.result = True return ApiResponse(STATUS_CREATED, body)
def create_tx_account(args): app = App.query.get_or_404(args["app"]) user = User.create_for_email(args["email"], args["name"]) if user is None: raise ApiException("Could not create user account") if "card_token" in args.keys(): customer = stripe.Customer.create(source=args["card_token"], email=user.email) user.as_stripe_customer(customer) deposit = user.deposit(args["top_up"]) if deposit is None: raise ApiException("Could not deposit funds") payment = Payment.transfer(user, app, args["price"], 1) if payment is None: raise ApiException("Could not complete transfer") return {"success": True}
def login(): '''Authenticate user based on sent login and password. If password and login are correct generate and send token. Returns: dict: returns dict with status, token and user name if user is authenticated successfully, otherwise send dict with status 'failed' and message. Example: { 'status': 'success', 'token': 'TokenString', 'name': 'admin' } ''' data = request.get_json() user = User.query.filter_by(login=data.get('login')).first() invalid_credentials_response = jsonify({ ResponseStrings.STATUS.value: ResponseStrings.FAILED.value, ResponseStrings.MESSAGE.value: 'Credentials are not valid' }) if not user: return invalid_credentials_response, 400 is_valid = User.check_password(data.get('password'), user.password) if not is_valid: return invalid_credentials_response, 400 token = user.encode_auth_token().decode('utf8') return jsonify({ ResponseStrings.STATUS.value: ResponseStrings.SUCCESS.value, ResponseStrings.TOKEN.value: token, ResponseStrings.NAME.value: user.login }), 200
def edit(id): data = request.get_json() if data is None: raise BadRequest() allow_fields = {'id', 'name', 'email', 'password'} if not data.keys() >= allow_fields: raise BadRequest() is_exist = UserMapper.exist_user(id) if not is_exist: raise NotFound(description='Not exist user') user = User(**data) saved = UserMapper.save(user) if not saved: raise Conflict(description='Failed edit data') body = ApiResponseBody() body.message = 'edited' body.result = True return ApiResponse(STATUS_OK, body)
def decorated_function(*args, **kwargs): if "Authorization" not in request.headers: return f(None, *args, **kwargs) data = request.headers["Authorization"] token = str.replace(str(data), "Bearer ", "") decoded_token, error = validate(token) if decoded_token is None: raise ApiException( "Invalid auth token", status_code=401, payload={ "token": token, "error": error }, ) user, err = User.for_token(decoded_token) if user is None: raise ApiException("Unable to find or create user for token", status_code=500) return f(user, *args, **kwargs)
def get_user_info(self): d = BaseModel.to_dict(self) d["app"] = App.for_account(self.dest_account_id).to_dict() d["user"] = User.for_account(self.source_account_id).to_dict() return d
def load_data(db, app): with app.app_context(): user = User(login='******', password='******') db.session.add(user) db.session.commit()
def init_db(dataset_path, db): db.drop_all() db.create_all() dataset_name = os.path.split(dataset_path)[1] summaries_path = os.path.join(dataset_path, 'summaries') documents_path = os.path.join(dataset_path, 'documents') sanity_path = os.path.join(dataset_path, 'sanity') sanity_2_path = os.path.join(dataset_path, 'sanity_2') sanity_summ_path = os.path.join(dataset_path, 'sanity_summary') # Insert User user = User(email='admin@localhost', password='******') db.session.add(user) db.session.commit() # Insert dataset dataset = Dataset(name=dataset_name) db.session.add(dataset) db.session.commit() # Insert documents documents = [] for file in os.listdir(documents_path): file_path = os.path.join(documents_path, file) sanity_file_path = os.path.join(sanity_path, f"{file.split('.')[0]}.json") sanity_file_2_path = os.path.join(sanity_2_path, f"{file.split('.')[0]}.json") with open(file_path, 'r') as infile: sanity = open(sanity_file_path, 'r') sanity_2 = open(sanity_file_2_path, 'r') json_result = json.load(infile) sanity_json = json.load(sanity) sanity_2_json = json.load(sanity_2) documents.append( Document( dataset_id=dataset.id, doc_id=json_result['doc_id'], doc_json=json_result, sanity_statement=sanity_json['statement'], sanity_answer=sanity_json['answer'], sanity_statement_2=sanity_2_json['statement'], sanity_answer_2=sanity_2_json['answer'], )) sanity.close() sanity_2.close() db.session.bulk_save_objects(documents) db.session.commit() # Insert Summaries summaries = [] for folder in os.listdir(summaries_path): if folder.startswith('ref'): summary_group = SummaryGroup(name='%s_ref_%s' % (dataset_name, folder[4:]), dataset_id=dataset.id, is_ref=True) elif folder.startswith('system'): summary_group = SummaryGroup(name='%s_system_%s' % (dataset_name, folder[7:]), dataset_id=dataset.id, is_ref=False) else: break db.session.add(summary_group) db.session.commit() ref_path = os.path.join(summaries_path, folder) for file in os.listdir(ref_path): with open(os.path.join(ref_path, file), 'r') as infile: text = ' '.join(infile.readlines()).strip() document = db.session.query(Document)\ .filter_by(doc_id=os.path.splitext(file)[0]).first() summaries.append( Summary(doc_id=document.id, text=text, summary_group_id=summary_group.id)) db.session.bulk_save_objects(summaries) db.session.commit() # Insert sanity summaries sanity_summaries = [] for file in os.listdir(sanity_summ_path): file_path = os.path.join(sanity_summ_path, file) with open(file_path, 'r') as infile: json_infile = json.load(infile) sanity_summaries.append( SanitySummary(good_summary=json_infile['best'].lower(), mediocre_summary=json_infile['average'].lower(), bad_summary=json_infile['worst'].lower(), dataset_id=dataset.id)) db.session.bulk_save_objects(sanity_summaries) db.session.commit()
def get_all(self): conn = self.db.get_connection() cur = conn.cursor() cur.execute("SELECT * FROM user") return [User(i[0], i[1]) for i in cur.fetchall()]