blob: 6a52f516f4ce9d95c94b8e5b6205c4092f5b7af7 [file] [log] [blame]
Enbo Wangb764f222020-09-18 11:06:12 +08001# ============LICENSE_START=======================================================
2# Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved.
3# ================================================================================
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# 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# ============LICENSE_END=========================================================
16
17"""
18 Used to get and check Access Token by SO NSSMF adapter.
19"""
20
21import json
22import uuid
23import time
24import sched
25import threading
26from schematics.types import StringType
27from schematics.models import Model
28
29from .utils import getLogger, AUTH_DB, TOKEN_EXPIRES_TIME, TOKEN_CLEAN_TIME
30
31
32logger = getLogger("AuthManager")
33lock = threading.Lock()
34
35
36class AuthRequest(Model):
37 grantType = StringType(required=True)
38 userName = StringType(required=True)
39 value = StringType(required=True)
40
41
42class AuthInfo(object):
43 def __init__(self, authRequest, expires):
44 self.authRequest = authRequest
45 self.expiredTime = int(time.time()) + expires * 60
46
47
48class AuthError(ValueError):
49 pass
50
51
52class TokenError(ValueError):
53 pass
54
55
56_AUTH_TOKEN = {}
57
58
59def cleanExpiredToken():
60 s = sched.scheduler(time.time, time.sleep)
61
62 def doCleanExpiredToken():
63 current_time = int(time.time())
64
65 expiredTokens = []
66 for authToken in _AUTH_TOKEN:
67 if current_time > _AUTH_TOKEN[authToken].expiredTime:
68 expiredTokens.append(authToken)
69 logger.debug("Auth token %s is expired and will be deleted" % authToken)
70
71 with lock:
72 for authToken in expiredTokens:
73 del _AUTH_TOKEN[authToken]
74
75 s.enter(TOKEN_CLEAN_TIME, 1, doCleanExpiredToken)
76
77 s.enter(TOKEN_CLEAN_TIME, 1, doCleanExpiredToken)
78
79 s.run()
80
81
82def checkAuth(authRequest):
83 with open(AUTH_DB) as f:
84 authDB = json.load(f)
85
86 if authRequest["grantType"].lower() != "password":
87 raise AuthError("Unsupported grantType %s" % authRequest["grantType"])
88
89 for authItem in authDB:
90 if authItem["userName"].lower() == authRequest["userName"].lower() \
91 and authItem["value"] == authRequest["value"]:
92 break
93 else:
94 raise AuthError("userName or password is error")
95
96
97def generateAuthToken(authRequest):
98 token = uuid.uuid4().hex
99 with lock:
100 _AUTH_TOKEN[token] = AuthInfo(authRequest, TOKEN_EXPIRES_TIME)
101
102 return {
103 "accessToken": token,
104 "expires": TOKEN_EXPIRES_TIME
105 }
106
107
108def checkAuthToken(requestHeaders):
109 authToken = requestHeaders.get("X-Auth-Token")
110 logger.debug("X-Auth-Token: %s" % authToken)
111
112 if not authToken:
113 raise TokenError("Auth token is missing")
114
115 if authToken not in _AUTH_TOKEN:
116 raise TokenError("Auth token is error")
117
118 current_time = int(time.time())
119 if current_time > _AUTH_TOKEN[authToken].expiredTime:
120 raise TokenError("Auth token is expired")
121
122
123def startAuthManagerJob():
124 cleanThread = threading.Thread(target=cleanExpiredToken)
125 cleanThread.daemon = True
126
127 cleanThread.start()