Exemple #1
0
def create_resource_server(app):
    require_oauth = ResourceProtector()
    BearerTokenValidator = create_bearer_token_validator(db.session, Token)
    require_oauth.register_token_validator(BearerTokenValidator())

    @app.route('/user')
    @require_oauth('profile')
    def user_profile():
        user = current_token.user
        return jsonify(id=user.id, username=user.username)

    @app.route('/user/email')
    @require_oauth('email')
    def user_email():
        user = current_token.user
        return jsonify(email=user.username + '@example.com')

    @app.route('/info')
    @require_oauth()
    def public_info():
        return jsonify(status='ok')

    @app.route('/acquire')
    def test_acquire():
        with require_oauth.acquire('profile') as token:
            user = token.user
            return jsonify(id=user.id, username=user.username)
Exemple #2
0
class AccountsOrgHandler(OrgHandler):
    def __init__(self, service, org_name):
        super(AccountsOrgHandler, self).__init__(service, org_name)
        self.users_db_config = self.dbs_config['users_db']
        self.users_db = self.store.db(
            db_name_suffix=self.users_db_config['name'])

        self.users_colln = self.users_db.get_collection(
            self.users_db_config['collections']['users'])
        self.oauth_colln = self.users_db.get_collection(
            self.users_db_config['collections']['oauth'])

        self.authlib_config = self.service.config['authlib']
        self.authlib_authorization_server = AuthorizationServer(
            self.authlib_config, self.oauth_colln, self.users_colln)

        bearer_validator = create_bearer_token_validator(self.oauth_colln)
        self.resource_protector = ResourceProtector()
        self.resource_protector.register_token_validator(bearer_validator())

    def initialize(self):
        self.users_colln.create_index(keys_dict={"email": 1},
                                      index_name="email")

        initial_agents_config = self.service.config["initial_agents"].copy()
        initial_agents_config['users']['root_admin'].update(
            self.org_config['root_admin'])

        logging.info("Add initial agents to the users db if they don't exist.")
        if initial_agents_config is None:
            return
        self.initial_agents = bootstrap_helper.bootstrap_initial_agents(
            self.users_colln, self.oauth_colln, initial_agents_config)
Exemple #3
0
def setup_oauth2_resource_protector(main_app: Flask):
    """
    Configure OAuth2 endpoints protector
    """
    BearerTokenValidator = create_bearer_token_validator(
        db.session, APIAccessToken)
    ResourceProtector.register_token_validator(BearerTokenValidator())
Exemple #4
0
    def __init__(self, service, org_name):
        super(AccountsOrgHandler, self).__init__(service, org_name)
        self.users_db_config = self.dbs_config['users_db']
        self.users_db = self.store.db(
            db_name_suffix=self.users_db_config['name'])

        self.users_colln = self.users_db.get_collection(
            self.users_db_config['collections']['users'])
        self.oauth_colln = self.users_db.get_collection(
            self.users_db_config['collections']['oauth'])

        self.authlib_config = self.service.config['authlib']
        self.authlib_authorization_server = AuthorizationServer(
            self.authlib_config, self.oauth_colln, self.users_colln)

        bearer_validator = create_bearer_token_validator(self.oauth_colln)
        self.resource_protector = ResourceProtector()
        self.resource_protector.register_token_validator(bearer_validator())
Exemple #5
0
def init_oauth() -> None:
    from app.service import oauth_service

    oauth_server.init_app(app,
                          query_client=oauth_service.get_client_by_id,
                          save_token=oauth_service.create_token)

    # TODO Remove in authlib 0.9, fixed lazy initialization
    # of client authentication.
    # See https://github.com/lepture/authlib/commit/afa9e43544a3575b06d97df27971d5698152bbac#diff-762725de53e7f2765188055295ed51da  # noqa
    oauth_server.authenticate_client = ClientAuthentication(
        oauth_service.get_client_by_id)

    oauth_server.register_grant(oauth_service.AuthorizationCodeGrant)
    oauth_server.register_grant(oauth_service.RefreshTokenGrant)
    oauth_server.register_grant(oauth_service.PasswordGrant)

    oauth_server.register_grant(grants.ImplicitGrant)
    oauth_server.register_endpoint(oauth_service.RevocationEndpoint)
    oauth_server.register_endpoint(oauth_service.IntrospectionEndpoint)

    ResourceProtector.register_token_validator(
        oauth_service.BearerTokenValidator())
def create_resource_server(app):
    query_token = create_query_token_func(db.session, Token)
    require_oauth = ResourceProtector(query_token)

    @app.route('/user')
    @require_oauth('profile')
    def user_profile():
        user = current_token.user
        return jsonify(id=user.id, username=user.username)

    @app.route('/user/email')
    @require_oauth('email')
    def user_email():
        user = current_token.user
        return jsonify(email=user.username + '@example.com')

    @app.route('/info')
    @require_oauth()
    def public_info():
        return jsonify(status='ok')
    def authenticate_refresh_token(self, refresh_token):
        token = OAuth2Token.query.filter_by(refresh_token=refresh_token).first()
        if token and not token.revoked and not token.is_refresh_token_expired():
            return token

    def authenticate_user(self, credential):
        return User.query.get(credential.user_id)


query_client = create_query_client_func(db.session, OAuth2Client)
save_token = create_save_token_func(db.session, OAuth2Token)
authorization = AuthorizationServer(
    query_client=query_client,
    save_token=save_token,
)
require_oauth = ResourceProtector()


def config_oauth(app):
    authorization.init_app(app)

    # support all grants
    authorization.register_grant(grants.ImplicitGrant)
    authorization.register_grant(grants.ClientCredentialsGrant)
    authorization.register_grant(AuthorizationCodeGrant)
    authorization.register_grant(PasswordGrant)
    authorization.register_grant(RefreshTokenGrant)

    # support revocation
    revocation_cls = create_revocation_endpoint(db.session, OAuth2Token)
    authorization.register_endpoint(revocation_cls)
Exemple #8
0
        db.session.delete(token)
        db.session.commit()


query_client = create_query_client_func(db.session, OAuth2Client)
authorization = AuthorizationServer(query_client=query_client)

# support all grants
authorization.register_grant_endpoint(AuthorizationCodeGrant)
authorization.register_grant_endpoint(ImplicitGrant)
authorization.register_grant_endpoint(PasswordGrant)
authorization.register_grant_endpoint(ClientCredentialsGrant)
authorization.register_grant_endpoint(RefreshTokenGrant)

# support revocation
authorization.register_revoke_token_endpoint(RevocationEndpoint)

# scopes definition
scopes = {
    'email': 'Access to your email address.',
    'connects': 'Access to your connected networks.'
}

# protect resource
query_token = create_query_token_func(db.session, OAuth2Token)
require_oauth = ResourceProtector(query_token=query_token)


def init_app(app):
    authorization.init_app(app)
Exemple #9
0
from authlib.specs.rfc6749 import grants
from authlib.common.security import generate_token

from authlib.flask.oauth2 import AuthorizationServer, ResourceProtector
from authlib.flask.oauth2.sqla import (create_revocation_endpoint,
                                       create_bearer_token_validator,
                                       create_query_client_func,
                                       create_save_token_func)

from extensions import db
from app.models import User, AuthorizationCode, Token, Client, PaymentAgreement

#Definitions
authorization = AuthorizationServer()
require_oauth = ResourceProtector()


class AuthorizationCodeGrant(grants.AuthorizationCodeGrant):
    def create_authorization_code(self, client, grant_user, request):
        # you can use other method to generate this code
        print(client.client_id)
        print(grant_user.id)
        code = generate_token(48)
        item = AuthorizationCode(
            code=code,
            client_id=client.client_id,
            redirect_uri=request.redirect_uri,
            scope=client.scope,
            user_id=grant_user.id,
        )
Exemple #10
0
import jwt
from authlib.flask.oauth2 import AuthorizationServer, ResourceProtector
from authlib.specs.rfc6749 import grants, InvalidGrantError, InvalidRequestError
from authlib.specs.rfc6750 import BearerTokenValidator
from flask import current_app

from ..exception import AccountLocked, PasswordNotMatch
from ..models import Organization, User, UserState
from ..util import timestamp

authorization = AuthorizationServer()
oauth = ResourceProtector()

def setup_oauth(app):
    authorization.init_app(app)

    authorization.register_grant(PasswordGrant)
    authorization.register_grant(RefreshTokenGrant)
    oauth.register_token_validator(JwtTokenValidator())

def create_token(subject, payload, exp_in=60, scope=None, token_use='access'):
    payload['token_use'] = token_use
    payload['sub'] = subject
    payload['iss'] = current_app.config['JWT_ISSUER']
    payload['iat'] = timestamp()
    payload['exp'] = payload['iat'] + exp_in

    payload['aud'] = 'registry-portal'
    if scope:
        payload['scope'] = scope
Exemple #11
0
# scopes definition
scopes = {
    'email': 'Access to your email address.',
}


class MyBearerTokenValidator(BearerTokenValidator):
    def authenticate_token(self, token_string):
        print('WAT    : token_string = %s' % token_string)
        return OAuth2Token.query.filter_by(access_token=token_string).first()

    def request_invalid(self, request):
        return False

    def token_revoked(self, token):
        token.revoked


# protect resource
query_token = create_query_token_func(db.session, OAuth2Token)
#require_oauth = ResourceProtector(query_token=query_token)
from authlib.flask.oauth2.sqla import create_bearer_token_validator

BearerTokenValidator = create_bearer_token_validator(db.session, OAuth2Token)
ResourceProtector.register_token_validator(BearerTokenValidator())
require_oauth = ResourceProtector()


def init_app(app):
    authorization.init_app(app)
Exemple #12
0
 def _factor_require_oauth():
     return ResourceProtector(Gateways._query_token)
Exemple #13
0
        username = session.get('username')
        if not username:
            return _make_redirect()

        user = User(username, None)
        if user:
            return authorization.create_authorization_response(grant_user=user)

    def issue_token(self):
        return authorization.create_token_response()


_token_validator = _BearerTokenValidator()

require_oauth = ResourceProtector()
require_oauth.register_token_validator(_token_validator)


def get_user_for_token(token) -> User:
    token = _token_validator(token, None, None)
    u = UserRepo.get_user(token.user_id)
    if not u:
        raise OAuth2Error('user not found for token')
    return u


def config_oauth(app):
    authorization.init_app(app)
    authorization.register_grant(AuthorizationCodeGrant)
    authorization.register_grant(RefreshTokenGrant)
Exemple #14
0
from authlib.flask.oauth2 import ResourceProtector
from authlib.flask.oauth2.sqla import create_bearer_token_validator
from recommender.extensions import db
from recommender.blueprints.user.models import Token

BearerTokenValidator = create_bearer_token_validator(db.session, Token)
auth_required = ResourceProtector()
auth_required.register_token_validator(BearerTokenValidator())