def decode_auth_token(auth_token): """ Decodes the auth token :param auth_token: :return: integer|string """ try: payload = jwt.decode(auth_token, create_app().config['SECRET_KEY']) return payload['sub'] except jwt.ExpiredSignatureError: return 'Signature expired. Please log in again.' except jwt.InvalidTokenError: return 'Invalid token. Please log in again.'
def encode_auth_token(user_id): """ Generates the Auth Token :return: string """ try: payload = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1), 'iat': datetime.datetime.utcnow(), 'sub': user_id } return jwt.encode( payload, create_app().config['SECRET_KEY'], algorithm='HS256' ) except Exception as e: return e
def user_login(): post_data = request.get_json() try: username = post_data.get('username') password = post_data.get('password') user = User.query.filter_by(username=username).first() if not user: response_object = { 'status': 'fail', 'message': 'User does not exist.' } return jsonify(response_object), 404 if not Bcrypt(create_app()).check_password_hash(user.password, password): response_object = { 'status': 'fail', 'message': 'Wrong password.' } return jsonify(response_object), 401 auth_token = User.encode_auth_token(user.user_id) if auth_token: response_object = { 'status': 'success', 'message': 'Successfully logged in.', 'auth_token': auth_token.decode() } return jsonify(response_object), 200 except Exception as e: print(e) response_object = { 'status': 'fail', 'message': 'Try again' } return jsonify(response_object), 500
from flask_testing import TestCase from pretenders import create_app, db app = create_app() class BaseTestCase(TestCase): """Base configuration""" TESTING = False SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = 'my_precious' def create_app(self): app.config.from_object('pretenders.config.TestingConfig') return app def setUp(self): db.create_all() db.session.commit() def tearDown(self): db.session.remove() db.drop_all()
def __init__(self, username, password): self.username = username self.password = Bcrypt(create_app()).generate_password_hash( password, create_app().config['BCRYPT_LOG_ROUNDS'] ).decode()