1 /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2 /*
3  *     Copyright 2016 Couchbase, Inc.
4  *
5  *   Licensed under the Apache License, Version 2.0 (the "License");
6  *   you may not use this file except in compliance with the License.
7  *   You may obtain a copy of the License at
8  *
9  *       http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *   Unless required by applicable law or agreed to in writing, software
12  *   distributed under the License is distributed on an "AS IS" BASIS,
13  *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *   See the License for the specific language governing permissions and
15  *   limitations under the License.
16  */
17 #include "password_database.h"
18 
19 #include <nlohmann/json.hpp>
20 #include <memory>
21 #include <string>
22 
23 namespace cb {
24 namespace sasl {
25 namespace pwdb {
26 
PasswordDatabase(const std::string& content, bool file)27 PasswordDatabase::PasswordDatabase(const std::string& content, bool file) {
28     nlohmann::json json;
29 
30     if (file) {
31         auto c = read_password_file(content);
32         try {
33             json = nlohmann::json::parse(c);
34         } catch (const nlohmann::json::exception&) {
35             throw std::runtime_error(
36                     "PasswordDatabase: Failed to parse the JSON in " + content);
37         }
38     } else {
39         try {
40             json = nlohmann::json::parse(content);
41         } catch (const nlohmann::json::exception&) {
42             throw std::runtime_error(
43                     "PasswordDatabase: Failed to parse the supplied JSON");
44         }
45     }
46 
47     if (json.size() != 1) {
48         throw std::runtime_error("PasswordDatabase: format error..");
49     }
50 
51     auto it = json.find("users");
52     if (it == json.end()) {
53         throw std::runtime_error(
54                 "PasswordDatabase: format error. users not"
55                 " present");
56     }
57 
58     if (!it->is_array()) {
59         throw std::runtime_error(
60                 "PasswordDatabase: Illegal type for \"users\". Expected Array");
61     }
62 
63     // parse all of the users
64     for (const auto& u : *it) {
65         auto user = UserFactory::create(u);
66         db[user.getUsername().getRawValue()] = user;
67     }
68 }
69 
to_json() const70 nlohmann::json PasswordDatabase::to_json() const {
71     nlohmann::json json;
72     nlohmann::json array = nlohmann::json::array();
73 
74     for (const auto& u : db) {
75         array.push_back(u.second.to_json());
76     }
77     json["users"] = array;
78     return json;
79 }
80 
to_string() const81 std::string PasswordDatabase::to_string() const {
82     return to_json().dump();
83 }
84 
85 } // namespace pwdb
86 } // namespace sasl
87 } // namespace cb
88