Exemplo n.º 1
0
def create_service_token(client, user):
    """Generate and return a bearer token for service calls

    Partners need a mechanism for automated, authorized API access.  This
    function returns a bearer token for subsequent authorized calls.

    NB - as this opens a back door, it's only offered to users with the single
    role 'service'.

    """
    if not current_app.config.get('TESTING') and (
            len(user.roles) > 1 or user.roles[0].name != ROLE.SERVICE.value):
        raise ValueError("only service users can create service tokens")

    # Hacking a backdoor into the OAuth protocol to generate a valid token
    # Mock the request and validation needed to pass
    from oauthlib.oauth2.rfc6749.tokens import BearerToken

    fake_request = Mock()
    fake_request.state, fake_request.extra_credentials = None, None
    fake_request.client = client
    fake_request.user = user
    fake_request.scopes = ['email']

    request_validator = Mock()
    request_validator.save_bearer_token = save_token

    bt = BearerToken(request_validator=request_validator)
    bt.expires_in = int(timedelta(days=365).total_seconds())  # one year
    bt.create_token(fake_request)

    # Token should now exist as only token for said user - return it
    return Token.query.filter_by(user_id=user.id).first()
Exemplo n.º 2
0
def create_service_token(client, user):
    """Generate and return a bearer token for service calls

    Partners need a mechanism for automated, authorized API access.  This
    function returns a bearer token for subsequent authorized calls.

    NB - as this opens a back door, it's only offered to users with the single
    role 'service'.

    """
    if not current_app.config.get('TESTING') and (
            len(user.roles) > 1 or user.roles[0].name != ROLE.SERVICE.value):
        raise ValueError("only service users can create service tokens")

    # Hacking a backdoor into the OAuth protocol to generate a valid token
    # Mock the request and validation needed to pass
    from oauthlib.oauth2.rfc6749.tokens import BearerToken

    fake_request = Mock()
    fake_request.state, fake_request.extra_credentials = None, None
    fake_request.client = client
    fake_request.user = user
    fake_request.scopes = ['email']

    request_validator = Mock()
    request_validator.save_bearer_token = save_token

    bt = BearerToken(request_validator=request_validator)
    bt.expires_in = int(timedelta(days=365).total_seconds())  # one year
    bt.create_token(fake_request)

    # Token should now exist as only token for said user - return it
    return Token.query.filter_by(user_id=user.id).first()