| Conditions | 7 |
| Total Lines | 51 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | # Licensed to the StackStorm, Inc ('StackStorm') under one or more |
||
| 37 | def create_token(username, ttl=None, metadata=None, add_missing_user=True): |
||
| 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 | |||
| 53 | if ttl: |
||
| 54 | if ttl > cfg.CONF.auth.token_ttl: |
||
| 55 | msg = 'TTL specified %s is greater than max allowed %s.' % ( |
||
| 56 | ttl, cfg.CONF.auth.token_ttl |
||
| 57 | ) |
||
| 58 | raise TTLTooLargeException(msg) |
||
| 59 | else: |
||
| 60 | ttl = cfg.CONF.auth.token_ttl |
||
| 61 | |||
| 62 | if username: |
||
| 63 | try: |
||
| 64 | User.get_by_name(username) |
||
| 65 | except: |
||
| 66 | if add_missing_user: |
||
| 67 | user = UserDB(name=username) |
||
| 68 | User.add_or_update(user) |
||
| 69 | |||
| 70 | extra = {'username': username, 'user': user} |
||
| 71 | LOG.audit('Registered new user "%s".' % (username), extra=extra) |
||
| 72 | else: |
||
| 73 | raise UserNotFoundError() |
||
| 74 | |||
| 75 | token = uuid.uuid4().hex |
||
| 76 | expiry = date_utils.get_datetime_utc_now() + datetime.timedelta(seconds=ttl) |
||
| 77 | token = TokenDB(user=username, token=token, expiry=expiry, metadata=metadata) |
||
| 78 | Token.add_or_update(token) |
||
| 79 | |||
| 80 | username_string = username if username else 'an anonymous user' |
||
| 81 | token_expire_string = isotime.format(expiry, offset=False) |
||
| 82 | extra = {'username': username, 'token_expiration': token_expire_string} |
||
| 83 | |||
| 84 | LOG.audit('Access granted to "%s" with the token set to expire at "%s".' % |
||
| 85 | (username_string, token_expire_string), extra=extra) |
||
| 86 | |||
| 87 | return token |
||
| 88 | |||
| 98 |