Exemplo n.º 1
0
    def post(self):
        """
        @api {post} /v1/login 登录
        @apiName login
        @apiGroup login
        @apiDescription 进行操作之前需要登录
        @apiVersion 1.0.0

        @apiParamExample {json} Request-Example:
        {
            "username":"******",
            "password":"******"
        }

        @apiErrorExample {json} Error-Response:
            HTTP/1.1 500 ERROR
            {
                "msg": "File not found"
            }
        """
        data = request.get_json()
        username = data.get(app.config.get('JWT_AUTH_USERNAME_KEY'), None)
        password = data.get(app.config.get('JWT_AUTH_PASSWORD_KEY'), None)
        criterion = [username, password, len(data) == 2]
        if not all(criterion):
            raise JWTError('Bad Request', 'Invalid credentials')

        identity = jwt.authentication_callback(
            User, username, util.md5(password))
        if identity:
            access_token = jwt.jwt_encode_callback(identity)
            return jwt.auth_response_callback(access_token, identity)
        else:
            raise JWTError('Bad Request', 'Invalid credentials')
Exemplo n.º 2
0
def jwt_required_handler(*args, **kwargs):
    """Does the actual work of verifying the JWT data in the current request.
    This is done automatically for you by `jwt_required()` but you could call it manually.
    Doing so would be useful in the context of optional JWT access in your APIs.

    :param realm: an optional realm
    """
    if 0 < len(args):
        realm = args[0]
    elif 'realm' in kwargs:
        realm = kwargs['realm']
    else:
        realm = app.config['JWT_DEFAULT_REALM']

    if 1 < len(args):
        roles = args[1]
    elif 'roles' in kwargs:
        roles = kwargs['roles']
    else:
        roles = None

    if 2 < len(args):
        soft = args[1]
    elif 'soft' in kwargs:
        soft = kwargs['soft']
    else:
        soft = False

    token = jwt.request_callback()

    if token is None:
        if soft:
            jwt.current_identity = None
            _request_ctx_stack.top.current_identity = identity = None
            return
        else:
            raise JWTError('Authorization Required', 'Request does not contain an access token',
                           headers={'WWW-Authenticate': 'JWT realm="{}"'.format(realm)})

    try:
        payload = jwt.jwt_decode_callback(token)
    except pyjwt.InvalidTokenError as e:
        raise JWTError('Invalid token', str(e))

    if roles and 'role' in payload:
        role = payload['role']

        identity_role = _force_iterable(role)
        roles = _force_iterable(roles)

        if not identity_role or not set(roles).intersection(identity_role):
            raise JWTError('Bad Request', 'Permission Denied')
    jwt.current_identity = jwt.identity_callback(payload)
    _request_ctx_stack.top.current_identity = identity = jwt.current_identity

    if identity is None:
        raise JWTError('Invalid JWT', 'User does not exist')
Exemplo n.º 3
0
def authenticate(username, password):
    data = json.loads(request.data)
    user = User.get(username=username)
    if not (user and safe_str_cmp(user.password.encode('utf-8'),
                                  User.cypher(password).encode('utf-8'))):
        return

    if 'group' in data and data['group'] != user.group:
        raise JWTError('Bad Request', 'Invalid group')

    if not user.enable:
        raise JWTError('Bad Request', 'Removed user')

    user.ref_id = str(user.ref_id)
    return user
Exemplo n.º 4
0
 def authenticate(phonenum, password):
     print(phonenum)
     print(password)
     userInfo = User.get(User, phonenum)
     if (userInfo is None):
         raise JWTError('Bad credentials',
                        'User not found!',
                        status_code=404)
     else:
         if safe_str_cmp(userInfo.password.encode('utf-8'), password.encode('utf-8')):
             return userInfo
         else:
             raise JWTError('Bad credentials',
                            'Incorrect password!',
                            status_code=404)
Exemplo n.º 5
0
def auth_request_handle():
    data = request.get_json()
    username    = data.get(current_app.config.get('JWT_AUTH_USERNAME_KEY'), None)
    password    = data.get(current_app.config.get('JWT_AUTH_PASSWORD_KEY'), None)
    user_type   = data.get('user_type', None)
    criterion = [username, password, user_type, len(data) == 3]

    if not all(criterion):
        raise JWTError('Bad Request', 'Invalid credentials')

    identity = _jwt.authentication_callback(username, password, user_type)

    if identity:
        access_token = _jwt.jwt_encode_callback(identity)
        return _jwt.auth_response_callback(access_token, identity)
    else:
        raise JWTError('Bad Request', 'Invalid credentials')
Exemplo n.º 6
0
 def wrapped_function(*args, **kwargs):
     resource_id = request.path.split('/')[-1]
     resource = model.query.filter_by(id=resource_id).first()
     if current_identity.id != resource.user.id and current_identity.nivel != 'Admin':
         raise JWTError(
             'Acceso no permitido',
             'No tiene suficientes privilegios para acceder al recurso')
     return fn(*args, **kwargs)
Exemplo n.º 7
0
def costum_header_name():
    auth_header_value = request.headers.get('JWTAuthorization', None)
    auth_header_prefix = app.config['JWT_AUTH_HEADER_PREFIX']

    if not auth_header_value:
        return

    parts = auth_header_value.split()

    if parts[0].lower() != auth_header_prefix.lower():
        raise JWTError('Invalid JWT header', 'Unsupported authorization type')
    elif len(parts) == 1:
        raise JWTError('Invalid JWT header', 'Token missing')
    elif len(parts) > 2:
        raise JWTError('Invalid JWT header', 'Token contains spaces')

    return parts[1]
Exemplo n.º 8
0
def jwt_auth_request_handler():
    data = request.get_json()
    username = data.get(app.config.get('JWT_AUTH_USERNAME_KEY'), None)
    password = data.get(app.config.get('JWT_AUTH_PASSWORD_KEY'), None)
    id_token = data.get('id_token', None)

    if username and password:
        identity = authenticate_username(username, password)
    elif id_token:
        identity = authenticate_id_token(id_token)
    else:
        raise JWTError('Bad Request', 'Invalid credentials')

    if identity:
        access_token = jwt.jwt_encode_callback(identity)
        return jwt.auth_response_callback(access_token, identity)
    else:
        raise JWTError('Bad Request', 'Invalid credentials')
Exemplo n.º 9
0
def login():
    data = request.get_json()
    username = data.get(app.config.get('JWT_AUTH_USERNAME_KEY'), None)
    password = data.get(app.config.get('JWT_AUTH_PASSWORD_KEY'), None)
    identity = jwt.authentication_callback(username, password)
    if identity:
        token = jwt.jwt_encode_callback(identity)
        return jwt.auth_response_callback(token, identity)
    raise JWTError('Bad Request', 'Invalid credentials')
Exemplo n.º 10
0
 def decorator(*args, **kwargs):
     try:
         _jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
         print(current_identity)
         if admin == 1 and current_identity.is_admin!=1:
             abort(401)
     except Exception as e:
         raise JWTError('Bad Request', 'Invalid credentials')
     return fn(*args, **kwargs)
Exemplo n.º 11
0
    def load_token():
        try:
            token = request.headers.get('Authorization', None)
            if not token:
                raise Exception("Unauthorized")

            return token
        except Exception as e:
            raise JWTError(description='Error', error=e)
Exemplo n.º 12
0
 def wrapper(*args, **kwargs):
     if not flask_user.access.is_authenticated():
         raise JWTError('Authorization Required',
                        'Request does not contain an access token',
                        headers={
                            'WWW-Authenticate':
                            'JWT realm="%s"' %
                            app.config['JWT_DEFAULT_REALM']
                        })
     return f(*args, **kwargs)
Exemplo n.º 13
0
    def authenticate(**kwargs):

        try:
            account = kwargs.get('username', None)
            password = kwargs.get('password', None)

            if account is None:
                raise JWTError('Bad Request', '请输入用户名')

            user = dao.UserDao.get(query={'account': account})
            if not user:
                raise JWTError('Bad Request', '未找到此用户')

            password_hash = user['password']
            if not check_password_hash(password_hash, password):
                raise JWTError('Bad Request', '用户名或密码错误')
            return dict(user)
        except (OperationalError, IntegrityError) as e:
            raise JWTError('Bad Request', str(e))
Exemplo n.º 14
0
        def decorator(*args, **kwargs):
            authorities = current_identity['user_client_authorities']
            print(authority)
            if authority in authorities:
                print(authorities)
            else:
                raise JWTError('Invalid user authority',
                               "User doesn't have the required authority")

            return fn(*args, **kwargs)
Exemplo n.º 15
0
def do_login():
    username = request.form.get("email")
    password = request.form.get("password")

    identity = jwt.authentication_callback(username, password)

    if identity:
        access_token = jwt.jwt_encode_callback(identity)
        return jwt.auth_response_callback(access_token, identity)
    else:
        raise JWTError('Bad Request', 'Invalid credentials')
Exemplo n.º 16
0
    def auth_request():
        data = request.get_json()
        _jwt = LocalProxy(lambda: current_app.extensions['jwt'])

        identity_data = _jwt.authentication_callback(**data)

        if identity_data:
            access_token = _jwt.jwt_encode_callback(identity_data)
            return _jwt.auth_response_callback(access_token, identity_data)
        else:
            raise JWTError('Bad Request', '用户或密码错误')
Exemplo n.º 17
0
def login():
    if current_identity:
        return utils.json_abort({'message': 'User has already logged in'}, 400)
    data = request.get_json(force=True)
    if isinstance(data, str):
        data = json.loads(data)
    username = data.get('username', None)
    password = data.get('password', None)

    if not username or not password:
        raise JWTError('Bad Request', 'Invalid credentials')

    identity = authenticate(username, password)

    jwt = utils.get_jwt()
    if identity:
        access_token = jwt.jwt_encode_callback(identity)
        return jwt.auth_response_callback(access_token, identity)
    else:
        raise JWTError('Bad Request', 'Invalid credentials')
Exemplo n.º 18
0
def authenticate(username: str, password: str) -> typing.Optional[User]:
    user = UserCRUD.get_by_login(db.session, username)

    if user and user.check_password(password):

        if not user.internal_auth or not UserCRUD.is_global_active(
                db.session, user.id):
            raise JWTError("Forbidden",
                           "Internal authentication not accepted",
                           status_code=403)
        return user
Exemplo n.º 19
0
    def post(self):
        """Authenticates and generates a token."""
        args = parser.parse_args()
        data = request.get_json(force=True)
        username = args.get('email')
        password = args.get('password')
        criterion = [username, password, len(data) == 2]

        if not all(criterion):
            raise JWTError('Bad Request', 'Invalid credentials')

        identity = _jwt.authentication_callback(username, password)
        if identity is not None:
            user = User.objects.get(id=identity.id)

        if identity and user and user.active:
            access_token = _jwt.jwt_encode_callback(identity)
            token = {"token": access_token}
            return token
        else:
            raise JWTError('Bad Request', 'Invalid credentials')
Exemplo n.º 20
0
def auth_request_handler():
    data = request.get_json()
    username = data.get('username', None)
    password = data.get('password', None)

    identity = jwt.authentication_callback(username, password)

    if identity:
        access_token = jwt.jwt_encode_callback(identity)
        return jwt.auth_response_callback(access_token, identity)
    else:
        raise JWTError('Bad Request', 'Invalid credentials')
Exemplo n.º 21
0
    def decode_auth_token(token):
        try:
            # decode the token by the secrete key
            decoded = pyjwt.decode(token,
                                   ConfigClass.SECRET_KEY,
                                   algorithms=['HS256'])
            return decoded
        except Exception as e:
            raise JWTError(description='Error', error=e)

        # currently just username
        return token
Exemplo n.º 22
0
        def decorator(*args, **kwargs):
            token = _jwt.request_callback()

            if token is None:
                raise JWTError('Authorization Required', 'Request does not contain an access token',
                               headers={'WWW-Authenticate': 'JWT realm="%s"' % realm})

            try:
                payload = _jwt.jwt_decode_callback(token)
            except jwt.InvalidTokenError as e:
                raise JWTError('Invalid token', str(e))

            identity = _jwt.identity_callback(payload)
            if user_type == 'student' and isinstance(identity, Student):
                return fn(*args, **kwargs)
            elif user_type == 'teacher' and isinstance(identity, Teacher):
                return fn(*args, **kwargs)
            # NOTE - By default JWTError throws 401. We needed 404. Hence status_code=404
            raise JWTError('Unauthorized',
                           'You are unauthorized to request the api or access the resource',
                           status_code=404)
def authenticate(username, password):
    user = student_users.find_one({"username": username})
    user_type = "student"
    if user is None:
        user = instructor_users.find_one({"username": username})
        user_type = "instructor"
    elif teams.find_one({"liason": username}):
        user_type = "liason"
    if user:
        user['type'] = user_type
        passMatch = bcrypt.hashpw(
            password.encode('utf-8'), user['password'].encode(
                'utf-8')) == user['password'].encode('utf-8')
        if passMatch:
            return user
        else:
            raise JWTError('Bad credentials',
                           'Incorrect password!',
                           status_code=404)
    else:
        raise JWTError('Bad credentials', 'User not found!', status_code=404)
Exemplo n.º 24
0
        def decorator(*args, **kwargs):
            _jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
            if current_identity.admin:
                return fn(*args, **kwargs)

            raise JWTError(
                    'Authorization Required', 
                    'You are not admin',
                    headers={
                       'WWW-Authenticate': 'JWT realm="%s"' %current_app.config['JWT_DEFAULT_REALM']
                    }
                )
Exemplo n.º 25
0
def jwt_request_handler():
    auth_header_value = request.headers.get('Authorization', None)
    auth_header_prefix = current_app.config['JWT_AUTH_HEADER_PREFIX']

    # If no header, try extracting token from the 'token' parameter
    if not auth_header_value:
        token = request.args.get('token')
        if token: auth_header_value = '{} {}'.format(auth_header_prefix, token)

    if not auth_header_value:
        return

    parts = auth_header_value.split()

    if parts[0].lower() != auth_header_prefix.lower():
        raise JWTError('Invalid JWT header', 'Unsupported authorization type')
    elif len(parts) == 1:
        raise JWTError('Invalid JWT header', 'Token missing')
    elif len(parts) > 2:
        raise JWTError('Invalid JWT header', 'Token contains spaces')

    return parts[1]
Exemplo n.º 26
0
def identity(payload: dict) -> typing.Optional[User]:
    user_id = payload["identity"]

    user = User.query.get(user_id)

    if not user.internal_auth or not UserCRUD.is_global_active(
            db.session, user.id):
        raise JWTError(
            "Forbidden",
            "Internal identity and authorization not accepted",
            status_code=403,
        )

    return user
Exemplo n.º 27
0
def request_handler():
    auth_header_value = request.headers.get('Authorization', None)
    auth_header_prefix = current_app.config['JWT_AUTH_HEADER_PREFIX']

    if auth_header_value is None and request.args.get('token',
                                                      None) is not None:
        logging.info(request.args.get('token', ''))
        auth_header_value = auth_header_prefix + ' ' + request.args.get(
            'token', '')

    if auth_header_value is None:
        return None

    parts = auth_header_value.split()

    if parts[0].lower() != auth_header_prefix.lower():
        raise JWTError('Invalid JWT header', 'Unsupported authorization type')
    elif len(parts) == 1:
        raise JWTError('Invalid JWT header', 'Token missing')
    elif len(parts) > 2:
        raise JWTError('Invalid JWT header', 'Token contains spaces')

    return parts[1]
Exemplo n.º 28
0
def jwt_auth():
    assertion = request.values.get('assertion')
    segments = assertion.split('.')

    payload = json.loads(_urlsafe_b64decode(segments[1]).decode('utf-8'))
    service_account = JwtUser.get(payload['iss'])

    if not service_account:
        raise JWTError('Bad Request', 'Invalid service account')

    jwt.decode(assertion,
               service_account.public_key,
               algorithms=['RS256'],
               options=dict(verify_aud=False))

    identity = User.get_by_id(payload['sub'])

    access_token = flask_jwt.jwt_encode_callback(identity)
    return flask_jwt.auth_response_callback(access_token, identity)
Exemplo n.º 29
0
    def check_authorization(self):
        # get view class
        try:
            _class = self.get_class()
        except NotImplementedError:
            return False

        # get user data
        if current_identity:
            user = current_identity.get_dict()
            organization = current_identity.organization
        else:
            return False

        # form policy key
        policy = '{}:{}'.format(_class.__name__.lower(), self.action)
        # get policies and update them with organization level overrides
        policies = current_app.config.get('DEFAULT_POLICIES', {})
        if hasattr(organization, 'policy') and organization.policy:
            policies.update(organization.policy)

        try:
            policy_value = policies[policy]
        except KeyError:
            current_app.logger.error('Unknown policy {}'.format(policy))
            return False

        # evaluate user permissions
        # if there are multiple objects, filter out those which current user
        # doesn't have access to
        if isinstance(self.obj, list):
            allowed = []
            for obj in self.obj:
                if is_authorized(user, policy_value, resource=obj):
                    allowed.append(obj)
            self.obj = allowed
        # if there is single object raise if user doesn't have access to it
        else:
            if not is_authorized(user, policy_value, resource=self.obj):
                raise JWTError(
                    'Insufficient permissions',
                    'Your user account is lacking the necessary '
                    'permissions to perform this operation')
Exemplo n.º 30
0
    def check_authorization(self):
        # get user data
        if current_identity:
            user = current_identity.get_dict()
        else:
            return False

        policy_value = self.get_policy_value()
        if not policy_value:
            return False

        if isinstance(self.obj, list):
            allowed = []
            for obj in self.obj:
                if is_authorized(user, policy_value, resource=obj):
                    allowed.append(obj)
            self.obj = allowed
        # if there is single object raise if user doesn't have access to it
        else:
            if not is_authorized(user, policy_value, resource=self.obj):
                raise JWTError('Insufficient permissions',
                               'Your user account is lacking the necessary '
                               'permissions to perform this operation')