"""Auth handlers. The auth handlers provide endpoints to facilitate the creation of a relation between a client and a user, and grant access to specific endpoints the client can fetch on the behalf of a user. If the user has a public key, it can fetch directly some of our public endpoints. """ from grass import access, api from grass.logic import session from grass.utils import response @api.route( '/auth/session/', access=[access.allow_client()], metric='auth.session', methods=['GET'], ) def create_user_session(handler): """Create a session token. GET: ``/auth/session/`` By calling this endpoint, the client will generate a session token the user can consume to perform direct actions against API endpoints that have for ACL ``access.auth_public`` without the need to go through the client again. This token has a very short life. If the server returns a 401 on a request, it means you will need to regenerate the token by calling this endpoint again. However, you can prevent the 401 to happen by calling this endpoint again before the token has expired. Example: .. code-block:: javascript // This code should live in a TokenManager singleton, supposing that // createToken will create a xhr to your current API client and // return the full api response. var duration = this.tokenDuration; window.setTimeout(this.createToken, duration); Returns: dict: that contains the key id and the timestamp on when it will expires. """ client_id = handler.get_argument('client') user_id = handler.get_argument('user') return session.create_token(client_id, user_id) @api.route( '/auth/logout-session/', access=[access.allow_client()], metric='auth.session', methods=['DELETE'], ) def delete_user_session(handler): """Delete a session token. DELETE: ``/auth/logout-session/`` By calling this endpoint, it deletes the provided session token in header that the user was able to consume to perform direct actions against API endpoints. Returns: 200 Session Deleted if success, else 404 Session does not exist. """ session_token = handler.request.headers.get('session') return session.delete_token(session_token) @api.route( '/token/store/', access=[access.allow_public_access], methods=['POST', 'OPTIONS'] ) def store_auth_tokens(handler): """ Use to store the authorization token of logged out user in redis cache. Args: authorization (string): authorization token. Returns: message: message. """ # Allow CORS preflight checks for OPTIONS requests if handler.request.method == 'OPTIONS': return response.Response(message='success') auth_token = handler.request.headers.get('authorization') message = session.store_auth_token_on_logout(auth_token) return response.Response(message=message)