:param username: Username of the user to create the token for. If the account for this user doesn't exist yet it will be created. :type username: ``str`` :param ttl: Token TTL (in seconds). :type ttl: ``int`` :param metadata: Optional metadata to associate
(
username, ttl=None, metadata=None, add_missing_user=True, service=False
)
| 33 | |
| 34 | |
| 35 | def create_token( |
| 36 | username, ttl=None, metadata=None, add_missing_user=True, service=False |
| 37 | ): |
| 38 | """ |
| 39 | :param username: Username of the user to create the token for. If the account for this user |
| 40 | doesn't exist yet it will be created. |
| 41 | :type username: ``str`` |
| 42 | |
| 43 | :param ttl: Token TTL (in seconds). |
| 44 | :type ttl: ``int`` |
| 45 | |
| 46 | :param metadata: Optional metadata to associate with the token. |
| 47 | :type metadata: ``dict`` |
| 48 | |
| 49 | :param add_missing_user: Add the user given by `username` if they don't exist |
| 50 | :type add_missing_user: ``bool`` |
| 51 | |
| 52 | :param service: True if this is a service (non-user) token. |
| 53 | :type service: ``bool`` |
| 54 | """ |
| 55 | |
| 56 | if ttl: |
| 57 | # Note: We allow arbitrary large TTLs for service tokens. |
| 58 | if not service and ttl > cfg.CONF.auth.token_ttl: |
| 59 | msg = "TTL specified %s is greater than max allowed %s." % ( |
| 60 | ttl, |
| 61 | cfg.CONF.auth.token_ttl, |
| 62 | ) |
| 63 | raise TTLTooLargeException(msg) |
| 64 | else: |
| 65 | ttl = cfg.CONF.auth.token_ttl |
| 66 | |
| 67 | if username: |
| 68 | try: |
| 69 | User.get_by_name(username) |
| 70 | except: |
| 71 | if add_missing_user: |
| 72 | user_db = UserDB(name=username) |
| 73 | User.add_or_update(user_db) |
| 74 | |
| 75 | extra = {"username": username, "user": user_db} |
| 76 | LOG.audit('Registered new user "%s".' % (username), extra=extra) |
| 77 | else: |
| 78 | raise UserNotFoundError() |
| 79 | |
| 80 | token = uuid.uuid4().hex |
| 81 | expiry = date_utils.get_datetime_utc_now() + datetime.timedelta(seconds=ttl) |
| 82 | token = TokenDB( |
| 83 | user=username, token=token, expiry=expiry, metadata=metadata, service=service |
| 84 | ) |
| 85 | Token.add_or_update(token) |
| 86 | |
| 87 | username_string = username if username else "an anonymous user" |
| 88 | token_expire_string = isotime.format(expiry, offset=False) |
| 89 | extra = {"username": username, "token_expiration": token_expire_string} |
| 90 | |
| 91 | LOG.audit( |
| 92 | 'Access granted to "%s" with the token set to expire at "%s".' |
no test coverage detected