"""Api Token.""" import uuid from datetime import datetime from ddtrace import tracer from grass.connectors import mysql from grass.models.api_token import ApiToken @tracer.wrap() def is_token_valid(token, client_id, user_id): """Check if a token is valid. Args: token (string): the token value. client_id (string): the client id. user_id (int): the client id. Returns: boolean: if the token has been found and has not expired yet. """ if not token or not client_id or not user_id: # TODO(mortali): This should be a custom exception. raise Exception('The token cannot be verified with missing information.') session = mysql.session() row = session.query(ApiToken).filter(ApiToken.oauth_token == token).first() session.close() if not row: return False if not client_id == row.client_id or not row.user_id == int(user_id): # TODO(mortali): Add logging. In this case it means that a client # is trying to access to a user without the right token. return False return True @tracer.wrap() def create_token(client_id, user_id): """Create a token. The token creation fetch user information to define the user type (if it's an OA or ALW user), also checks the validity of the client id. After botch checks a token is generated. Args: client_id (string): the client id refers to the system that has gained access to this particular user. Without this - the system will not be able to perform actions on the behalf of this user. user_id (int): the user id. Returns: ApiToken: the ApiToken object with the ``oauth_token`` set. """ token = str(uuid.uuid4()).replace('-', '') # Perform the checks on the user and the client before returning the # response. user_type = 'alw' # Token is valid for a month. expires = datetime.utcnow().timestamp() + 3600 * 24 * 30 return _create_token(token, client_id, user_id, user_type, expires) @tracer.wrap() def _create_token(token, client_id, user_id, user_type, expires): """Internal helper to create a token. Args: token (string): the token value. client_id (string): The client id. user_id (int): the client id. expires (int): the expiration date. Returns: ApiToken: the temporary api token. """ token = ApiToken( oauth_token=token, client_id=client_id, user_id=user_id, user_type=user_type, expires_REMOVE=expires, ) session = mysql.session() session.add(token) session.commit() session.close() return token