Created
July 6, 2019 06:27
-
-
Save rscarrera27/846054f446ee0851954a8b587cdd5b2a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from sanic import Sanic | |
from sanic.response import json | |
from sanic.request import Request | |
from sanic_jwt_extended import ( | |
JWTManager, jwt_required, create_access_token, | |
create_refresh_token) | |
import uuid | |
from sanic_jwt_extended.tokens import Token | |
app = Sanic(__name__) | |
# Setup the Sanic-JWT-Extended extension | |
app.config['JWT_SECRET_KEY'] = 'super-secret' # Change this! | |
app.config['ACL_ENABLE'] = True | |
app.config['ACCESS_CONTROL_LEVEL'] = [ | |
"ADMIN" | |
"USER" | |
] | |
app.config["ACL_BLACKLIST_MODE"] = False | |
JWTManager(app) | |
@app.route('/login', methods=['POST']) | |
async def login(request: Request): | |
username = request.json.get('username', None) | |
password = request.json.get('password', None) | |
access_token = await create_access_token(identity=username, permission=random.choice(["ADMIN", "USER"]), app=request.app) | |
return json(dict(access_token=access_token), status=200) | |
@app.route('/admin-protected', methods=['GET']) | |
@jwt_required(acl=["ADMIN"]) # default to whitelist mode | |
async def protected(request: Request, token: Token): | |
# Access the identity of the current user with get_jwt_identity | |
current_user = token.jwt_identity | |
return json(dict(logined_as=current_user)) | |
@app.route('/user-protected', methods=['GET']) | |
@jwt_required(acl=["USER"]) # default to whitelist mode | |
async def protected(request: Request, token: Token): | |
# Access the identity of the current user with get_jwt_identity | |
current_user = token.jwt_identity | |
return json(dict(logined_as=current_user)) | |
if __name__ == '__main__': | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment