def createApiKey(self, user, name, scope=None, days=None, active=True): """ Create a new API key for a user. :param user: The user who owns the API key. :type user: dict :param name: A human readable name for the API key :param days: The lifespan of the session in days. If not passed, uses the database setting for cookie lifetime. Note that this is a maximum duration; clients may request tokens with a shorter lifetime than this value. :type days: float or int :param scope: Scope or list of scopes this API key grants. By default, will grant tokens provided full access on behalf of the user. :type scope: str, list of str, or set of str :param active: Whether this key is active. :returns: The API key document that was created. """ apiKey = { 'created': datetime.datetime.utcnow(), 'lastUse': None, 'tokenDuration': days, 'name': name, 'scope': scope, 'userId': user['_id'], 'key': genToken(40), 'active': active } return self.setUserAccess(apiKey, user, level=AccessType.ADMIN, save=True)
def createToken(self, user=None, days=None, scope=None, apiKey=None): """ Creates a new token. You can create an anonymous token (such as for CSRF mitigation) by passing "None" for the user argument. :param user: The user to create the session for. :type user: dict :param days: The lifespan of the session in days. If not passed, uses the database setting for cookie lifetime. :type days: float or int :param scope: Scope or list of scopes this token applies to. By default, will create a user authentication token. :type scope: str or list of str :param apiKey: If this token is being created via an API key, pass it so that we can record the provenance for cleanup and auditing. :type apiKey: dict :returns: The token document that was created. """ from .setting import Setting now = datetime.datetime.utcnow() days = days or Setting().get(SettingKey.COOKIE_LIFETIME) if scope is None: scope = (TokenScope.USER_AUTH, ) elif isinstance(scope, six.string_types): scope = (scope, ) token = { '_id': genToken(), 'created': now, 'expires': now + datetime.timedelta(days=float(days)), 'scope': scope } if user is None: # Since these tokens don't correspond to a user, we want to be # able to load them by their value without passing a user or # force=True, so we set it to public access. This is OK since tokens # are not exposed externally for listing, and the _id is the secure # token value. self.setPublic(token, True, save=False) else: token['userId'] = user['_id'] self.setUserAccess(token, user=user, level=AccessType.ADMIN, save=False) if apiKey is not None: token['apiKeyId'] = apiKey['_id'] return self.save(token)