Enbo Wang | b764f22 | 2020-09-18 11:06:12 +0800 | [diff] [blame] | 1 | # ============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 | |
| 21 | import json |
| 22 | import uuid |
| 23 | import time |
| 24 | import sched |
| 25 | import threading |
| 26 | from schematics.types import StringType |
| 27 | from schematics.models import Model |
| 28 | |
| 29 | from .utils import getLogger, AUTH_DB, TOKEN_EXPIRES_TIME, TOKEN_CLEAN_TIME |
| 30 | |
| 31 | |
| 32 | logger = getLogger("AuthManager") |
| 33 | lock = threading.Lock() |
| 34 | |
| 35 | |
| 36 | class AuthRequest(Model): |
| 37 | grantType = StringType(required=True) |
| 38 | userName = StringType(required=True) |
| 39 | value = StringType(required=True) |
| 40 | |
| 41 | |
| 42 | class AuthInfo(object): |
| 43 | def __init__(self, authRequest, expires): |
| 44 | self.authRequest = authRequest |
| 45 | self.expiredTime = int(time.time()) + expires * 60 |
| 46 | |
| 47 | |
| 48 | class AuthError(ValueError): |
| 49 | pass |
| 50 | |
| 51 | |
| 52 | class TokenError(ValueError): |
| 53 | pass |
| 54 | |
| 55 | |
| 56 | _AUTH_TOKEN = {} |
| 57 | |
| 58 | |
| 59 | def 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 | |
| 82 | def 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 | |
| 97 | def 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 | |
| 108 | def 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 | |
| 123 | def startAuthManagerJob(): |
| 124 | cleanThread = threading.Thread(target=cleanExpiredToken) |
| 125 | cleanThread.daemon = True |
| 126 | |
| 127 | cleanThread.start() |