Passed
Pull Request — master (#3163)
by W
05:12
created

get_token()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
dl 0
loc 2
rs 10
c 0
b 0
f 0
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 get_token(token):
91
    return Token.get(token)
92
93
94
def delete_token(token):
95
    try:
96
        token_db = Token.get(token)
97
        return Token.delete(token_db)
98
    except TokenNotFoundError:
99
        pass
100
    except Exception:
101
        raise
102