2022-05-27 13:28:26 +02:00
|
|
|
from time import time
|
|
|
|
from typing import Dict
|
|
|
|
|
|
|
|
from werkzeug.security import gen_salt
|
|
|
|
|
|
|
|
from fittrackee.oauth2.models import OAuth2Client
|
|
|
|
from fittrackee.users.models import User
|
|
|
|
|
2022-05-27 18:19:12 +02:00
|
|
|
DEFAULT_SCOPE = 'read'
|
|
|
|
VALID_SCOPES = ['read', 'write']
|
|
|
|
|
|
|
|
|
|
|
|
def check_scope(scope: str) -> str:
|
|
|
|
"""
|
|
|
|
Verify if provided scope is valid.
|
|
|
|
If not, it returns the default scope ('read').
|
|
|
|
"""
|
|
|
|
valid_scopes = []
|
|
|
|
if not isinstance(scope, str) or not scope:
|
|
|
|
return DEFAULT_SCOPE
|
|
|
|
|
|
|
|
scopes = scope.split()
|
|
|
|
for value in scopes:
|
|
|
|
if value in VALID_SCOPES:
|
|
|
|
valid_scopes.append(value)
|
|
|
|
if len(valid_scopes) == 0:
|
|
|
|
valid_scopes.append(DEFAULT_SCOPE)
|
|
|
|
|
|
|
|
return ' '.join(valid_scopes)
|
|
|
|
|
2022-05-27 13:28:26 +02:00
|
|
|
|
|
|
|
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'],
|
2022-05-28 15:36:18 +02:00
|
|
|
'client_description': metadata.get('client_description'),
|
2022-05-27 13:28:26 +02:00
|
|
|
'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'],
|
2022-05-27 13:28:26 +02:00
|
|
|
'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
|