def test_adds_auth_endpoint(): app = Flask(__name__) app.config['SECRET_KEY'] = 'super-secret' app.config['JWT_AUTH_URL_RULE'] = '/auth' app.config['JWT_AUTH_ENDPOINT'] = 'jwt_auth' flask_jwt.JWT(app) rules = [str(r) for r in app.url_map._rules] assert '/auth' in rules
def test_custom_auth_handler(): def custom_auth_request_handler(): return jsonify({'hello': 'world'}) jwt = flask_jwt.JWT() pytest.deprecated_call(jwt.auth_request_handler, custom_auth_request_handler) app = Flask(__name__) jwt.init_app(app) with app.test_client() as c: resp, jdata = post_json(c, '/auth', {}) assert jdata == {'hello': 'world'}
def test_initialize(): app = Flask(__name__) app.config['SECRET_KEY'] = 'super-secret' jwt = flask_jwt.JWT(app) assert isinstance(jwt, flask_jwt.JWT) assert len(app.url_map._rules) == 2
import resources.item import resources.store import resources.user import security app = flask.Flask(__name__) #app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db' #heroku_db_url = os.environ.get('DATABASE_URL', 'sqlite:///data.db') app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///data.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.secret_key = 'a very long key' api = flask_restful.Api(app) # jwt creates endpoint /auth jwt = flask_jwt.JWT(app, security.authenticate, security.identity) # moved to run.py for heroku #@app.before_first_request #def create_tables(): # db.db.create_all() api.add_resource(resources.item.Item, '/item/<string:name>') api.add_resource(resources.item.Items, '/items') api.add_resource(resources.user.UserRegister, '/register') api.add_resource(resources.store.Store, '/store/<string:name>') api.add_resource(resources.store.StoreList, '/store') if __name__ == '__main__': import db db.db.init_app(app)
""" # find user with provided username and password user = User.query.filter(User.username == username).first() if user is None: raise ApiException('Authentication failed.') # check for correct password if not check_password_hash(user.password, password): raise ApiException('Authentication failed.') return user def jwt_identity(payload): """ Load an identity from the jwt payload """ return payload jwt = flask_jwt.JWT(app, jwt_authenticate, jwt_identity) def getUser(): return User.load(flask_jwt.current_identity.get('identity', None))
if user is not None and user.password == password: return user def identity(payload): """Get the identity from the JWT payload. """ User = hapcat.models.User userid = payload['identity'] return db.session.query(User).filter(User.id == userid).scalar() jwt = flask_jwt.JWT(app, authenticate, identity) @jwt.jwt_payload_handler def payload_handler(identity): """Transform the identity object into a payload. """ current_app = flask.current_app iat = datetime.datetime.utcnow() exp = iat + current_app.config.get('JWT_EXPIRATION_DELTA') nbf = iat + current_app.config.get('JWT_NOT_BEFORE_DELTA') identity = str(identity.id)
def jwt(): return flask_jwt.JWT()
import flask_jwt import user_API import camera_API import camera_user_API import vehicle_API import image_API import argparse import db import reports_API app = Flask(__name__) cors = CORS(app, resources={r"/*": {"origins": "*"}}) app.config['DEBUG'] = True app.config['SECRET_KEY'] = 'my_goat_has_thumbs' app.config['JWT_EXPIRATION_DELTA'] = datetime.timedelta(minutes=120) app.register_blueprint(camera_API.camera_api) app.register_blueprint(camera_user_API.camera_user_api) app.register_blueprint(user_API.user_api) app.register_blueprint(vehicle_API.vehicle_api) app.register_blueprint(image_API.image_api) app.register_blueprint(vehicle_API.vehicle_api) jwt = flask_jwt.JWT(app, user_API.authenticate, user_API.identity) parser = argparse.ArgumentParser() parser.add_argument('--db', help='IP address of MongoDB server') parser.add_argument('--host', help='IP address to bind API server to') db = db.db(parser.parse_args().db) if __name__ == '__main__': app.run(host=parser.parse_args().host, threaded=True)
Flask-JWT __init__.py has the CONFIG_DEFAULTS which are config keys ''' ''' This is called to authenticate, it is like the view ''' # @jwt.authentication_handler def authentication_handler(username, password): # user = User.query.filter_by(username=username).first() user = User.query.filter(User.username == username).scalar() if user.check_password(password): return user jwt = flask_jwt.JWT(app, authentication_handler=authentication_handler) # jwt.authentication_handler(authentication_handler) # jwt.auth_response_callback(jwt_response_handler) def jwt_error_handler(error): return jsonify({'success': False, 'full_messages': [str(error)]}), 400 # this will generate the JWT token(not the response) but the token that will be encoded # @jwt.identity_handler def payload_handler(identity): result = flask_jwt._default_jwt_payload_handler(identity) result.update({