monkey/monkey_island/cc/auth.py

54 lines
1.4 KiB
Python
Raw Normal View History

2018-02-22 16:33:37 +08:00
from functools import wraps
2018-02-22 21:43:51 +08:00
from flask import current_app, abort
from flask_jwt import JWT, _jwt_required, JWTError
2018-02-22 16:33:37 +08:00
from werkzeug.security import safe_str_cmp
from cc.environment.environment import env
2018-02-22 16:33:37 +08:00
__author__ = 'itay.mizeretz'
class User(object):
2018-02-26 00:23:52 +08:00
def __init__(self, id, username, secret):
2018-02-22 16:33:37 +08:00
self.id = id
self.username = username
2018-02-26 00:23:52 +08:00
self.secret = secret
2018-02-22 16:33:37 +08:00
def __str__(self):
return "User(id='%s')" % self.id
def init_jwt(app):
users = env.get_auth_users()
username_table = {u.username: u for u in users}
userid_table = {u.id: u for u in users}
2018-02-22 16:33:37 +08:00
2018-02-26 00:23:52 +08:00
def authenticate(username, secret):
user = username_table.get(username, None)
2018-02-26 00:23:52 +08:00
if user and safe_str_cmp(user.secret.encode('utf-8'), secret.encode('utf-8')):
return user
2018-02-22 16:33:37 +08:00
def identity(payload):
user_id = payload['identity']
return userid_table.get(user_id, None)
2018-02-22 16:33:37 +08:00
if env.is_auth_enabled():
2018-02-22 16:33:37 +08:00
JWT(app, authenticate, identity)
def jwt_required(realm=None):
2018-02-22 21:43:51 +08:00
def wrapper(fn):
@wraps(fn)
def decorator(*args, **kwargs):
if env.is_auth_enabled():
2018-02-22 21:43:51 +08:00
try:
_jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
except JWTError:
abort(401)
return fn(*args, **kwargs)
return decorator
return wrapper