Completed
Push — master ( 1c9535...b8d4ca )
by Edward
02:26
created

create_token()   C

Complexity

Conditions 7

Size

Total Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
c 2
b 0
f 0
dl 0
loc 51
rs 5.7838

How to fix   Long Method   

Long Method

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:

1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
import uuid
17
import datetime
18
19
from oslo_config import cfg
20
21
from st2common.util import isotime
22
from st2common.util import date as date_utils
23
from st2common.exceptions.auth import TokenNotFoundError, UserNotFoundError
24
from st2common.exceptions.auth import TTLTooLargeException
25
from st2common.models.db.auth import TokenDB, UserDB
26
from st2common.persistence.auth import Token, User
27
from st2common import log as logging
28
29
__all__ = [
30
    'create_token',
31
    'delete_token'
32
]
33
34
LOG = logging.getLogger(__name__)
35
36
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_db = UserDB(name=username)
68
                User.add_or_update(user_db)
69
70
                extra = {'username': username, 'user': user_db}
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
89
90
def delete_token(token):
91
    try:
92
        token_db = Token.get(token)
93
        return Token.delete(token_db)
94
    except TokenNotFoundError:
95
        pass
96
    except Exception:
97
        raise
98