1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "userauth_datamgr.h"
17 #include <openssl/rand.h>
18 #include "userauth_hilog_wrapper.h"
19
20 namespace OHOS {
21 namespace UserIAM {
22 namespace UserAuth {
GetInstance()23 UserAuthDataMgr &UserAuthDataMgr::GetInstance()
24 {
25 static UserAuthDataMgr instance;
26 return instance;
27 }
28
AddContextId(uint64_t contextId)29 int32_t UserAuthDataMgr::AddContextId(uint64_t contextId)
30 {
31 USERAUTH_HILOGD(MODULE_SERVICE, "UserAuthDataMgr AddContextId start");
32 std::lock_guard<std::mutex> lock(mutex_);
33 if (contextIds_.count(contextId) == 1) {
34 USERAUTH_HILOGE(MODULE_SERVICE, "contextId is exist");
35 return GENERAL_ERROR;
36 }
37 contextIds_.insert(contextId);
38 USERAUTH_HILOGD(MODULE_SERVICE, "UserAuthDataMgr AddContextId end");
39 return SUCCESS;
40 }
41
IsContextIdExist(uint64_t contextId)42 int32_t UserAuthDataMgr::IsContextIdExist(uint64_t contextId)
43 {
44 USERAUTH_HILOGD(MODULE_SERVICE, "UserAuthDataMgr IsContextIdExist start");
45 std::lock_guard<std::mutex> lock(mutex_);
46 if (contextIds_.count(contextId) == 1) {
47 return SUCCESS;
48 }
49 USERAUTH_HILOGD(MODULE_SERVICE, "UserAuthDataMgr IsContextIdExist end");
50 return GENERAL_ERROR;
51 }
52
GenerateContextId(uint64_t & contextId)53 int32_t UserAuthDataMgr::GenerateContextId(uint64_t &contextId)
54 {
55 USERAUTH_HILOGD(MODULE_SERVICE, "UserAuthDataMgr GenerateContextId start");
56
57 std::lock_guard<std::mutex> lock(mutex_);
58 do {
59 if (RAND_bytes(reinterpret_cast<uint8_t *>(&contextId), (int)sizeof(contextId)) != OPENSSLSUCCESS) {
60 USERAUTH_HILOGE(MODULE_SERVICE, "GenerateContextId failed");
61 continue;
62 }
63 } while ((contextIds_.count(contextId) > 0) || (contextId == 0));
64 USERAUTH_HILOGD(MODULE_SERVICE, "UserAuthDataMgr GenerateContextId end");
65 return SUCCESS;
66 }
67
DeleteContextId(uint64_t contextId)68 int32_t UserAuthDataMgr::DeleteContextId(uint64_t contextId)
69 {
70 USERAUTH_HILOGD(MODULE_SERVICE, "UserAuthDataMgr DeleteContextId start");
71 std::lock_guard<std::mutex> lock(mutex_);
72 if (contextIds_.count(contextId) == 0) {
73 USERAUTH_HILOGE(MODULE_SERVICE, "contextId invalid");
74 return GENERAL_ERROR;
75 }
76 contextIds_.erase(contextId);
77 return SUCCESS;
78 }
79 } // namespace UserAuth
80 } // namespace UserIam
81 } // namespace OHOS
82