from flask_jwt import JWT, _default_jwt_payload_handler def authentication_not_implemented(username, password): raise NotImplemented() def identity(payload): return payload['identity'] def make_payload(identity): print("pase") result = _default_jwt_payload_handler(identity) result['identity'] = {'id': identity.id, 'username': identity.username} return result jwt = JWT(authentication_handler=authentication_not_implemented, identity_handler=identity) jwt.jwt_payload_handler(callback=make_payload)
def create_jwt(app): jwt = JWT(app, authenticate, identity) jwt.jwt_payload_handler(payload_handler)
app.config.from_object(config) for code in default_exceptions.iterkeys(): app.error_handler_spec[None][code] = make_json_error db.init_app(app) with app.app_context(): db.create_all() app.app_context().push() return app app = create_json_app(config.Config) # Set up security ------------------------------- security = Security(app, user_datastore) jwt = JWT(app, authenticate, jwt_identity) jwt.jwt_payload_handler(jwt_payload_handler) # Endpoints ------------------------------------- @app.route("/") @jwt_required() def index(): return "Hello World!" @app.route("/signup", methods=["POST"]) def signup(): # input validation here signup_request = request.get_json() # print "Signup info is: %s" % signup_request if validate_signup(signup_request): user = Student.query.filter_by(email=signup_request["email"]).first()
def identity(payload): user_id = int(payload['id']) return models.User[user_id] jwt = JWT(app, authenticate, identity) def make_payload(identity): iat = datetime.utcnow() exp = iat + current_app.config.get('JWT_EXPIRATION_DELTA') nbf = iat + current_app.config.get('JWT_NOT_BEFORE_DELTA') return {'exp': exp, 'iat': iat, 'nbf': nbf, 'id': identity.id} jwt.jwt_payload_handler(make_payload) # Route limiter exempts def is_admin(): try: return current_identity.admin except AttributeError: return False # Routes custom decorators def active_user_required(function): doc = 'Requires to be authentified as an active user' if function.__doc__: function.__doc__ += doc
from common.schema import ma from common.security import authenticate, identity, payload_handle, auth_url_rule, auth_url_options from resources.register import Register from resources.admin import AdminData from resources.nodetree import TreeRoot, TreeList, TreeEdit app = Flask(__name__) app.config.from_object('config') db.init_app(app) ma.init_app(app) api = Api(app) jwt = JWT(app, authenticate, identity) jwt.jwt_payload_handler(payload_handle) app.add_url_rule(auth_url_rule, **auth_url_options) api.add_resource(AdminData, '/admin') api.add_resource(Register, '/register') #tree root api.add_resource(TreeRoot, '/noderoot') #tree list api.add_resource(TreeList, '/nodetree/<string:node_uuid>') #tree edit api.add_resource(TreeEdit, '/node/<string:node_uuid>') if __name__ == '__main__': app.run(host=app.config['HOST'], port=app.config['PORT'], debug=app.config['DEBUG'])
@apiGroup Authorization @apiParam {String} username @apiParam {String} password @apiSuccess {String} access_token Authorization token for use it in other endpoints @apiError {String} 401 Invalid credentials @apiExample {curl} Example usage: curl -H "Content-Type: application/json" -XPOST http://127.0.0.1:5000/api/v1/auth -d '{ "username": "******", "password": "******"}' """ app.config['JWT_AUTH_URL_RULE'] = api_prefix + '/auth' app.config['JWT_EXPIRATION_DELTA'] = timedelta(hours=24) jwt = JWT(app, authenticate, identity) jwt.jwt_payload_handler(jwt_payload_handler) # TODO: uncomment if needed to pass token via URL parameter # jwt.request_handler(jwt_request_handler) # Admin UI app.register_blueprint(admin_ui) if __name__ == '__main__': print(os.getcwd()) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.DEBUG) app.logger.addHandler(stream_handler) # fix gives access to the gunicorn error log facility app.logger.handlers.extend(logging.getLogger("gunicorn.error").handlers) app.run(debug=True)
def init_auth(app): app.config['JWT_AUTH_URL_RULE'] = None app.config['JWT_EXPIRATION_DELTA'] = timedelta(days=7) app.config['JWT_AUTH_HEADER_PREFIX'] = 'JWT' jwt = JWT(app, None, identify) jwt.jwt_payload_handler(payload_handler)
from resources.users import UserManager, UserRegister from resources.project_info import Project from resources.project_mgr import ProjectMgr, ProjectCtl from resources.options import Options from resources.spider_ctl import SpiderCtl app = Flask(__name__) app.config.from_object('config.ProductionConfig') db.init_app(app) app.config['SECRET_KEY'] = 'mch_heat_map' app.config['JWT_AUTH_URL_RULE'] = '/apiserver/auth' app.config['JWT_EXPIRATION_DELTA'] = timedelta(seconds=36000) jwt = JWT(app, authen_callback, identity_callback) #jwt.auth_response_handler(response_callback) jwt.jwt_payload_handler(payload_callback) api = Api(app) api.add_resource(UserManager, '/apiserver/userinfo') api.add_resource(UserRegister, '/apiserver/userigister') api.add_resource(Project, '/apiserver/dataset') api.add_resource(Options, '/apiserver/options') api.add_resource(ProjectMgr, '/apiserver/project') api.add_resource(ProjectCtl, '/apiserver/project/<string:uuid>') api.add_resource(SpiderCtl, '/apiserver/task') if __name__ == '__main__': logpath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'log') if not os.path.exists(logpath): os.makedirs(logpath) handler = logging.FileHandler(os.path.join(logpath, 'apiserver.log'),