FitTrackee/fittrackee/oauth2/client.py

68 lines
1.7 KiB
Python
Raw Normal View History

from time import time
from typing import Dict
from werkzeug.security import gen_salt
from fittrackee.users.models import User
2022-06-15 19:16:14 +02:00
from .exceptions import InvalidOAuth2Scopes
from .models import OAuth2Client
VALID_SCOPES = [
'application:write',
'profile:read',
'profile:write',
'users:read',
'users:write',
'workouts:read',
'workouts:write',
]
2022-05-27 18:19:12 +02:00
def check_scope(scope: str) -> str:
"""
Verify if provided scope is valid.
"""
if not isinstance(scope, str) or not scope:
2022-06-15 19:16:14 +02:00
raise InvalidOAuth2Scopes()
2022-05-27 18:19:12 +02:00
2022-06-15 19:16:14 +02:00
valid_scopes = []
2022-05-27 18:19:12 +02:00
scopes = scope.split()
for value in scopes:
if value in VALID_SCOPES:
valid_scopes.append(value)
2022-06-15 19:16:14 +02:00
if not valid_scopes:
raise InvalidOAuth2Scopes()
2022-05-27 18:19:12 +02:00
return ' '.join(valid_scopes)
def create_oauth_client(metadata: Dict, user: User) -> OAuth2Client:
"""
Create oauth client for 3rd-party applications.
Only Authorization Code Grant with 'client_secret_post' as method
is supported.
"""
client_metadata = {
'client_name': metadata['client_name'],
'client_description': metadata.get('client_description'),
'client_uri': metadata['client_uri'],
'redirect_uris': metadata['redirect_uris'],
2022-05-27 18:19:12 +02:00
'scope': check_scope(metadata['scope']),
2022-05-27 14:18:50 +02:00
'grant_types': ['authorization_code', 'refresh_token'],
'response_types': ['code'],
'token_endpoint_auth_method': 'client_secret_post',
}
client_id = gen_salt(24)
client_id_issued_at = int(time())
client = OAuth2Client(
client_id=client_id,
client_id_issued_at=client_id_issued_at,
user_id=user.id,
)
client.set_client_metadata(client_metadata)
client.client_secret = gen_salt(48)
return client