示例#1
0
def create_oauth2_client(
        context,
        username,
        client_id,
        client_secret,
        default_scopes=None
    ):
    """
    Create a new OAuth2 Client associated with a given user (username).
    """
    from app.modules.users.models import User
    from app.modules.auth.models import OAuth2Client

    user = User.query.first(User.username == username)
    if not user:
        raise Exception("User with username '%s' does not exist." % username)

    if default_scopes is None:
        from app.extensions.api import api_v1
        default_scopes = ' '.join(api_v1.authorizations['oauth2_password']['scopes'])

    oauth2_client = OAuth2Client(
        client_id=client_id,
        client_secret=client_secret,
        user=user,
        _default_scopes=default_scopes
    )

    from app.extensions import db
    db.session.add(oauth2_client)
    db.session.commit()
示例#2
0
文件: users.py 项目: hwindsor/houston
def create_oauth2_client(context, email, guid, secret, default_scopes=None):
    """
    Create a new OAuth2 Client associated with a given user (email).
    """
    from app.modules.users.models import User
    from app.modules.auth.models import OAuth2Client

    user = User.query.filter(User.email == email).first()
    if not user:
        raise Exception("User with email '%s' does not exist." % email)

    if default_scopes is None:
        from app.extensions.api import api_v1

        default_scopes = list(
            api_v1.authorizations['oauth2_password']['scopes'].keys())

    oauth2_client = OAuth2Client(
        guid=guid,
        secret=secret,
        user=user,
        default_scopes=default_scopes,
    )

    from app.extensions import db

    with db.session.begin():
        db.session.add(oauth2_client)
示例#3
0
def regular_user_oauth2_client(regular_user, temp_db_instance_helper):
    # pylint: disable=invalid-name,unused-argument
    from app.modules.auth.models import OAuth2Client

    for _ in temp_db_instance_helper(
            OAuth2Client(user=regular_user,
                         client_id='regular_user_client',
                         client_secret='regular_user_secret',
                         redirect_uris=[],
                         default_scopes=[])):
        yield _
def init_auth(docs_user):
    # TODO: OpenAPI documentation has to have OAuth2 Implicit Flow instead
    # of Resource Owner Password Credentials Flow
    oauth2_client = OAuth2Client(
        client_id='documentation',
        client_secret='KQ()SWK)SQK)QWSKQW(SKQ)S(QWSQW(SJ*HQ&HQW*SQ*^SSQWSGQSG',
        user_id=docs_user.id,
        _default_scopes=' '.join(
            api.api_v1.authorizations['oauth2_password']['scopes']))
    db.session.add(oauth2_client)
    db.session.commit()
    return oauth2_client
def init_auth(docs_user):
    # TODO: OpenAPI documentation has to have OAuth2 Implicit Flow instead
    # of Resource Owner Password Credentials Flow
    with db.session.begin():
        oauth2_client = OAuth2Client(
            guid=DOCUMENTATION_CLIENT_GUID,
            secret=DOCUMENTATION_CLIENT_SECRET,
            user_guid=docs_user.guid,
            redirect_uris=[],
            default_scopes=api.api_v1.authorizations['oauth2_password']
            ['scopes'],
        )
        db.session.add(oauth2_client)
    return oauth2_client
def init_auth(docs_user):
    # TODO: OpenAPI documentation has to have OAuth2 Implicit Flow instead
    # of Resource Owner Password Credentials Flow
    with db.session.begin():
        oauth2_client = OAuth2Client(
            client_id='documentation',
            client_secret=
            'KQ()SWK)SQK)QWSKQW(SKQ)S(QWSQW(SJ*HQ&HQW*SQ*^SSQWSGQSG',
            user_id=docs_user.id,
            scope=api.api_v1.authorizations['oauth2_password']['scopes'],
            default_scopes=api.api_v1.authorizations['oauth2_password']
            ['scopes'])
        oauth2_client.redirect_uris = []
        db.session.add(oauth2_client)
    return oauth2_client
def regular_user_oauth2_client(regular_user, db):
    # pylint: disable=invalid-name,unused-argument
    from app.modules.auth.models import OAuth2Client

    admin_oauth2_client_instance = OAuth2Client(
        user=regular_user,
        client_id='regular_user_client',
        client_secret='regular_user_secret',
        redirect_uris=[],
        default_scopes=[])

    db.session.add(admin_oauth2_client_instance)
    db.session.commit()
    yield admin_oauth2_client_instance
    db.session.delete(admin_oauth2_client_instance)
    db.session.commit()
示例#8
0
    def open(self, *args, **kwargs):
        if self._user is not None:
            from app.extensions import db
            from app.modules.auth.models import OAuth2Client, OAuth2Token

            oauth2_client = OAuth2Client(
                secret='SECRET',
                user=self._user,
                default_scopes=[],
            )

            oauth2_bearer_token = OAuth2Token(
                client=oauth2_client,
                user=self._user,
                token_type='Bearer',
                access_token='test_access_token',
                scopes=self._auth_scopes,
                expires=datetime.utcnow() + timedelta(days=1),
            )

            with db.session.begin():
                db.session.add(oauth2_bearer_token)

            extra_headers = ((
                'Authorization',
                '{token.token_type} {token.access_token}'.format(
                    token=oauth2_bearer_token),
            ), )
            if kwargs.get('headers'):
                kwargs['headers'] += extra_headers
            else:
                kwargs['headers'] = extra_headers

        response = super(AutoAuthFlaskClient, self).open(*args, **kwargs)

        if self._user is not None:
            with db.session.begin():
                db.session.delete(oauth2_bearer_token)
                db.session.delete(oauth2_bearer_token.client)

        return response
示例#9
0
文件: views.py 项目: Emily-Ke/houston
def create_session_oauth2_token(cleanup_tokens=False,
                                check_renewal=False,
                                user=None,
                                update_session=True):
    from app.extensions import db
    from app.modules.auth.models import OAuth2Client, OAuth2Token
    from app.extensions.api import api_v1
    import datetime

    if user is None:
        user = current_user
        if not user.is_authenticated:
            return None

    default_scopes = list(
        api_v1.authorizations['oauth2_password']['scopes'].keys())

    # Retrieve Oauth2 client for user and/or clean-up multiple clients
    session_oauth2_clients = OAuth2Client.query.filter_by(
        user=user, level=OAuth2Client.ClientLevels.session).all()
    session_oauth2_client = None
    if len(session_oauth2_clients) == 1:
        # We have an existing Oauth2 frontend client for this user, let's re-use it
        session_oauth2_client = session_oauth2_clients[0]
    elif len(session_oauth2_clients) > 1:
        # We have somehow created multiple clients for this user, delete them all and make new ones
        with db.session.begin():
            for session_oauth2_client_ in session_oauth2_clients:
                db.session.delete(session_oauth2_client_)

    if session_oauth2_client is None:
        session_oauth2_client = OAuth2Client(
            level=OAuth2Client.ClientLevels.session,
            user=user,
            default_scopes=default_scopes,
        )
        with db.session.begin():
            db.session.add(session_oauth2_client)
    log.info('Using session Oauth2 client = %r' % (session_oauth2_client, ))

    # Clean-up all tokens for the confidential client
    session_oauth2_bearer_tokens = OAuth2Token.query.filter_by(
        client=session_oauth2_client).all()
    log.info('User %s has %d confidential Oauth2 bearer tokens' % (
        user.email,
        len(session_oauth2_bearer_tokens),
    ))
    if cleanup_tokens:
        for session_oauth2_bearer_token_ in session_oauth2_bearer_tokens:
            log.info('Cleaning up User %s Oauth2 bearer token: %r' % (
                user.email,
                len(session_oauth2_bearer_tokens),
            ))
            session_oauth2_bearer_token_.delete()

    # IMPORTANT: WE NEED THIS TO BE IN UTC FOR OAUTH2
    expires = datetime.datetime.now(tz=pytz.utc) + datetime.timedelta(days=1)

    # Create a Oauth2 session bearer token with all scopes for this session
    session_oauth2_bearer_token = OAuth2Token(
        client=session_oauth2_client,
        user=user,
        token_type='Bearer',
        scopes=default_scopes,
        expires=expires,
    )
    with db.session.begin():
        db.session.add(session_oauth2_bearer_token)

    # Add the access token to the session

    if update_session:
        session_oauth2_access_token = session_oauth2_bearer_token.access_token
        session['access_token'] = session_oauth2_access_token

    return session_oauth2_bearer_token