def single_race_endpoint(id): """GET end point to return a single race's information""" auth = Auth(app) if not auth.authenticate_request(): return auth.unauthorized_response() race = Race() single_race_query = race.get_race(id) single_race_participants = RaceParticipants( ).get_race_participants_race_id(id) if single_race_query: json = [] snails_id_list = [] for row in single_race_participants: snails_id_list.append(row.id_snail) json.append({ "id": single_race_query.id, "date": single_race_query.date, "status": single_race_query.status, "id_round": single_race_query.id_round, "id_snails": snails_id_list }) return json return { 'status': 'Failed', 'message': 'Race not found' }, status.HTTP_404_NOT_FOUND
def rounds_endpoint(): """GET end point to return rounds information""" auth = Auth(app) if not auth.authenticate_request(): return auth.unauthorized_response() round_model = Round() query_response = round_model.get_all_rounds() if query_response: json = [] for row in query_response: race_model = Race() race_ids = race_model.get_round_race_ids(row.id) json.append({ "id": row.id, "name": row.name, "start_date": row.start_date, "end_date": row.end_date, "races": [race_id.id for race_id in race_ids] }) return json return { 'status': 'Failed', 'message': 'Rounds not found' }, status.HTTP_404_NOT_FOUND
def races_endpoint(): """GET end point to return races information""" auth = Auth(app) if not auth.authenticate_request(): return auth.unauthorized_response() race = Race() race_query = race.get_all_races() all_race_participants = RaceParticipants() if race_query: json = [] for each_race in race_query: race_participants = all_race_participants.get_race_participants_race_id( each_race.id) snails_id_list = [] for row in race_participants: snails_id_list.append(row.id_snail) json.append({ "id": each_race.id, "date": each_race.date, "status": each_race.status, "id_round": each_race.id_round, "id_snails": snails_id_list }) return json return { 'status': 'Failed', 'message': 'Races not found' }, status.HTTP_404_NOT_FOUND
def single_snail_endpoint(id): """GET end point to return single snail information""" auth = Auth(app) if not auth.authenticate_request(): return auth.unauthorized_response() snail = Snail() query_response = snail.get_snail(id) if query_response is not None: trainer = Trainer() query_response_trainer = trainer.get_trainer(query_response.trainer_id) return { "id": query_response.id, "name": query_response.name, "trainer": { "id": query_response_trainer.id, "name": query_response_trainer.name } } return { 'status': 'Failed', 'message': 'Snail not found' }, status.HTTP_404_NOT_FOUND
def snails_endpoint(): """GET end point to return snails information""" auth = Auth(app) if not auth.authenticate_request(): return auth.unauthorized_response() snail = Snail() query_response = snail.get_all_snails() if query_response: trainer = Trainer() json = [] for row in query_response: query_response_trainer = trainer.get_trainer(row.trainer_id) json.append({ "id": row.id, "name": row.name, "trainer": { "id": query_response_trainer.id, "name": query_response_trainer.name } }) return json return { 'status': 'Failed', 'message': 'Snails not found' }, status.HTTP_404_NOT_FOUND
def create_app(): app = Flask(__name__) app.debug = True app.secret_key = "secret_key" # 设置配置文件 app.config['SESSION_TYPE'] = 'redis' # 注册蓝图 app.register_blueprint(account) # app.register_blueprint(user) app.register_blueprint(main) # # @app.before_request # def check_login(): # print('定义验证方法') # 注册组件 # 为Flask-session组件提供的配置 app.config['SESSION_TYPE'] = 'redis' # session类型为redis app.config['SESSION_REDIS'] = redis.Redis(host='47.93.252.50', port='6379', password='******') # 用于连接redis的配置 app.config['SESSION_KEY_PREFIX'] = 'session:' # 保存到session中的值的前缀 app.config['SESSION_PERMANENT'] = False # 如果设置为True,则关闭浏览器session就失效。 app.config['SESSION_USE_SIGNER'] = False # 是否对发送到浏览器上 session:cookie值进行加密 Session(app) #Auth验证 Auth(app) return app
def single_result_endpoint(id): """GET end point to return single result information""" auth = Auth(app) if not auth.authenticate_request(): return auth.unauthorized_response() return single_result_json(id)
def results_endpoint(): """GET end point to return results information""" auth = Auth(app) if not auth.authenticate_request(): return auth.unauthorized_response() return results_json()
def auth_token(): """Endpoint to retrieve an Authorization token. Returns: JSON -- Containing 'token' key with corresponding Authorization token. """ try: auth = Auth(app) token = auth.encode_auth_token() return make_response({"token": token.decode('utf-8')}), status.HTTP_200_OK except Exception as e: return e
def create_app(): app = Flask(__name__) app.secret_key = "lmw" # 设置配置文件 app.config.from_object("config.DevelopmentConfig") db.init_app(app) Auth(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) return app
def create_app(): app = Flask(__name__) app.debug = True app.secret_key = 'sdiusdfsdf' # 设置配置文件 app.config.from_object('settings.DevelopmentConfig') # 注册蓝图 app.register_blueprint(account) app.register_blueprint(user) app.register_blueprint(main) # 注册组件 # Session(app) Auth(app) return app
def create_app(): app = Flask(__name__) app.debug = True app.secret_key = 'sdiusdfsdf' # 设置配置文件 app.config.from_object('settings.DevelopmentConfig') # 注册蓝图 app.register_blueprint(account) app.register_blueprint(user) app.register_blueprint(main) # # @app.before_request # def check_login(): # print('定义验证方法') # 注册组件 Session(app) Auth(app) return app
def create_app(): app = Flask(__name__) app.debug = True #session秘钥 app.secret_key = 'ctz12345' #配置文件 app.config.from_object('settings.BaseConfig') #注册蓝图 app.register_blueprint(acount.count) app.register_blueprint(operate.op) app.register_blueprint(user.user) app.register_blueprint(order.order) #注册Auth组件 Auth(app) #注册flask_sqlalchemy db.init_app(app) return app
def snails_endpoint(id): """Endpoint to get information for a round with specified id. Retrieves the round information in json format for the specified id. Args: id (int): The id of the requested round. Returns: JSON: The json representation of the round with specified id. """ auth = Auth(app) if not auth.authenticate_request(): return auth.unauthorized_response() round_model = Round() query_response = round_model.get_round(id) if query_response: race_model = Race() race_ids = race_model.get_round_race_ids(query_response.id) return { "id": query_response.id, "name": query_response.name, "start_date": query_response.start_date, "end_date": query_response.end_date, "races": [race_id.id for race_id in race_ids] } return { 'status': 'Failed', 'message': 'Round id: %s not found' % id }, status.HTTP_404_NOT_FOUND
def setUp(self): self.auth = Auth(app)
import os from flask import Flask from flask_restful import Resource, Api from api.api import RegisterUser, LoginAPI from flask_cors import CORS from auth.auth import Auth from database.database import Database app = Flask(__name__) api = Api(app) CORS(app) token_auth = Auth() # Connect to db try: Database.init_db() except Exception as e: print(e) print("Could not initialise database") class HomeRoute(Resource): def get(self): return "Hello World" api.add_resource(HomeRoute, '/') # LoginAPI api.add_resource(LoginAPI, '/session', resource_class_args=(token_auth,)) api.add_resource(RegisterUser, '/user')
class LoginAPI(Resource): """ Pbench API for User Login or generating an auth token """ def __init__(self, auth): self.auth = auth self.token_expire_duration = "200" @Auth.token_auth.login_required(optional=True, f=Auth().verify_auth()) def post(self): """ Post request for logging in user. The user is allowed to re-login multiple times and each time a new valid auth token will be provided. This requires a JSON data with required user metadata fields { "username": "******", "password": "******", } Required headers include Content-Type: application/json Accept: application/json :return: JSON Payload if we succeed to decrypt the password hash, the returned response_object will include the auth_token response_object = { "status": "success", # will not present if failed "message": "Successfully logged in."/"failure message", "auth_token": auth_token.decode(), # Will not present if failed } """ post_data = request.get_json() if not post_data: print("Invalid json object: {}", request.url) abort(400, message="Invalid json object in request") username = post_data.get("username") if not username: print("Username not provided during the login process") abort(400, message="Please provide a valid username") password = post_data.get("password") if not password: print("Password not provided during the login process") abort(400, message="Please provide a valid password") # Query the database try: user = UserModel.query.filter_by(username=username).first() except Exception as e: print(e) abort(500, message="INTERNAL ERROR") if not user: print( "No user found in the db for Username: {} while login", username ) abort(403, message="No such user, please register first") # Validate the password try: check_password_hash(user.password, password) except Exception as e: print(e) abort(401, message="Bad login") # if not check_password_hash(user.password, password.encode('utf-8')): # print("Wrong password for user: {} while login", username) # abort(401, message="Bad login") try: auth_token = self.auth.encode_auth_token( self.token_expire_duration, user.id ) except ( jwt.InvalidIssuer, jwt.InvalidIssuedAtError, jwt.InvalidAlgorithmError, jwt.PyJWTError, ): print( "Could not encode the JWT auth token for user: {} while login", username ) abort( 500, message="INTERNAL ERROR", ) # Add the new auth token to the database for later access try: token = ActiveTokens(token=auth_token.decode()) token.user_id = user.id # TODO: Decide on the auth token limit per user # Adds a token for the user. Database.db_session.add(token) Database.db_session.commit() # user.query.update({user.auth_tokens: token}) print("New auth token registered for user {}", user.email) except IntegrityError: print( "Duplicate auth token got created, user might have tried to re-login immediately" ) abort(409, message="Retry login after some time") except SQLAlchemyError as e: print( "SQLAlchemy Exception while logging in a user {}", type(e) ) abort(500, message="INTERNAL ERROR") except Exception: print("Exception while logging in a user") abort(500, message="INTERNAL ERROR") response_object = { "status": "success", "message": "Successfully logged in.", "auth_token": auth_token.decode(), } return make_response(jsonify(response_object), 200)