xref: /openbmc/bmcweb/features/redfish/lib/account_service.hpp (revision d02aad3988620c648d6e696b67d6c542857f5bfc)
188d16c9aSLewanczyk, Dawid /*
288d16c9aSLewanczyk, Dawid // Copyright (c) 2018 Intel Corporation
388d16c9aSLewanczyk, Dawid //
488d16c9aSLewanczyk, Dawid // Licensed under the Apache License, Version 2.0 (the "License");
588d16c9aSLewanczyk, Dawid // you may not use this file except in compliance with the License.
688d16c9aSLewanczyk, Dawid // You may obtain a copy of the License at
788d16c9aSLewanczyk, Dawid //
888d16c9aSLewanczyk, Dawid //      http://www.apache.org/licenses/LICENSE-2.0
988d16c9aSLewanczyk, Dawid //
1088d16c9aSLewanczyk, Dawid // Unless required by applicable law or agreed to in writing, software
1188d16c9aSLewanczyk, Dawid // distributed under the License is distributed on an "AS IS" BASIS,
1288d16c9aSLewanczyk, Dawid // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1388d16c9aSLewanczyk, Dawid // See the License for the specific language governing permissions and
1488d16c9aSLewanczyk, Dawid // limitations under the License.
1588d16c9aSLewanczyk, Dawid */
1688d16c9aSLewanczyk, Dawid #pragma once
1788d16c9aSLewanczyk, Dawid 
183ccb3adbSEd Tanous #include "app.hpp"
193ccb3adbSEd Tanous #include "dbus_utility.hpp"
203ccb3adbSEd Tanous #include "error_messages.hpp"
210ec8b83dSEd Tanous #include "generated/enums/account_service.hpp"
223ccb3adbSEd Tanous #include "openbmc_dbus_rest.hpp"
233ccb3adbSEd Tanous #include "persistent_data.hpp"
243ccb3adbSEd Tanous #include "query.hpp"
250ec8b83dSEd Tanous #include "registries/privilege_registry.hpp"
263ccb3adbSEd Tanous #include "utils/dbus_utils.hpp"
273ccb3adbSEd Tanous #include "utils/json_utils.hpp"
280ec8b83dSEd Tanous 
291e1e598dSJonathan Doman #include <sdbusplus/asio/property.hpp>
30d1bde9e5SKrzysztof Grobelny #include <sdbusplus/unpack_properties.hpp>
311214b7e7SGunnar Mills 
322b73119cSGeorge Liu #include <array>
33c7229815SAbhishek Patel #include <optional>
343544d2a7SEd Tanous #include <ranges>
35c7229815SAbhishek Patel #include <string>
362b73119cSGeorge Liu #include <string_view>
37c7229815SAbhishek Patel #include <vector>
38c7229815SAbhishek Patel 
391abe55efSEd Tanous namespace redfish
401abe55efSEd Tanous {
4188d16c9aSLewanczyk, Dawid 
4223a21a1cSEd Tanous constexpr const char* ldapConfigObjectName =
436973a582SRatan Gupta     "/xyz/openbmc_project/user/ldap/openldap";
442c70f800SEd Tanous constexpr const char* adConfigObject =
45ab828d7cSRatan Gupta     "/xyz/openbmc_project/user/ldap/active_directory";
46ab828d7cSRatan Gupta 
47b477fd44SP Dheeraj Srujan Kumar constexpr const char* rootUserDbusPath = "/xyz/openbmc_project/user/";
486973a582SRatan Gupta constexpr const char* ldapRootObject = "/xyz/openbmc_project/user/ldap";
496973a582SRatan Gupta constexpr const char* ldapDbusService = "xyz.openbmc_project.Ldap.Config";
506973a582SRatan Gupta constexpr const char* ldapConfigInterface =
516973a582SRatan Gupta     "xyz.openbmc_project.User.Ldap.Config";
526973a582SRatan Gupta constexpr const char* ldapCreateInterface =
536973a582SRatan Gupta     "xyz.openbmc_project.User.Ldap.Create";
546973a582SRatan Gupta constexpr const char* ldapEnableInterface = "xyz.openbmc_project.Object.Enable";
5506785244SRatan Gupta constexpr const char* ldapPrivMapperInterface =
5606785244SRatan Gupta     "xyz.openbmc_project.User.PrivilegeMapper";
576973a582SRatan Gupta 
5854fc587aSNagaraju Goruganti struct LDAPRoleMapData
5954fc587aSNagaraju Goruganti {
6054fc587aSNagaraju Goruganti     std::string groupName;
6154fc587aSNagaraju Goruganti     std::string privilege;
6254fc587aSNagaraju Goruganti };
6354fc587aSNagaraju Goruganti 
646973a582SRatan Gupta struct LDAPConfigData
656973a582SRatan Gupta {
6647f2934cSEd Tanous     std::string uri;
6747f2934cSEd Tanous     std::string bindDN;
6847f2934cSEd Tanous     std::string baseDN;
6947f2934cSEd Tanous     std::string searchScope;
7047f2934cSEd Tanous     std::string serverType;
716973a582SRatan Gupta     bool serviceEnabled = false;
7247f2934cSEd Tanous     std::string userNameAttribute;
7347f2934cSEd Tanous     std::string groupAttribute;
7454fc587aSNagaraju Goruganti     std::vector<std::pair<std::string, LDAPRoleMapData>> groupRoleList;
756973a582SRatan Gupta };
766973a582SRatan Gupta 
7754fc587aSNagaraju Goruganti inline std::string getRoleIdFromPrivilege(std::string_view role)
7884e12cb7SAppaRao Puli {
7984e12cb7SAppaRao Puli     if (role == "priv-admin")
8084e12cb7SAppaRao Puli     {
8184e12cb7SAppaRao Puli         return "Administrator";
8284e12cb7SAppaRao Puli     }
833174e4dfSEd Tanous     if (role == "priv-user")
8484e12cb7SAppaRao Puli     {
85c80fee55SAppaRao Puli         return "ReadOnly";
8684e12cb7SAppaRao Puli     }
873174e4dfSEd Tanous     if (role == "priv-operator")
8884e12cb7SAppaRao Puli     {
8984e12cb7SAppaRao Puli         return "Operator";
9084e12cb7SAppaRao Puli     }
9184e12cb7SAppaRao Puli     return "";
9284e12cb7SAppaRao Puli }
9354fc587aSNagaraju Goruganti inline std::string getPrivilegeFromRoleId(std::string_view role)
9484e12cb7SAppaRao Puli {
9584e12cb7SAppaRao Puli     if (role == "Administrator")
9684e12cb7SAppaRao Puli     {
9784e12cb7SAppaRao Puli         return "priv-admin";
9884e12cb7SAppaRao Puli     }
993174e4dfSEd Tanous     if (role == "ReadOnly")
10084e12cb7SAppaRao Puli     {
10184e12cb7SAppaRao Puli         return "priv-user";
10284e12cb7SAppaRao Puli     }
1033174e4dfSEd Tanous     if (role == "Operator")
10484e12cb7SAppaRao Puli     {
10584e12cb7SAppaRao Puli         return "priv-operator";
10684e12cb7SAppaRao Puli     }
10784e12cb7SAppaRao Puli     return "";
10884e12cb7SAppaRao Puli }
109b9b2e0b2SEd Tanous 
110c7229815SAbhishek Patel /**
111c7229815SAbhishek Patel  * @brief Maps user group names retrieved from D-Bus object to
112c7229815SAbhishek Patel  * Account Types.
113c7229815SAbhishek Patel  *
114c7229815SAbhishek Patel  * @param[in] userGroups List of User groups
115c7229815SAbhishek Patel  * @param[out] res AccountTypes populated
116c7229815SAbhishek Patel  *
117c7229815SAbhishek Patel  * @return true in case of success, false if UserGroups contains
118c7229815SAbhishek Patel  * invalid group name(s).
119c7229815SAbhishek Patel  */
120c7229815SAbhishek Patel inline bool translateUserGroup(const std::vector<std::string>& userGroups,
121c7229815SAbhishek Patel                                crow::Response& res)
122c7229815SAbhishek Patel {
123c7229815SAbhishek Patel     std::vector<std::string> accountTypes;
124c7229815SAbhishek Patel     for (const auto& userGroup : userGroups)
125c7229815SAbhishek Patel     {
126c7229815SAbhishek Patel         if (userGroup == "redfish")
127c7229815SAbhishek Patel         {
128c7229815SAbhishek Patel             accountTypes.emplace_back("Redfish");
129c7229815SAbhishek Patel             accountTypes.emplace_back("WebUI");
130c7229815SAbhishek Patel         }
131c7229815SAbhishek Patel         else if (userGroup == "ipmi")
132c7229815SAbhishek Patel         {
133c7229815SAbhishek Patel             accountTypes.emplace_back("IPMI");
134c7229815SAbhishek Patel         }
135c7229815SAbhishek Patel         else if (userGroup == "ssh")
136c7229815SAbhishek Patel         {
137c7229815SAbhishek Patel             accountTypes.emplace_back("ManagerConsole");
138c7229815SAbhishek Patel         }
1393e72c202SNinad Palsule         else if (userGroup == "hostconsole")
1403e72c202SNinad Palsule         {
1413e72c202SNinad Palsule             // The hostconsole group controls who can access the host console
1423e72c202SNinad Palsule             // port via ssh and websocket.
1433e72c202SNinad Palsule             accountTypes.emplace_back("HostConsole");
1443e72c202SNinad Palsule         }
145c7229815SAbhishek Patel         else if (userGroup == "web")
146c7229815SAbhishek Patel         {
147c7229815SAbhishek Patel             // 'web' is one of the valid groups in the UserGroups property of
148c7229815SAbhishek Patel             // the user account in the D-Bus object. This group is currently not
149c7229815SAbhishek Patel             // doing anything, and is considered to be equivalent to 'redfish'.
150c7229815SAbhishek Patel             // 'redfish' user group is mapped to 'Redfish'and 'WebUI'
151c7229815SAbhishek Patel             // AccountTypes, so do nothing here...
152c7229815SAbhishek Patel         }
153c7229815SAbhishek Patel         else
154c7229815SAbhishek Patel         {
1558ece0e45SEd Tanous             // Invalid user group name. Caller throws an exception.
156c7229815SAbhishek Patel             return false;
157c7229815SAbhishek Patel         }
158c7229815SAbhishek Patel     }
159c7229815SAbhishek Patel 
160c7229815SAbhishek Patel     res.jsonValue["AccountTypes"] = std::move(accountTypes);
161c7229815SAbhishek Patel     return true;
162c7229815SAbhishek Patel }
163c7229815SAbhishek Patel 
16458345856SAbhishek Patel /**
16558345856SAbhishek Patel  * @brief Builds User Groups from the Account Types
16658345856SAbhishek Patel  *
16758345856SAbhishek Patel  * @param[in] asyncResp Async Response
16858345856SAbhishek Patel  * @param[in] accountTypes List of Account Types
16958345856SAbhishek Patel  * @param[out] userGroups List of User Groups mapped from Account Types
17058345856SAbhishek Patel  *
17158345856SAbhishek Patel  * @return true if Account Types mapped to User Groups, false otherwise.
17258345856SAbhishek Patel  */
17358345856SAbhishek Patel inline bool
17458345856SAbhishek Patel     getUserGroupFromAccountType(crow::Response& res,
17558345856SAbhishek Patel                                 const std::vector<std::string>& accountTypes,
17658345856SAbhishek Patel                                 std::vector<std::string>& userGroups)
17758345856SAbhishek Patel {
17858345856SAbhishek Patel     // Need both Redfish and WebUI Account Types to map to 'redfish' User Group
17958345856SAbhishek Patel     bool redfishType = false;
18058345856SAbhishek Patel     bool webUIType = false;
18158345856SAbhishek Patel 
18258345856SAbhishek Patel     for (const auto& accountType : accountTypes)
18358345856SAbhishek Patel     {
18458345856SAbhishek Patel         if (accountType == "Redfish")
18558345856SAbhishek Patel         {
18658345856SAbhishek Patel             redfishType = true;
18758345856SAbhishek Patel         }
18858345856SAbhishek Patel         else if (accountType == "WebUI")
18958345856SAbhishek Patel         {
19058345856SAbhishek Patel             webUIType = true;
19158345856SAbhishek Patel         }
19258345856SAbhishek Patel         else if (accountType == "IPMI")
19358345856SAbhishek Patel         {
19458345856SAbhishek Patel             userGroups.emplace_back("ipmi");
19558345856SAbhishek Patel         }
19658345856SAbhishek Patel         else if (accountType == "HostConsole")
19758345856SAbhishek Patel         {
19858345856SAbhishek Patel             userGroups.emplace_back("hostconsole");
19958345856SAbhishek Patel         }
20058345856SAbhishek Patel         else if (accountType == "ManagerConsole")
20158345856SAbhishek Patel         {
20258345856SAbhishek Patel             userGroups.emplace_back("ssh");
20358345856SAbhishek Patel         }
20458345856SAbhishek Patel         else
20558345856SAbhishek Patel         {
20658345856SAbhishek Patel             // Invalid Account Type
20758345856SAbhishek Patel             messages::propertyValueNotInList(res, "AccountTypes", accountType);
20858345856SAbhishek Patel             return false;
20958345856SAbhishek Patel         }
21058345856SAbhishek Patel     }
21158345856SAbhishek Patel 
21258345856SAbhishek Patel     // Both  Redfish and WebUI Account Types are needed to PATCH
21358345856SAbhishek Patel     if (redfishType ^ webUIType)
21458345856SAbhishek Patel     {
21562598e31SEd Tanous         BMCWEB_LOG_ERROR(
21662598e31SEd Tanous             "Missing Redfish or WebUI Account Type to set redfish User Group");
21758345856SAbhishek Patel         messages::strictAccountTypes(res, "AccountTypes");
21858345856SAbhishek Patel         return false;
21958345856SAbhishek Patel     }
22058345856SAbhishek Patel 
22158345856SAbhishek Patel     if (redfishType && webUIType)
22258345856SAbhishek Patel     {
22358345856SAbhishek Patel         userGroups.emplace_back("redfish");
22458345856SAbhishek Patel     }
22558345856SAbhishek Patel 
22658345856SAbhishek Patel     return true;
22758345856SAbhishek Patel }
22858345856SAbhishek Patel 
22958345856SAbhishek Patel /**
23058345856SAbhishek Patel  * @brief Sets UserGroups property of the user based on the Account Types
23158345856SAbhishek Patel  *
23258345856SAbhishek Patel  * @param[in] accountTypes List of User Account Types
23358345856SAbhishek Patel  * @param[in] asyncResp Async Response
23458345856SAbhishek Patel  * @param[in] dbusObjectPath D-Bus Object Path
23558345856SAbhishek Patel  * @param[in] userSelf true if User is updating OWN Account Types
23658345856SAbhishek Patel  */
23758345856SAbhishek Patel inline void
23858345856SAbhishek Patel     patchAccountTypes(const std::vector<std::string>& accountTypes,
23958345856SAbhishek Patel                       const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
24058345856SAbhishek Patel                       const std::string& dbusObjectPath, bool userSelf)
24158345856SAbhishek Patel {
24258345856SAbhishek Patel     // Check if User is disabling own Redfish Account Type
24358345856SAbhishek Patel     if (userSelf &&
24458345856SAbhishek Patel         (accountTypes.cend() ==
24558345856SAbhishek Patel          std::find(accountTypes.cbegin(), accountTypes.cend(), "Redfish")))
24658345856SAbhishek Patel     {
24762598e31SEd Tanous         BMCWEB_LOG_ERROR(
24862598e31SEd Tanous             "User disabling OWN Redfish Account Type is not allowed");
24958345856SAbhishek Patel         messages::strictAccountTypes(asyncResp->res, "AccountTypes");
25058345856SAbhishek Patel         return;
25158345856SAbhishek Patel     }
25258345856SAbhishek Patel 
25358345856SAbhishek Patel     std::vector<std::string> updatedUserGroups;
25458345856SAbhishek Patel     if (!getUserGroupFromAccountType(asyncResp->res, accountTypes,
25558345856SAbhishek Patel                                      updatedUserGroups))
25658345856SAbhishek Patel     {
25758345856SAbhishek Patel         // Problem in mapping Account Types to User Groups, Error already
25858345856SAbhishek Patel         // logged.
25958345856SAbhishek Patel         return;
26058345856SAbhishek Patel     }
261*d02aad39SEd Tanous     setDbusProperty(asyncResp, "xyz.openbmc_project.User.Manager",
262*d02aad39SEd Tanous                     dbusObjectPath, "xyz.openbmc_project.User.Attributes",
263*d02aad39SEd Tanous                     "UserGroups", "AccountTypes", updatedUserGroups);
26458345856SAbhishek Patel }
26558345856SAbhishek Patel 
2668d1b46d7Szhanghch05 inline void userErrorMessageHandler(
2678d1b46d7Szhanghch05     const sd_bus_error* e, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2688d1b46d7Szhanghch05     const std::string& newUser, const std::string& username)
26966b5ca76Sjayaprakash Mutyala {
27066b5ca76Sjayaprakash Mutyala     if (e == nullptr)
27166b5ca76Sjayaprakash Mutyala     {
27266b5ca76Sjayaprakash Mutyala         messages::internalError(asyncResp->res);
27366b5ca76Sjayaprakash Mutyala         return;
27466b5ca76Sjayaprakash Mutyala     }
27566b5ca76Sjayaprakash Mutyala 
276055806b3SManojkiran Eda     const char* errorMessage = e->name;
27766b5ca76Sjayaprakash Mutyala     if (strcmp(errorMessage,
27866b5ca76Sjayaprakash Mutyala                "xyz.openbmc_project.User.Common.Error.UserNameExists") == 0)
27966b5ca76Sjayaprakash Mutyala     {
280d8a5d5d8SJiaqing Zhao         messages::resourceAlreadyExists(asyncResp->res, "ManagerAccount",
28166b5ca76Sjayaprakash Mutyala                                         "UserName", newUser);
28266b5ca76Sjayaprakash Mutyala     }
28366b5ca76Sjayaprakash Mutyala     else if (strcmp(errorMessage, "xyz.openbmc_project.User.Common.Error."
28466b5ca76Sjayaprakash Mutyala                                   "UserNameDoesNotExist") == 0)
28566b5ca76Sjayaprakash Mutyala     {
286d8a5d5d8SJiaqing Zhao         messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
28766b5ca76Sjayaprakash Mutyala     }
288d4d25793SEd Tanous     else if ((strcmp(errorMessage,
289d4d25793SEd Tanous                      "xyz.openbmc_project.Common.Error.InvalidArgument") ==
290d4d25793SEd Tanous               0) ||
2910fda0f12SGeorge Liu              (strcmp(
2920fda0f12SGeorge Liu                   errorMessage,
2930fda0f12SGeorge Liu                   "xyz.openbmc_project.User.Common.Error.UserNameGroupFail") ==
2940fda0f12SGeorge Liu               0))
29566b5ca76Sjayaprakash Mutyala     {
29666b5ca76Sjayaprakash Mutyala         messages::propertyValueFormatError(asyncResp->res, newUser, "UserName");
29766b5ca76Sjayaprakash Mutyala     }
29866b5ca76Sjayaprakash Mutyala     else if (strcmp(errorMessage,
29966b5ca76Sjayaprakash Mutyala                     "xyz.openbmc_project.User.Common.Error.NoResource") == 0)
30066b5ca76Sjayaprakash Mutyala     {
30166b5ca76Sjayaprakash Mutyala         messages::createLimitReachedForResource(asyncResp->res);
30266b5ca76Sjayaprakash Mutyala     }
30366b5ca76Sjayaprakash Mutyala     else
30466b5ca76Sjayaprakash Mutyala     {
305b8ad583fSGunnar Mills         BMCWEB_LOG_ERROR("DBUS response error {}", errorMessage);
30666b5ca76Sjayaprakash Mutyala         messages::internalError(asyncResp->res);
30766b5ca76Sjayaprakash Mutyala     }
30866b5ca76Sjayaprakash Mutyala }
30966b5ca76Sjayaprakash Mutyala 
31081ce609eSEd Tanous inline void parseLDAPConfigData(nlohmann::json& jsonResponse,
311ab828d7cSRatan Gupta                                 const LDAPConfigData& confData,
312ab828d7cSRatan Gupta                                 const std::string& ldapType)
3136973a582SRatan Gupta {
31449cc263fSEd Tanous     nlohmann::json::object_t ldap;
3151476687dSEd Tanous     ldap["ServiceEnabled"] = confData.serviceEnabled;
31649cc263fSEd Tanous     nlohmann::json::array_t serviceAddresses;
31749cc263fSEd Tanous     serviceAddresses.emplace_back(confData.uri);
31849cc263fSEd Tanous     ldap["ServiceAddresses"] = std::move(serviceAddresses);
31949cc263fSEd Tanous 
32049cc263fSEd Tanous     nlohmann::json::object_t authentication;
32149cc263fSEd Tanous     authentication["AuthenticationType"] =
3220ec8b83dSEd Tanous         account_service::AuthenticationTypes::UsernameAndPassword;
32349cc263fSEd Tanous     authentication["Username"] = confData.bindDN;
32449cc263fSEd Tanous     authentication["Password"] = nullptr;
32549cc263fSEd Tanous     ldap["Authentication"] = std::move(authentication);
3261476687dSEd Tanous 
32749cc263fSEd Tanous     nlohmann::json::object_t ldapService;
32849cc263fSEd Tanous     nlohmann::json::object_t searchSettings;
32949cc263fSEd Tanous     nlohmann::json::array_t baseDistinguishedNames;
33049cc263fSEd Tanous     baseDistinguishedNames.emplace_back(confData.baseDN);
3311476687dSEd Tanous 
33249cc263fSEd Tanous     searchSettings["BaseDistinguishedNames"] =
33349cc263fSEd Tanous         std::move(baseDistinguishedNames);
33449cc263fSEd Tanous     searchSettings["UsernameAttribute"] = confData.userNameAttribute;
33549cc263fSEd Tanous     searchSettings["GroupsAttribute"] = confData.groupAttribute;
33649cc263fSEd Tanous     ldapService["SearchSettings"] = std::move(searchSettings);
33749cc263fSEd Tanous     ldap["LDAPService"] = std::move(ldapService);
33849cc263fSEd Tanous 
33949cc263fSEd Tanous     nlohmann::json::array_t roleMapArray;
3409eb808c1SEd Tanous     for (const auto& obj : confData.groupRoleList)
34154fc587aSNagaraju Goruganti     {
34262598e31SEd Tanous         BMCWEB_LOG_DEBUG("Pushing the data groupName={}", obj.second.groupName);
343613dabeaSEd Tanous 
344613dabeaSEd Tanous         nlohmann::json::object_t remoteGroup;
345613dabeaSEd Tanous         remoteGroup["RemoteGroup"] = obj.second.groupName;
346329f0348SJorge Cisneros         remoteGroup["LocalRole"] = getRoleIdFromPrivilege(obj.second.privilege);
347329f0348SJorge Cisneros         roleMapArray.emplace_back(std::move(remoteGroup));
34854fc587aSNagaraju Goruganti     }
34949cc263fSEd Tanous 
35049cc263fSEd Tanous     ldap["RemoteRoleMapping"] = std::move(roleMapArray);
35149cc263fSEd Tanous 
35249cc263fSEd Tanous     jsonResponse[ldapType].update(ldap);
3536973a582SRatan Gupta }
3546973a582SRatan Gupta 
3556973a582SRatan Gupta /**
35606785244SRatan Gupta  *  @brief validates given JSON input and then calls appropriate method to
35706785244SRatan Gupta  * create, to delete or to set Rolemapping object based on the given input.
35806785244SRatan Gupta  *
35906785244SRatan Gupta  */
36023a21a1cSEd Tanous inline void handleRoleMapPatch(
3618d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
36206785244SRatan Gupta     const std::vector<std::pair<std::string, LDAPRoleMapData>>& roleMapObjData,
363f23b7296SEd Tanous     const std::string& serverType, const std::vector<nlohmann::json>& input)
36406785244SRatan Gupta {
36506785244SRatan Gupta     for (size_t index = 0; index < input.size(); index++)
36606785244SRatan Gupta     {
367f23b7296SEd Tanous         const nlohmann::json& thisJson = input[index];
36806785244SRatan Gupta 
36906785244SRatan Gupta         if (thisJson.is_null())
37006785244SRatan Gupta         {
37106785244SRatan Gupta             // delete the existing object
37206785244SRatan Gupta             if (index < roleMapObjData.size())
37306785244SRatan Gupta             {
37406785244SRatan Gupta                 crow::connections::systemBus->async_method_call(
37506785244SRatan Gupta                     [asyncResp, roleMapObjData, serverType,
3765e7e2dc5SEd Tanous                      index](const boost::system::error_code& ec) {
37706785244SRatan Gupta                     if (ec)
37806785244SRatan Gupta                     {
37962598e31SEd Tanous                         BMCWEB_LOG_ERROR("DBUS response error: {}", ec);
38006785244SRatan Gupta                         messages::internalError(asyncResp->res);
38106785244SRatan Gupta                         return;
38206785244SRatan Gupta                     }
38389492a15SPatrick Williams                     asyncResp->res.jsonValue[serverType]["RemoteRoleMapping"]
38489492a15SPatrick Williams                                             [index] = nullptr;
38506785244SRatan Gupta                 },
38606785244SRatan Gupta                     ldapDbusService, roleMapObjData[index].first,
38706785244SRatan Gupta                     "xyz.openbmc_project.Object.Delete", "Delete");
38806785244SRatan Gupta             }
38906785244SRatan Gupta             else
39006785244SRatan Gupta             {
39162598e31SEd Tanous                 BMCWEB_LOG_ERROR("Can't delete the object");
3922e8c4bdaSEd Tanous                 messages::propertyValueTypeError(asyncResp->res, thisJson,
3932e8c4bdaSEd Tanous                                                  "RemoteRoleMapping/" +
3942e8c4bdaSEd Tanous                                                      std::to_string(index));
39506785244SRatan Gupta                 return;
39606785244SRatan Gupta             }
39706785244SRatan Gupta         }
39806785244SRatan Gupta         else if (thisJson.empty())
39906785244SRatan Gupta         {
40006785244SRatan Gupta             // Don't do anything for the empty objects,parse next json
40106785244SRatan Gupta             // eg {"RemoteRoleMapping",[{}]}
40206785244SRatan Gupta         }
40306785244SRatan Gupta         else
40406785244SRatan Gupta         {
40506785244SRatan Gupta             // update/create the object
40606785244SRatan Gupta             std::optional<std::string> remoteGroup;
40706785244SRatan Gupta             std::optional<std::string> localRole;
40806785244SRatan Gupta 
409f23b7296SEd Tanous             // This is a copy, but it's required in this case because of how
410f23b7296SEd Tanous             // readJson is structured
411f23b7296SEd Tanous             nlohmann::json thisJsonCopy = thisJson;
412f23b7296SEd Tanous             if (!json_util::readJson(thisJsonCopy, asyncResp->res,
413f23b7296SEd Tanous                                      "RemoteGroup", remoteGroup, "LocalRole",
414f23b7296SEd Tanous                                      localRole))
41506785244SRatan Gupta             {
41606785244SRatan Gupta                 continue;
41706785244SRatan Gupta             }
41806785244SRatan Gupta 
41906785244SRatan Gupta             // Update existing RoleMapping Object
42006785244SRatan Gupta             if (index < roleMapObjData.size())
42106785244SRatan Gupta             {
42262598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Update Role Map Object");
42306785244SRatan Gupta                 // If "RemoteGroup" info is provided
42406785244SRatan Gupta                 if (remoteGroup)
42506785244SRatan Gupta                 {
426*d02aad39SEd Tanous                     setDbusProperty(
427*d02aad39SEd Tanous                         asyncResp, ldapDbusService, roleMapObjData[index].first,
4289ae226faSGeorge Liu                         "xyz.openbmc_project.User.PrivilegeMapperEntry",
429*d02aad39SEd Tanous                         "GroupName",
430*d02aad39SEd Tanous                         std::format("RemoteRoleMapping/{}/RemoteGroup", index),
43125e055a3SRavi Teja                         *remoteGroup);
43206785244SRatan Gupta                 }
43306785244SRatan Gupta 
43406785244SRatan Gupta                 // If "LocalRole" info is provided
43506785244SRatan Gupta                 if (localRole)
43606785244SRatan Gupta                 {
437*d02aad39SEd Tanous                     setDbusProperty(
438*d02aad39SEd Tanous                         asyncResp, ldapDbusService, roleMapObjData[index].first,
4399ae226faSGeorge Liu                         "xyz.openbmc_project.User.PrivilegeMapperEntry",
440*d02aad39SEd Tanous                         "Privilege",
441*d02aad39SEd Tanous                         std::format("RemoteRoleMapping/{}/LocalRole", index),
442*d02aad39SEd Tanous                         *localRole);
44306785244SRatan Gupta                 }
44406785244SRatan Gupta             }
44506785244SRatan Gupta             // Create a new RoleMapping Object.
44606785244SRatan Gupta             else
44706785244SRatan Gupta             {
44862598e31SEd Tanous                 BMCWEB_LOG_DEBUG(
44962598e31SEd Tanous                     "setRoleMappingProperties: Creating new Object");
45089492a15SPatrick Williams                 std::string pathString = "RemoteRoleMapping/" +
45189492a15SPatrick Williams                                          std::to_string(index);
45206785244SRatan Gupta 
45306785244SRatan Gupta                 if (!localRole)
45406785244SRatan Gupta                 {
45506785244SRatan Gupta                     messages::propertyMissing(asyncResp->res,
45606785244SRatan Gupta                                               pathString + "/LocalRole");
45706785244SRatan Gupta                     continue;
45806785244SRatan Gupta                 }
45906785244SRatan Gupta                 if (!remoteGroup)
46006785244SRatan Gupta                 {
46106785244SRatan Gupta                     messages::propertyMissing(asyncResp->res,
46206785244SRatan Gupta                                               pathString + "/RemoteGroup");
46306785244SRatan Gupta                     continue;
46406785244SRatan Gupta                 }
46506785244SRatan Gupta 
46606785244SRatan Gupta                 std::string dbusObjectPath;
46706785244SRatan Gupta                 if (serverType == "ActiveDirectory")
46806785244SRatan Gupta                 {
4692c70f800SEd Tanous                     dbusObjectPath = adConfigObject;
47006785244SRatan Gupta                 }
47106785244SRatan Gupta                 else if (serverType == "LDAP")
47206785244SRatan Gupta                 {
47323a21a1cSEd Tanous                     dbusObjectPath = ldapConfigObjectName;
47406785244SRatan Gupta                 }
47506785244SRatan Gupta 
47662598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Remote Group={},LocalRole={}", *remoteGroup,
47762598e31SEd Tanous                                  *localRole);
47806785244SRatan Gupta 
47906785244SRatan Gupta                 crow::connections::systemBus->async_method_call(
480271584abSEd Tanous                     [asyncResp, serverType, localRole,
4815e7e2dc5SEd Tanous                      remoteGroup](const boost::system::error_code& ec) {
48206785244SRatan Gupta                     if (ec)
48306785244SRatan Gupta                     {
48462598e31SEd Tanous                         BMCWEB_LOG_ERROR("DBUS response error: {}", ec);
48506785244SRatan Gupta                         messages::internalError(asyncResp->res);
48606785244SRatan Gupta                         return;
48706785244SRatan Gupta                     }
48806785244SRatan Gupta                     nlohmann::json& remoteRoleJson =
48906785244SRatan Gupta                         asyncResp->res
49006785244SRatan Gupta                             .jsonValue[serverType]["RemoteRoleMapping"];
4911476687dSEd Tanous                     nlohmann::json::object_t roleMapEntry;
4921476687dSEd Tanous                     roleMapEntry["LocalRole"] = *localRole;
4931476687dSEd Tanous                     roleMapEntry["RemoteGroup"] = *remoteGroup;
494b2ba3072SPatrick Williams                     remoteRoleJson.emplace_back(std::move(roleMapEntry));
49506785244SRatan Gupta                 },
49606785244SRatan Gupta                     ldapDbusService, dbusObjectPath, ldapPrivMapperInterface,
4973174e4dfSEd Tanous                     "Create", *remoteGroup,
49806785244SRatan Gupta                     getPrivilegeFromRoleId(std::move(*localRole)));
49906785244SRatan Gupta             }
50006785244SRatan Gupta         }
50106785244SRatan Gupta     }
50206785244SRatan Gupta }
50306785244SRatan Gupta 
50406785244SRatan Gupta /**
5056973a582SRatan Gupta  * Function that retrieves all properties for LDAP config object
5066973a582SRatan Gupta  * into JSON
5076973a582SRatan Gupta  */
5086973a582SRatan Gupta template <typename CallbackFunc>
5096973a582SRatan Gupta inline void getLDAPConfigData(const std::string& ldapType,
5106973a582SRatan Gupta                               CallbackFunc&& callback)
5116973a582SRatan Gupta {
5122b73119cSGeorge Liu     constexpr std::array<std::string_view, 2> interfaces = {
5132b73119cSGeorge Liu         ldapEnableInterface, ldapConfigInterface};
51454fc587aSNagaraju Goruganti 
5152b73119cSGeorge Liu     dbus::utility::getDbusObject(
5162b73119cSGeorge Liu         ldapConfigObjectName, interfaces,
5172b73119cSGeorge Liu         [callback, ldapType](const boost::system::error_code& ec,
518b9d36b47SEd Tanous                              const dbus::utility::MapperGetObject& resp) {
51954fc587aSNagaraju Goruganti         if (ec || resp.empty())
52054fc587aSNagaraju Goruganti         {
521bf2ddedeSCarson Labrado             BMCWEB_LOG_WARNING(
52262598e31SEd Tanous                 "DBUS response error during getting of service name: {}", ec);
52323a21a1cSEd Tanous             LDAPConfigData empty{};
52423a21a1cSEd Tanous             callback(false, empty, ldapType);
52554fc587aSNagaraju Goruganti             return;
52654fc587aSNagaraju Goruganti         }
52754fc587aSNagaraju Goruganti         std::string service = resp.begin()->first;
5285eb468daSGeorge Liu         sdbusplus::message::object_path path(ldapRootObject);
5295eb468daSGeorge Liu         dbus::utility::getManagedObjects(
5305eb468daSGeorge Liu             service, path,
531002d39b4SEd Tanous             [callback,
5328b24275dSEd Tanous              ldapType](const boost::system::error_code& ec2,
533711ac7a9SEd Tanous                        const dbus::utility::ManagedObjectType& ldapObjects) {
5346973a582SRatan Gupta             LDAPConfigData confData{};
5358b24275dSEd Tanous             if (ec2)
5366973a582SRatan Gupta             {
537ab828d7cSRatan Gupta                 callback(false, confData, ldapType);
538bf2ddedeSCarson Labrado                 BMCWEB_LOG_WARNING("D-Bus responses error: {}", ec2);
5396973a582SRatan Gupta                 return;
5406973a582SRatan Gupta             }
541ab828d7cSRatan Gupta 
542ab828d7cSRatan Gupta             std::string ldapDbusType;
54354fc587aSNagaraju Goruganti             std::string searchString;
54454fc587aSNagaraju Goruganti 
545ab828d7cSRatan Gupta             if (ldapType == "LDAP")
546ab828d7cSRatan Gupta             {
5470fda0f12SGeorge Liu                 ldapDbusType =
5480fda0f12SGeorge Liu                     "xyz.openbmc_project.User.Ldap.Config.Type.OpenLdap";
54954fc587aSNagaraju Goruganti                 searchString = "openldap";
550ab828d7cSRatan Gupta             }
551ab828d7cSRatan Gupta             else if (ldapType == "ActiveDirectory")
552ab828d7cSRatan Gupta             {
55354fc587aSNagaraju Goruganti                 ldapDbusType =
5540fda0f12SGeorge Liu                     "xyz.openbmc_project.User.Ldap.Config.Type.ActiveDirectory";
55554fc587aSNagaraju Goruganti                 searchString = "active_directory";
556ab828d7cSRatan Gupta             }
557ab828d7cSRatan Gupta             else
558ab828d7cSRatan Gupta             {
55962598e31SEd Tanous                 BMCWEB_LOG_ERROR("Can't get the DbusType for the given type={}",
56062598e31SEd Tanous                                  ldapType);
561ab828d7cSRatan Gupta                 callback(false, confData, ldapType);
562ab828d7cSRatan Gupta                 return;
563ab828d7cSRatan Gupta             }
564ab828d7cSRatan Gupta 
565ab828d7cSRatan Gupta             std::string ldapEnableInterfaceStr = ldapEnableInterface;
566ab828d7cSRatan Gupta             std::string ldapConfigInterfaceStr = ldapConfigInterface;
567ab828d7cSRatan Gupta 
5686973a582SRatan Gupta             for (const auto& object : ldapObjects)
5696973a582SRatan Gupta             {
57054fc587aSNagaraju Goruganti                 // let's find the object whose ldap type is equal to the
57154fc587aSNagaraju Goruganti                 // given type
572002d39b4SEd Tanous                 if (object.first.str.find(searchString) == std::string::npos)
5736973a582SRatan Gupta                 {
574ab828d7cSRatan Gupta                     continue;
575ab828d7cSRatan Gupta                 }
576ab828d7cSRatan Gupta 
5776973a582SRatan Gupta                 for (const auto& interface : object.second)
5786973a582SRatan Gupta                 {
5796973a582SRatan Gupta                     if (interface.first == ldapEnableInterfaceStr)
5806973a582SRatan Gupta                     {
5816973a582SRatan Gupta                         // rest of the properties are string.
5826973a582SRatan Gupta                         for (const auto& property : interface.second)
5836973a582SRatan Gupta                         {
5846973a582SRatan Gupta                             if (property.first == "Enabled")
5856973a582SRatan Gupta                             {
5866973a582SRatan Gupta                                 const bool* value =
5876973a582SRatan Gupta                                     std::get_if<bool>(&property.second);
5886973a582SRatan Gupta                                 if (value == nullptr)
5896973a582SRatan Gupta                                 {
5906973a582SRatan Gupta                                     continue;
5916973a582SRatan Gupta                                 }
5926973a582SRatan Gupta                                 confData.serviceEnabled = *value;
5936973a582SRatan Gupta                                 break;
5946973a582SRatan Gupta                             }
5956973a582SRatan Gupta                         }
5966973a582SRatan Gupta                     }
5976973a582SRatan Gupta                     else if (interface.first == ldapConfigInterfaceStr)
5986973a582SRatan Gupta                     {
5996973a582SRatan Gupta                         for (const auto& property : interface.second)
6006973a582SRatan Gupta                         {
601271584abSEd Tanous                             const std::string* strValue =
602002d39b4SEd Tanous                                 std::get_if<std::string>(&property.second);
603271584abSEd Tanous                             if (strValue == nullptr)
6046973a582SRatan Gupta                             {
6056973a582SRatan Gupta                                 continue;
6066973a582SRatan Gupta                             }
6076973a582SRatan Gupta                             if (property.first == "LDAPServerURI")
6086973a582SRatan Gupta                             {
609271584abSEd Tanous                                 confData.uri = *strValue;
6106973a582SRatan Gupta                             }
6116973a582SRatan Gupta                             else if (property.first == "LDAPBindDN")
6126973a582SRatan Gupta                             {
613271584abSEd Tanous                                 confData.bindDN = *strValue;
6146973a582SRatan Gupta                             }
6156973a582SRatan Gupta                             else if (property.first == "LDAPBaseDN")
6166973a582SRatan Gupta                             {
617271584abSEd Tanous                                 confData.baseDN = *strValue;
6186973a582SRatan Gupta                             }
619002d39b4SEd Tanous                             else if (property.first == "LDAPSearchScope")
6206973a582SRatan Gupta                             {
621271584abSEd Tanous                                 confData.searchScope = *strValue;
6226973a582SRatan Gupta                             }
623002d39b4SEd Tanous                             else if (property.first == "GroupNameAttribute")
6246973a582SRatan Gupta                             {
625271584abSEd Tanous                                 confData.groupAttribute = *strValue;
6266973a582SRatan Gupta                             }
627002d39b4SEd Tanous                             else if (property.first == "UserNameAttribute")
6286973a582SRatan Gupta                             {
629271584abSEd Tanous                                 confData.userNameAttribute = *strValue;
6306973a582SRatan Gupta                             }
63154fc587aSNagaraju Goruganti                             else if (property.first == "LDAPType")
632ab828d7cSRatan Gupta                             {
633271584abSEd Tanous                                 confData.serverType = *strValue;
63454fc587aSNagaraju Goruganti                             }
63554fc587aSNagaraju Goruganti                         }
63654fc587aSNagaraju Goruganti                     }
637002d39b4SEd Tanous                     else if (interface.first ==
6380fda0f12SGeorge Liu                              "xyz.openbmc_project.User.PrivilegeMapperEntry")
63954fc587aSNagaraju Goruganti                     {
64054fc587aSNagaraju Goruganti                         LDAPRoleMapData roleMapData{};
64154fc587aSNagaraju Goruganti                         for (const auto& property : interface.second)
64254fc587aSNagaraju Goruganti                         {
643271584abSEd Tanous                             const std::string* strValue =
644002d39b4SEd Tanous                                 std::get_if<std::string>(&property.second);
64554fc587aSNagaraju Goruganti 
646271584abSEd Tanous                             if (strValue == nullptr)
64754fc587aSNagaraju Goruganti                             {
64854fc587aSNagaraju Goruganti                                 continue;
64954fc587aSNagaraju Goruganti                             }
65054fc587aSNagaraju Goruganti 
65154fc587aSNagaraju Goruganti                             if (property.first == "GroupName")
65254fc587aSNagaraju Goruganti                             {
653271584abSEd Tanous                                 roleMapData.groupName = *strValue;
65454fc587aSNagaraju Goruganti                             }
65554fc587aSNagaraju Goruganti                             else if (property.first == "Privilege")
65654fc587aSNagaraju Goruganti                             {
657271584abSEd Tanous                                 roleMapData.privilege = *strValue;
65854fc587aSNagaraju Goruganti                             }
65954fc587aSNagaraju Goruganti                         }
66054fc587aSNagaraju Goruganti 
661002d39b4SEd Tanous                         confData.groupRoleList.emplace_back(object.first.str,
662002d39b4SEd Tanous                                                             roleMapData);
66354fc587aSNagaraju Goruganti                     }
66454fc587aSNagaraju Goruganti                 }
66554fc587aSNagaraju Goruganti             }
666ab828d7cSRatan Gupta             callback(true, confData, ldapType);
6675eb468daSGeorge Liu         });
6682b73119cSGeorge Liu     });
6696973a582SRatan Gupta }
6706973a582SRatan Gupta 
6718a07d286SRatan Gupta /**
6728a07d286SRatan Gupta  * @brief parses the authentication section under the LDAP
6738a07d286SRatan Gupta  * @param input JSON data
6748a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
6758a07d286SRatan Gupta  * @param userName  userName to be filled from the given JSON.
6768a07d286SRatan Gupta  * @param password  password to be filled from the given JSON.
6778a07d286SRatan Gupta  */
6784f48d5f6SEd Tanous inline void parseLDAPAuthenticationJson(
6796c51eab1SEd Tanous     nlohmann::json input, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
6806c51eab1SEd Tanous     std::optional<std::string>& username, std::optional<std::string>& password)
6818a07d286SRatan Gupta {
6828a07d286SRatan Gupta     std::optional<std::string> authType;
6838a07d286SRatan Gupta 
6848a07d286SRatan Gupta     if (!json_util::readJson(input, asyncResp->res, "AuthenticationType",
6858a07d286SRatan Gupta                              authType, "Username", username, "Password",
6868a07d286SRatan Gupta                              password))
6878a07d286SRatan Gupta     {
6888a07d286SRatan Gupta         return;
6898a07d286SRatan Gupta     }
6908a07d286SRatan Gupta     if (!authType)
6918a07d286SRatan Gupta     {
6928a07d286SRatan Gupta         return;
6938a07d286SRatan Gupta     }
6948a07d286SRatan Gupta     if (*authType != "UsernameAndPassword")
6958a07d286SRatan Gupta     {
6968a07d286SRatan Gupta         messages::propertyValueNotInList(asyncResp->res, *authType,
6978a07d286SRatan Gupta                                          "AuthenticationType");
6988a07d286SRatan Gupta         return;
6998a07d286SRatan Gupta     }
7008a07d286SRatan Gupta }
7018a07d286SRatan Gupta /**
7028a07d286SRatan Gupta  * @brief parses the LDAPService section under the LDAP
7038a07d286SRatan Gupta  * @param input JSON data
7048a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7058a07d286SRatan Gupta  * @param baseDNList baseDN to be filled from the given JSON.
7068a07d286SRatan Gupta  * @param userNameAttribute  userName to be filled from the given JSON.
7078a07d286SRatan Gupta  * @param groupaAttribute  password to be filled from the given JSON.
7088a07d286SRatan Gupta  */
7098a07d286SRatan Gupta 
7104f48d5f6SEd Tanous inline void
7114f48d5f6SEd Tanous     parseLDAPServiceJson(nlohmann::json input,
7128d1b46d7Szhanghch05                          const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7138a07d286SRatan Gupta                          std::optional<std::vector<std::string>>& baseDNList,
7148a07d286SRatan Gupta                          std::optional<std::string>& userNameAttribute,
7158a07d286SRatan Gupta                          std::optional<std::string>& groupsAttribute)
7168a07d286SRatan Gupta {
7178a07d286SRatan Gupta     std::optional<nlohmann::json> searchSettings;
7188a07d286SRatan Gupta 
7198a07d286SRatan Gupta     if (!json_util::readJson(input, asyncResp->res, "SearchSettings",
7208a07d286SRatan Gupta                              searchSettings))
7218a07d286SRatan Gupta     {
7228a07d286SRatan Gupta         return;
7238a07d286SRatan Gupta     }
7248a07d286SRatan Gupta     if (!searchSettings)
7258a07d286SRatan Gupta     {
7268a07d286SRatan Gupta         return;
7278a07d286SRatan Gupta     }
7288a07d286SRatan Gupta     if (!json_util::readJson(*searchSettings, asyncResp->res,
7298a07d286SRatan Gupta                              "BaseDistinguishedNames", baseDNList,
7308a07d286SRatan Gupta                              "UsernameAttribute", userNameAttribute,
7318a07d286SRatan Gupta                              "GroupsAttribute", groupsAttribute))
7328a07d286SRatan Gupta     {
7338a07d286SRatan Gupta         return;
7348a07d286SRatan Gupta     }
7358a07d286SRatan Gupta }
7368a07d286SRatan Gupta /**
7378a07d286SRatan Gupta  * @brief updates the LDAP server address and updates the
7388a07d286SRatan Gupta           json response with the new value.
7398a07d286SRatan Gupta  * @param serviceAddressList address to be updated.
7408a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7418a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7428a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7438a07d286SRatan Gupta  */
7448a07d286SRatan Gupta 
7454f48d5f6SEd Tanous inline void handleServiceAddressPatch(
7468a07d286SRatan Gupta     const std::vector<std::string>& serviceAddressList,
7478d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7488a07d286SRatan Gupta     const std::string& ldapServerElementName,
7498a07d286SRatan Gupta     const std::string& ldapConfigObject)
7508a07d286SRatan Gupta {
751*d02aad39SEd Tanous     setDbusProperty(asyncResp, ldapDbusService, ldapConfigObject,
752*d02aad39SEd Tanous                     ldapConfigInterface, "LDAPServerURI",
753*d02aad39SEd Tanous                     ldapServerElementName + "/ServiceAddress",
75425e055a3SRavi Teja                     serviceAddressList.front());
7558a07d286SRatan Gupta }
7568a07d286SRatan Gupta /**
7578a07d286SRatan Gupta  * @brief updates the LDAP Bind DN and updates the
7588a07d286SRatan Gupta           json response with the new value.
7598a07d286SRatan Gupta  * @param username name of the user which needs to be updated.
7608a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7618a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7628a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7638a07d286SRatan Gupta  */
7648a07d286SRatan Gupta 
7654f48d5f6SEd Tanous inline void
7664f48d5f6SEd Tanous     handleUserNamePatch(const std::string& username,
7678d1b46d7Szhanghch05                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7688a07d286SRatan Gupta                         const std::string& ldapServerElementName,
7698a07d286SRatan Gupta                         const std::string& ldapConfigObject)
7708a07d286SRatan Gupta {
771*d02aad39SEd Tanous     setDbusProperty(asyncResp, ldapDbusService, ldapConfigObject,
772*d02aad39SEd Tanous                     ldapConfigInterface, "LDAPBindDN",
773*d02aad39SEd Tanous                     ldapServerElementName + "/Authentication/Username",
774*d02aad39SEd Tanous                     username);
7758a07d286SRatan Gupta }
7768a07d286SRatan Gupta 
7778a07d286SRatan Gupta /**
7788a07d286SRatan Gupta  * @brief updates the LDAP password
7798a07d286SRatan Gupta  * @param password : ldap password which needs to be updated.
7808a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7818a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7828a07d286SRatan Gupta  *        server(openLDAP/ActiveDirectory)
7838a07d286SRatan Gupta  */
7848a07d286SRatan Gupta 
7854f48d5f6SEd Tanous inline void
7864f48d5f6SEd Tanous     handlePasswordPatch(const std::string& password,
7878d1b46d7Szhanghch05                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7888a07d286SRatan Gupta                         const std::string& ldapServerElementName,
7898a07d286SRatan Gupta                         const std::string& ldapConfigObject)
7908a07d286SRatan Gupta {
791*d02aad39SEd Tanous     setDbusProperty(asyncResp, ldapDbusService, ldapConfigObject,
792*d02aad39SEd Tanous                     ldapConfigInterface, "LDAPBindDNPassword",
793*d02aad39SEd Tanous                     ldapServerElementName + "/Authentication/Password",
794*d02aad39SEd Tanous                     password);
7958a07d286SRatan Gupta }
7968a07d286SRatan Gupta 
7978a07d286SRatan Gupta /**
7988a07d286SRatan Gupta  * @brief updates the LDAP BaseDN and updates the
7998a07d286SRatan Gupta           json response with the new value.
8008a07d286SRatan Gupta  * @param baseDNList baseDN list which needs to be updated.
8018a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
8028a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
8038a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
8048a07d286SRatan Gupta  */
8058a07d286SRatan Gupta 
8064f48d5f6SEd Tanous inline void
8074f48d5f6SEd Tanous     handleBaseDNPatch(const std::vector<std::string>& baseDNList,
8088d1b46d7Szhanghch05                       const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8098a07d286SRatan Gupta                       const std::string& ldapServerElementName,
8108a07d286SRatan Gupta                       const std::string& ldapConfigObject)
8118a07d286SRatan Gupta {
812*d02aad39SEd Tanous     setDbusProperty(asyncResp, ldapDbusService, ldapConfigObject,
813*d02aad39SEd Tanous                     ldapConfigInterface, "LDAPBaseDN",
814*d02aad39SEd Tanous                     ldapServerElementName +
815*d02aad39SEd Tanous                         "/LDAPService/SearchSettings/BaseDistinguishedNames",
81625e055a3SRavi Teja                     baseDNList.front());
8178a07d286SRatan Gupta }
8188a07d286SRatan Gupta /**
8198a07d286SRatan Gupta  * @brief updates the LDAP user name attribute and updates the
8208a07d286SRatan Gupta           json response with the new value.
8218a07d286SRatan Gupta  * @param userNameAttribute attribute to be updated.
8228a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
8238a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
8248a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
8258a07d286SRatan Gupta  */
8268a07d286SRatan Gupta 
8274f48d5f6SEd Tanous inline void
8284f48d5f6SEd Tanous     handleUserNameAttrPatch(const std::string& userNameAttribute,
8298d1b46d7Szhanghch05                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8308a07d286SRatan Gupta                             const std::string& ldapServerElementName,
8318a07d286SRatan Gupta                             const std::string& ldapConfigObject)
8328a07d286SRatan Gupta {
833*d02aad39SEd Tanous     setDbusProperty(asyncResp, ldapDbusService, ldapConfigObject,
834*d02aad39SEd Tanous                     ldapConfigInterface, "UserNameAttribute",
835*d02aad39SEd Tanous                     ldapServerElementName +
836*d02aad39SEd Tanous                         "LDAPService/SearchSettings/UsernameAttribute",
837*d02aad39SEd Tanous                     userNameAttribute);
8388a07d286SRatan Gupta }
8398a07d286SRatan Gupta /**
8408a07d286SRatan Gupta  * @brief updates the LDAP group attribute and updates the
8418a07d286SRatan Gupta           json response with the new value.
8428a07d286SRatan Gupta  * @param groupsAttribute attribute to be updated.
8438a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
8448a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
8458a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
8468a07d286SRatan Gupta  */
8478a07d286SRatan Gupta 
8484f48d5f6SEd Tanous inline void handleGroupNameAttrPatch(
8498d1b46d7Szhanghch05     const std::string& groupsAttribute,
8508d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8518a07d286SRatan Gupta     const std::string& ldapServerElementName,
8528a07d286SRatan Gupta     const std::string& ldapConfigObject)
8538a07d286SRatan Gupta {
854*d02aad39SEd Tanous     setDbusProperty(asyncResp, ldapDbusService, ldapConfigObject,
855*d02aad39SEd Tanous                     ldapConfigInterface, "GroupNameAttribute",
856*d02aad39SEd Tanous                     ldapServerElementName +
857*d02aad39SEd Tanous                         "/LDAPService/SearchSettings/GroupsAttribute",
858*d02aad39SEd Tanous                     groupsAttribute);
8598a07d286SRatan Gupta }
8608a07d286SRatan Gupta /**
8618a07d286SRatan Gupta  * @brief updates the LDAP service enable and updates the
8628a07d286SRatan Gupta           json response with the new value.
8638a07d286SRatan Gupta  * @param input JSON data.
8648a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
8658a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
8668a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
8678a07d286SRatan Gupta  */
8688a07d286SRatan Gupta 
8694f48d5f6SEd Tanous inline void handleServiceEnablePatch(
8706c51eab1SEd Tanous     bool serviceEnabled, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8718a07d286SRatan Gupta     const std::string& ldapServerElementName,
8728a07d286SRatan Gupta     const std::string& ldapConfigObject)
8738a07d286SRatan Gupta {
874*d02aad39SEd Tanous     setDbusProperty(asyncResp, ldapDbusService, ldapConfigObject,
875*d02aad39SEd Tanous                     ldapEnableInterface, "Enabled",
876*d02aad39SEd Tanous                     ldapServerElementName + "/ServiceEnabled", serviceEnabled);
8778a07d286SRatan Gupta }
8788a07d286SRatan Gupta 
8794f48d5f6SEd Tanous inline void
8804f48d5f6SEd Tanous     handleAuthMethodsPatch(nlohmann::json& input,
8818d1b46d7Szhanghch05                            const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
88278158631SZbigniew Kurzynski {
88378158631SZbigniew Kurzynski     std::optional<bool> basicAuth;
88478158631SZbigniew Kurzynski     std::optional<bool> cookie;
88578158631SZbigniew Kurzynski     std::optional<bool> sessionToken;
88678158631SZbigniew Kurzynski     std::optional<bool> xToken;
887501f1e58SZbigniew Kurzynski     std::optional<bool> tls;
88878158631SZbigniew Kurzynski 
88978158631SZbigniew Kurzynski     if (!json_util::readJson(input, asyncResp->res, "BasicAuth", basicAuth,
89078158631SZbigniew Kurzynski                              "Cookie", cookie, "SessionToken", sessionToken,
891501f1e58SZbigniew Kurzynski                              "XToken", xToken, "TLS", tls))
89278158631SZbigniew Kurzynski     {
89362598e31SEd Tanous         BMCWEB_LOG_ERROR("Cannot read values from AuthMethod tag");
89478158631SZbigniew Kurzynski         return;
89578158631SZbigniew Kurzynski     }
89678158631SZbigniew Kurzynski 
89778158631SZbigniew Kurzynski     // Make a copy of methods configuration
89852cc112dSEd Tanous     persistent_data::AuthConfigMethods authMethodsConfig =
89952cc112dSEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
90078158631SZbigniew Kurzynski 
90178158631SZbigniew Kurzynski     if (basicAuth)
90278158631SZbigniew Kurzynski     {
903f16f6263SAlan Kuo #ifndef BMCWEB_ENABLE_BASIC_AUTHENTICATION
904f16f6263SAlan Kuo         messages::actionNotSupported(
9050fda0f12SGeorge Liu             asyncResp->res,
9060fda0f12SGeorge Liu             "Setting BasicAuth when basic-auth feature is disabled");
907f16f6263SAlan Kuo         return;
908f16f6263SAlan Kuo #endif
90978158631SZbigniew Kurzynski         authMethodsConfig.basic = *basicAuth;
91078158631SZbigniew Kurzynski     }
91178158631SZbigniew Kurzynski 
91278158631SZbigniew Kurzynski     if (cookie)
91378158631SZbigniew Kurzynski     {
914f16f6263SAlan Kuo #ifndef BMCWEB_ENABLE_COOKIE_AUTHENTICATION
9150fda0f12SGeorge Liu         messages::actionNotSupported(
9160fda0f12SGeorge Liu             asyncResp->res,
9170fda0f12SGeorge Liu             "Setting Cookie when cookie-auth feature is disabled");
918f16f6263SAlan Kuo         return;
919f16f6263SAlan Kuo #endif
92078158631SZbigniew Kurzynski         authMethodsConfig.cookie = *cookie;
92178158631SZbigniew Kurzynski     }
92278158631SZbigniew Kurzynski 
92378158631SZbigniew Kurzynski     if (sessionToken)
92478158631SZbigniew Kurzynski     {
925f16f6263SAlan Kuo #ifndef BMCWEB_ENABLE_SESSION_AUTHENTICATION
926f16f6263SAlan Kuo         messages::actionNotSupported(
9270fda0f12SGeorge Liu             asyncResp->res,
9280fda0f12SGeorge Liu             "Setting SessionToken when session-auth feature is disabled");
929f16f6263SAlan Kuo         return;
930f16f6263SAlan Kuo #endif
93178158631SZbigniew Kurzynski         authMethodsConfig.sessionToken = *sessionToken;
93278158631SZbigniew Kurzynski     }
93378158631SZbigniew Kurzynski 
93478158631SZbigniew Kurzynski     if (xToken)
93578158631SZbigniew Kurzynski     {
936f16f6263SAlan Kuo #ifndef BMCWEB_ENABLE_XTOKEN_AUTHENTICATION
9370fda0f12SGeorge Liu         messages::actionNotSupported(
9380fda0f12SGeorge Liu             asyncResp->res,
9390fda0f12SGeorge Liu             "Setting XToken when xtoken-auth feature is disabled");
940f16f6263SAlan Kuo         return;
941f16f6263SAlan Kuo #endif
94278158631SZbigniew Kurzynski         authMethodsConfig.xtoken = *xToken;
94378158631SZbigniew Kurzynski     }
94478158631SZbigniew Kurzynski 
945501f1e58SZbigniew Kurzynski     if (tls)
946501f1e58SZbigniew Kurzynski     {
947f16f6263SAlan Kuo #ifndef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
9480fda0f12SGeorge Liu         messages::actionNotSupported(
9490fda0f12SGeorge Liu             asyncResp->res,
9500fda0f12SGeorge Liu             "Setting TLS when mutual-tls-auth feature is disabled");
951f16f6263SAlan Kuo         return;
952f16f6263SAlan Kuo #endif
953501f1e58SZbigniew Kurzynski         authMethodsConfig.tls = *tls;
954501f1e58SZbigniew Kurzynski     }
955501f1e58SZbigniew Kurzynski 
95678158631SZbigniew Kurzynski     if (!authMethodsConfig.basic && !authMethodsConfig.cookie &&
957501f1e58SZbigniew Kurzynski         !authMethodsConfig.sessionToken && !authMethodsConfig.xtoken &&
958501f1e58SZbigniew Kurzynski         !authMethodsConfig.tls)
95978158631SZbigniew Kurzynski     {
96078158631SZbigniew Kurzynski         // Do not allow user to disable everything
96178158631SZbigniew Kurzynski         messages::actionNotSupported(asyncResp->res,
96278158631SZbigniew Kurzynski                                      "of disabling all available methods");
96378158631SZbigniew Kurzynski         return;
96478158631SZbigniew Kurzynski     }
96578158631SZbigniew Kurzynski 
96652cc112dSEd Tanous     persistent_data::SessionStore::getInstance().updateAuthMethodsConfig(
96752cc112dSEd Tanous         authMethodsConfig);
96878158631SZbigniew Kurzynski     // Save configuration immediately
96952cc112dSEd Tanous     persistent_data::getConfig().writeData();
97078158631SZbigniew Kurzynski 
97178158631SZbigniew Kurzynski     messages::success(asyncResp->res);
97278158631SZbigniew Kurzynski }
97378158631SZbigniew Kurzynski 
9748a07d286SRatan Gupta /**
9758a07d286SRatan Gupta  * @brief Get the required values from the given JSON, validates the
9768a07d286SRatan Gupta  *        value and create the LDAP config object.
9778a07d286SRatan Gupta  * @param input JSON data
9788a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
9798a07d286SRatan Gupta  * @param serverType Type of LDAP server(openLDAP/ActiveDirectory)
9808a07d286SRatan Gupta  */
9818a07d286SRatan Gupta 
9826c51eab1SEd Tanous inline void handleLDAPPatch(nlohmann::json& input,
9838d1b46d7Szhanghch05                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
9848a07d286SRatan Gupta                             const std::string& serverType)
9858a07d286SRatan Gupta {
986eb2bbe56SRatan Gupta     std::string dbusObjectPath;
987eb2bbe56SRatan Gupta     if (serverType == "ActiveDirectory")
988eb2bbe56SRatan Gupta     {
9892c70f800SEd Tanous         dbusObjectPath = adConfigObject;
990eb2bbe56SRatan Gupta     }
991eb2bbe56SRatan Gupta     else if (serverType == "LDAP")
992eb2bbe56SRatan Gupta     {
99323a21a1cSEd Tanous         dbusObjectPath = ldapConfigObjectName;
994eb2bbe56SRatan Gupta     }
995cb13a392SEd Tanous     else
996cb13a392SEd Tanous     {
997cb13a392SEd Tanous         return;
998cb13a392SEd Tanous     }
999eb2bbe56SRatan Gupta 
10008a07d286SRatan Gupta     std::optional<nlohmann::json> authentication;
10018a07d286SRatan Gupta     std::optional<nlohmann::json> ldapService;
10028a07d286SRatan Gupta     std::optional<std::vector<std::string>> serviceAddressList;
10038a07d286SRatan Gupta     std::optional<bool> serviceEnabled;
10048a07d286SRatan Gupta     std::optional<std::vector<std::string>> baseDNList;
10058a07d286SRatan Gupta     std::optional<std::string> userNameAttribute;
10068a07d286SRatan Gupta     std::optional<std::string> groupsAttribute;
10078a07d286SRatan Gupta     std::optional<std::string> userName;
10088a07d286SRatan Gupta     std::optional<std::string> password;
100906785244SRatan Gupta     std::optional<std::vector<nlohmann::json>> remoteRoleMapData;
10108a07d286SRatan Gupta 
10118a07d286SRatan Gupta     if (!json_util::readJson(input, asyncResp->res, "Authentication",
10128a07d286SRatan Gupta                              authentication, "LDAPService", ldapService,
10138a07d286SRatan Gupta                              "ServiceAddresses", serviceAddressList,
101406785244SRatan Gupta                              "ServiceEnabled", serviceEnabled,
101506785244SRatan Gupta                              "RemoteRoleMapping", remoteRoleMapData))
10168a07d286SRatan Gupta     {
10178a07d286SRatan Gupta         return;
10188a07d286SRatan Gupta     }
10198a07d286SRatan Gupta 
10208a07d286SRatan Gupta     if (authentication)
10218a07d286SRatan Gupta     {
10228a07d286SRatan Gupta         parseLDAPAuthenticationJson(*authentication, asyncResp, userName,
10238a07d286SRatan Gupta                                     password);
10248a07d286SRatan Gupta     }
10258a07d286SRatan Gupta     if (ldapService)
10268a07d286SRatan Gupta     {
10278a07d286SRatan Gupta         parseLDAPServiceJson(*ldapService, asyncResp, baseDNList,
10288a07d286SRatan Gupta                              userNameAttribute, groupsAttribute);
10298a07d286SRatan Gupta     }
10308a07d286SRatan Gupta     if (serviceAddressList)
10318a07d286SRatan Gupta     {
103226f6976fSEd Tanous         if (serviceAddressList->empty())
10338a07d286SRatan Gupta         {
1034e2616cc5SEd Tanous             messages::propertyValueNotInList(
1035e2616cc5SEd Tanous                 asyncResp->res, *serviceAddressList, "ServiceAddress");
10368a07d286SRatan Gupta             return;
10378a07d286SRatan Gupta         }
10388a07d286SRatan Gupta     }
10398a07d286SRatan Gupta     if (baseDNList)
10408a07d286SRatan Gupta     {
104126f6976fSEd Tanous         if (baseDNList->empty())
10428a07d286SRatan Gupta         {
1043e2616cc5SEd Tanous             messages::propertyValueNotInList(asyncResp->res, *baseDNList,
10448a07d286SRatan Gupta                                              "BaseDistinguishedNames");
10458a07d286SRatan Gupta             return;
10468a07d286SRatan Gupta         }
10478a07d286SRatan Gupta     }
10488a07d286SRatan Gupta 
10498a07d286SRatan Gupta     // nothing to update, then return
10508a07d286SRatan Gupta     if (!userName && !password && !serviceAddressList && !baseDNList &&
105106785244SRatan Gupta         !userNameAttribute && !groupsAttribute && !serviceEnabled &&
105206785244SRatan Gupta         !remoteRoleMapData)
10538a07d286SRatan Gupta     {
10548a07d286SRatan Gupta         return;
10558a07d286SRatan Gupta     }
10568a07d286SRatan Gupta 
10578a07d286SRatan Gupta     // Get the existing resource first then keep modifying
10588a07d286SRatan Gupta     // whenever any property gets updated.
1059002d39b4SEd Tanous     getLDAPConfigData(
1060002d39b4SEd Tanous         serverType,
1061002d39b4SEd Tanous         [asyncResp, userName, password, baseDNList, userNameAttribute,
1062002d39b4SEd Tanous          groupsAttribute, serviceAddressList, serviceEnabled, dbusObjectPath,
1063002d39b4SEd Tanous          remoteRoleMapData](bool success, const LDAPConfigData& confData,
106423a21a1cSEd Tanous                             const std::string& serverT) {
10658a07d286SRatan Gupta         if (!success)
10668a07d286SRatan Gupta         {
10678a07d286SRatan Gupta             messages::internalError(asyncResp->res);
10688a07d286SRatan Gupta             return;
10698a07d286SRatan Gupta         }
10706c51eab1SEd Tanous         parseLDAPConfigData(asyncResp->res.jsonValue, confData, serverT);
10718a07d286SRatan Gupta         if (confData.serviceEnabled)
10728a07d286SRatan Gupta         {
10738a07d286SRatan Gupta             // Disable the service first and update the rest of
10748a07d286SRatan Gupta             // the properties.
10756c51eab1SEd Tanous             handleServiceEnablePatch(false, asyncResp, serverT, dbusObjectPath);
10768a07d286SRatan Gupta         }
10778a07d286SRatan Gupta 
10788a07d286SRatan Gupta         if (serviceAddressList)
10798a07d286SRatan Gupta         {
10806c51eab1SEd Tanous             handleServiceAddressPatch(*serviceAddressList, asyncResp, serverT,
10816c51eab1SEd Tanous                                       dbusObjectPath);
10828a07d286SRatan Gupta         }
10838a07d286SRatan Gupta         if (userName)
10848a07d286SRatan Gupta         {
10856c51eab1SEd Tanous             handleUserNamePatch(*userName, asyncResp, serverT, dbusObjectPath);
10868a07d286SRatan Gupta         }
10878a07d286SRatan Gupta         if (password)
10888a07d286SRatan Gupta         {
10896c51eab1SEd Tanous             handlePasswordPatch(*password, asyncResp, serverT, dbusObjectPath);
10908a07d286SRatan Gupta         }
10918a07d286SRatan Gupta 
10928a07d286SRatan Gupta         if (baseDNList)
10938a07d286SRatan Gupta         {
10946c51eab1SEd Tanous             handleBaseDNPatch(*baseDNList, asyncResp, serverT, dbusObjectPath);
10958a07d286SRatan Gupta         }
10968a07d286SRatan Gupta         if (userNameAttribute)
10978a07d286SRatan Gupta         {
10986c51eab1SEd Tanous             handleUserNameAttrPatch(*userNameAttribute, asyncResp, serverT,
10996c51eab1SEd Tanous                                     dbusObjectPath);
11008a07d286SRatan Gupta         }
11018a07d286SRatan Gupta         if (groupsAttribute)
11028a07d286SRatan Gupta         {
11036c51eab1SEd Tanous             handleGroupNameAttrPatch(*groupsAttribute, asyncResp, serverT,
11046c51eab1SEd Tanous                                      dbusObjectPath);
11058a07d286SRatan Gupta         }
11068a07d286SRatan Gupta         if (serviceEnabled)
11078a07d286SRatan Gupta         {
11088a07d286SRatan Gupta             // if user has given the value as true then enable
11098a07d286SRatan Gupta             // the service. if user has given false then no-op
11108a07d286SRatan Gupta             // as service is already stopped.
11118a07d286SRatan Gupta             if (*serviceEnabled)
11128a07d286SRatan Gupta             {
11136c51eab1SEd Tanous                 handleServiceEnablePatch(*serviceEnabled, asyncResp, serverT,
11146c51eab1SEd Tanous                                          dbusObjectPath);
11158a07d286SRatan Gupta             }
11168a07d286SRatan Gupta         }
11178a07d286SRatan Gupta         else
11188a07d286SRatan Gupta         {
11198a07d286SRatan Gupta             // if user has not given the service enabled value
11208a07d286SRatan Gupta             // then revert it to the same state as it was
11218a07d286SRatan Gupta             // before.
11228a07d286SRatan Gupta             handleServiceEnablePatch(confData.serviceEnabled, asyncResp,
112323a21a1cSEd Tanous                                      serverT, dbusObjectPath);
11248a07d286SRatan Gupta         }
112506785244SRatan Gupta 
112606785244SRatan Gupta         if (remoteRoleMapData)
112706785244SRatan Gupta         {
11286c51eab1SEd Tanous             handleRoleMapPatch(asyncResp, confData.groupRoleList, serverT,
11296c51eab1SEd Tanous                                *remoteRoleMapData);
113006785244SRatan Gupta         }
11318a07d286SRatan Gupta     });
11328a07d286SRatan Gupta }
1133d4b5443fSEd Tanous 
113458345856SAbhishek Patel inline void updateUserProperties(
113558345856SAbhishek Patel     std::shared_ptr<bmcweb::AsyncResp> asyncResp, const std::string& username,
1136618c14b4SEd Tanous     const std::optional<std::string>& password,
1137618c14b4SEd Tanous     const std::optional<bool>& enabled,
113858345856SAbhishek Patel     const std::optional<std::string>& roleId, const std::optional<bool>& locked,
113958345856SAbhishek Patel     std::optional<std::vector<std::string>> accountTypes, bool userSelf)
11401abe55efSEd Tanous {
1141b477fd44SP Dheeraj Srujan Kumar     sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
1142b477fd44SP Dheeraj Srujan Kumar     tempObjPath /= username;
1143b477fd44SP Dheeraj Srujan Kumar     std::string dbusObjectPath(tempObjPath);
11446c51eab1SEd Tanous 
11456c51eab1SEd Tanous     dbus::utility::checkDbusPathExists(
1146618c14b4SEd Tanous         dbusObjectPath, [dbusObjectPath, username, password, roleId, enabled,
114758345856SAbhishek Patel                          locked, accountTypes(std::move(accountTypes)),
114858345856SAbhishek Patel                          userSelf, asyncResp{std::move(asyncResp)}](int rc) {
1149e662eae8SEd Tanous         if (rc <= 0)
11506c51eab1SEd Tanous         {
1151d8a5d5d8SJiaqing Zhao             messages::resourceNotFound(asyncResp->res, "ManagerAccount",
11526c51eab1SEd Tanous                                        username);
11536c51eab1SEd Tanous             return;
11546c51eab1SEd Tanous         }
11556c51eab1SEd Tanous 
11566c51eab1SEd Tanous         if (password)
11576c51eab1SEd Tanous         {
11586c51eab1SEd Tanous             int retval = pamUpdatePassword(username, *password);
11596c51eab1SEd Tanous 
11606c51eab1SEd Tanous             if (retval == PAM_USER_UNKNOWN)
11616c51eab1SEd Tanous             {
1162d8a5d5d8SJiaqing Zhao                 messages::resourceNotFound(asyncResp->res, "ManagerAccount",
11636c51eab1SEd Tanous                                            username);
11646c51eab1SEd Tanous             }
11656c51eab1SEd Tanous             else if (retval == PAM_AUTHTOK_ERR)
11666c51eab1SEd Tanous             {
11676c51eab1SEd Tanous                 // If password is invalid
11689bd80831SJason M. Bills                 messages::propertyValueFormatError(asyncResp->res, nullptr,
11699bd80831SJason M. Bills                                                    "Password");
117062598e31SEd Tanous                 BMCWEB_LOG_ERROR("pamUpdatePassword Failed");
11716c51eab1SEd Tanous             }
11726c51eab1SEd Tanous             else if (retval != PAM_SUCCESS)
11736c51eab1SEd Tanous             {
11746c51eab1SEd Tanous                 messages::internalError(asyncResp->res);
11756c51eab1SEd Tanous                 return;
11766c51eab1SEd Tanous             }
1177e7b1b62bSEd Tanous             else
1178e7b1b62bSEd Tanous             {
1179e7b1b62bSEd Tanous                 messages::success(asyncResp->res);
1180e7b1b62bSEd Tanous             }
11816c51eab1SEd Tanous         }
11826c51eab1SEd Tanous 
11836c51eab1SEd Tanous         if (enabled)
11846c51eab1SEd Tanous         {
1185*d02aad39SEd Tanous             setDbusProperty(asyncResp, "xyz.openbmc_project.User.Manager",
1186*d02aad39SEd Tanous                             dbusObjectPath,
1187*d02aad39SEd Tanous                             "xyz.openbmc_project.User.Attributes",
1188*d02aad39SEd Tanous                             "UserEnabled", "Enabled", *enabled);
11896c51eab1SEd Tanous         }
11906c51eab1SEd Tanous 
11916c51eab1SEd Tanous         if (roleId)
11926c51eab1SEd Tanous         {
11936c51eab1SEd Tanous             std::string priv = getPrivilegeFromRoleId(*roleId);
11946c51eab1SEd Tanous             if (priv.empty())
11956c51eab1SEd Tanous             {
1196e2616cc5SEd Tanous                 messages::propertyValueNotInList(asyncResp->res, true,
1197e2616cc5SEd Tanous                                                  "Locked");
11986c51eab1SEd Tanous                 return;
11996c51eab1SEd Tanous             }
1200*d02aad39SEd Tanous             setDbusProperty(asyncResp, "xyz.openbmc_project.User.Manager",
1201*d02aad39SEd Tanous                             dbusObjectPath,
1202*d02aad39SEd Tanous                             "xyz.openbmc_project.User.Attributes",
1203*d02aad39SEd Tanous                             "UserPrivilege", "RoleId", priv);
12046c51eab1SEd Tanous         }
12056c51eab1SEd Tanous 
12066c51eab1SEd Tanous         if (locked)
12076c51eab1SEd Tanous         {
12086c51eab1SEd Tanous             // admin can unlock the account which is locked by
12096c51eab1SEd Tanous             // successive authentication failures but admin should
12106c51eab1SEd Tanous             // not be allowed to lock an account.
12116c51eab1SEd Tanous             if (*locked)
12126c51eab1SEd Tanous             {
12136c51eab1SEd Tanous                 messages::propertyValueNotInList(asyncResp->res, "true",
12146c51eab1SEd Tanous                                                  "Locked");
12156c51eab1SEd Tanous                 return;
12166c51eab1SEd Tanous             }
1217*d02aad39SEd Tanous             setDbusProperty(asyncResp, "xyz.openbmc_project.User.Manager",
1218*d02aad39SEd Tanous                             dbusObjectPath,
12199ae226faSGeorge Liu                             "xyz.openbmc_project.User.Attributes",
1220*d02aad39SEd Tanous                             "UserLockedForFailedAttempt", "Locked", *locked);
12216c51eab1SEd Tanous         }
122258345856SAbhishek Patel 
122358345856SAbhishek Patel         if (accountTypes)
122458345856SAbhishek Patel         {
122558345856SAbhishek Patel             patchAccountTypes(*accountTypes, asyncResp, dbusObjectPath,
122658345856SAbhishek Patel                               userSelf);
122758345856SAbhishek Patel         }
12286c51eab1SEd Tanous     });
12296c51eab1SEd Tanous }
12306c51eab1SEd Tanous 
12314c7d4d33SEd Tanous inline void handleAccountServiceHead(
12324c7d4d33SEd Tanous     App& app, const crow::Request& req,
12331ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
12346c51eab1SEd Tanous {
12353ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
123645ca1b86SEd Tanous     {
123745ca1b86SEd Tanous         return;
123845ca1b86SEd Tanous     }
12394c7d4d33SEd Tanous     asyncResp->res.addHeader(
12404c7d4d33SEd Tanous         boost::beast::http::field::link,
12414c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/AccountService/AccountService.json>; rel=describedby");
12424c7d4d33SEd Tanous }
12434c7d4d33SEd Tanous 
12444c7d4d33SEd Tanous inline void
12454c7d4d33SEd Tanous     handleAccountServiceGet(App& app, const crow::Request& req,
12464c7d4d33SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
12474c7d4d33SEd Tanous {
1248afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1249afd369c6SJiaqing Zhao     {
1250afd369c6SJiaqing Zhao         return;
1251afd369c6SJiaqing Zhao     }
12523e72c202SNinad Palsule 
12533e72c202SNinad Palsule     if (req.session == nullptr)
12543e72c202SNinad Palsule     {
12553e72c202SNinad Palsule         messages::internalError(asyncResp->res);
12563e72c202SNinad Palsule         return;
12573e72c202SNinad Palsule     }
12583e72c202SNinad Palsule 
1259afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1260afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1261afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/AccountService/AccountService.json>; rel=describedby");
1262afd369c6SJiaqing Zhao 
126352cc112dSEd Tanous     const persistent_data::AuthConfigMethods& authMethodsConfig =
12641ef4c342SEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
126578158631SZbigniew Kurzynski 
12661476687dSEd Tanous     nlohmann::json& json = asyncResp->res.jsonValue;
12671476687dSEd Tanous     json["@odata.id"] = "/redfish/v1/AccountService";
12681476687dSEd Tanous     json["@odata.type"] = "#AccountService."
12691476687dSEd Tanous                           "v1_10_0.AccountService";
12701476687dSEd Tanous     json["Id"] = "AccountService";
12711476687dSEd Tanous     json["Name"] = "Account Service";
12721476687dSEd Tanous     json["Description"] = "Account Service";
12731476687dSEd Tanous     json["ServiceEnabled"] = true;
12741476687dSEd Tanous     json["MaxPasswordLength"] = 20;
12751ef4c342SEd Tanous     json["Accounts"]["@odata.id"] = "/redfish/v1/AccountService/Accounts";
12761476687dSEd Tanous     json["Roles"]["@odata.id"] = "/redfish/v1/AccountService/Roles";
12771476687dSEd Tanous     json["Oem"]["OpenBMC"]["@odata.type"] =
12785b5574acSEd Tanous         "#OpenBMCAccountService.v1_0_0.AccountService";
12791476687dSEd Tanous     json["Oem"]["OpenBMC"]["@odata.id"] =
12801476687dSEd Tanous         "/redfish/v1/AccountService#/Oem/OpenBMC";
12811476687dSEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["BasicAuth"] =
12821476687dSEd Tanous         authMethodsConfig.basic;
12831476687dSEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["SessionToken"] =
12841476687dSEd Tanous         authMethodsConfig.sessionToken;
12851ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["XToken"] = authMethodsConfig.xtoken;
12861ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["Cookie"] = authMethodsConfig.cookie;
12871ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["TLS"] = authMethodsConfig.tls;
12881476687dSEd Tanous 
12891ef4c342SEd Tanous     // /redfish/v1/AccountService/LDAP/Certificates is something only
12901ef4c342SEd Tanous     // ConfigureManager can access then only display when the user has
12911ef4c342SEd Tanous     // permissions ConfigureManager
129272048780SAbhishek Patel     Privileges effectiveUserPrivileges =
12933e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
129472048780SAbhishek Patel 
129572048780SAbhishek Patel     if (isOperationAllowedWithPrivileges({{"ConfigureManager"}},
129672048780SAbhishek Patel                                          effectiveUserPrivileges))
129772048780SAbhishek Patel     {
12981ef4c342SEd Tanous         asyncResp->res.jsonValue["LDAP"]["Certificates"]["@odata.id"] =
12991476687dSEd Tanous             "/redfish/v1/AccountService/LDAP/Certificates";
130072048780SAbhishek Patel     }
1301d1bde9e5SKrzysztof Grobelny     sdbusplus::asio::getAllProperties(
1302d1bde9e5SKrzysztof Grobelny         *crow::connections::systemBus, "xyz.openbmc_project.User.Manager",
1303d1bde9e5SKrzysztof Grobelny         "/xyz/openbmc_project/user", "xyz.openbmc_project.User.AccountPolicy",
13045e7e2dc5SEd Tanous         [asyncResp](const boost::system::error_code& ec,
13051ef4c342SEd Tanous                     const dbus::utility::DBusPropertiesMap& propertiesList) {
13063d958bbcSAppaRao Puli         if (ec)
13073d958bbcSAppaRao Puli         {
13083d958bbcSAppaRao Puli             messages::internalError(asyncResp->res);
13093d958bbcSAppaRao Puli             return;
13103d958bbcSAppaRao Puli         }
1311d1bde9e5SKrzysztof Grobelny 
131262598e31SEd Tanous         BMCWEB_LOG_DEBUG("Got {}properties for AccountService",
131362598e31SEd Tanous                          propertiesList.size());
1314d1bde9e5SKrzysztof Grobelny 
1315d1bde9e5SKrzysztof Grobelny         const uint8_t* minPasswordLength = nullptr;
1316d1bde9e5SKrzysztof Grobelny         const uint32_t* accountUnlockTimeout = nullptr;
1317d1bde9e5SKrzysztof Grobelny         const uint16_t* maxLoginAttemptBeforeLockout = nullptr;
1318d1bde9e5SKrzysztof Grobelny 
1319d1bde9e5SKrzysztof Grobelny         const bool success = sdbusplus::unpackPropertiesNoThrow(
1320d1bde9e5SKrzysztof Grobelny             dbus_utils::UnpackErrorPrinter(), propertiesList,
1321d1bde9e5SKrzysztof Grobelny             "MinPasswordLength", minPasswordLength, "AccountUnlockTimeout",
1322d1bde9e5SKrzysztof Grobelny             accountUnlockTimeout, "MaxLoginAttemptBeforeLockout",
1323d1bde9e5SKrzysztof Grobelny             maxLoginAttemptBeforeLockout);
1324d1bde9e5SKrzysztof Grobelny 
1325d1bde9e5SKrzysztof Grobelny         if (!success)
13263d958bbcSAppaRao Puli         {
1327d1bde9e5SKrzysztof Grobelny             messages::internalError(asyncResp->res);
1328d1bde9e5SKrzysztof Grobelny             return;
13293d958bbcSAppaRao Puli         }
1330d1bde9e5SKrzysztof Grobelny 
1331d1bde9e5SKrzysztof Grobelny         if (minPasswordLength != nullptr)
13323d958bbcSAppaRao Puli         {
1333d1bde9e5SKrzysztof Grobelny             asyncResp->res.jsonValue["MinPasswordLength"] = *minPasswordLength;
13343d958bbcSAppaRao Puli         }
1335d1bde9e5SKrzysztof Grobelny 
1336d1bde9e5SKrzysztof Grobelny         if (accountUnlockTimeout != nullptr)
13373d958bbcSAppaRao Puli         {
1338d1bde9e5SKrzysztof Grobelny             asyncResp->res.jsonValue["AccountLockoutDuration"] =
1339d1bde9e5SKrzysztof Grobelny                 *accountUnlockTimeout;
1340d1bde9e5SKrzysztof Grobelny         }
1341d1bde9e5SKrzysztof Grobelny 
1342d1bde9e5SKrzysztof Grobelny         if (maxLoginAttemptBeforeLockout != nullptr)
13433d958bbcSAppaRao Puli         {
1344002d39b4SEd Tanous             asyncResp->res.jsonValue["AccountLockoutThreshold"] =
1345d1bde9e5SKrzysztof Grobelny                 *maxLoginAttemptBeforeLockout;
13463d958bbcSAppaRao Puli         }
1347d1bde9e5SKrzysztof Grobelny     });
13486973a582SRatan Gupta 
134902cad96eSEd Tanous     auto callback = [asyncResp](bool success, const LDAPConfigData& confData,
1350ab828d7cSRatan Gupta                                 const std::string& ldapType) {
1351cb13a392SEd Tanous         if (!success)
1352cb13a392SEd Tanous         {
1353cb13a392SEd Tanous             return;
1354cb13a392SEd Tanous         }
1355002d39b4SEd Tanous         parseLDAPConfigData(asyncResp->res.jsonValue, confData, ldapType);
1356ab828d7cSRatan Gupta     };
1357ab828d7cSRatan Gupta 
1358ab828d7cSRatan Gupta     getLDAPConfigData("LDAP", callback);
1359ab828d7cSRatan Gupta     getLDAPConfigData("ActiveDirectory", callback);
13601ef4c342SEd Tanous }
13616973a582SRatan Gupta 
13621ef4c342SEd Tanous inline void handleAccountServicePatch(
13631ef4c342SEd Tanous     App& app, const crow::Request& req,
13641ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
13651ef4c342SEd Tanous {
13663ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
136745ca1b86SEd Tanous     {
136845ca1b86SEd Tanous         return;
136945ca1b86SEd Tanous     }
1370f5ffd806SEd Tanous     std::optional<uint32_t> unlockTimeout;
1371f5ffd806SEd Tanous     std::optional<uint16_t> lockoutThreshold;
1372ef73ad0dSPaul Fertser     std::optional<uint8_t> minPasswordLength;
1373f5ffd806SEd Tanous     std::optional<uint16_t> maxPasswordLength;
1374f5ffd806SEd Tanous     std::optional<nlohmann::json> ldapObject;
1375f5ffd806SEd Tanous     std::optional<nlohmann::json> activeDirectoryObject;
1376f5ffd806SEd Tanous     std::optional<nlohmann::json> oemObject;
1377f5ffd806SEd Tanous 
137815ed6780SWilly Tu     if (!json_util::readJsonPatch(
13791ef4c342SEd Tanous             req, asyncResp->res, "AccountLockoutDuration", unlockTimeout,
13801ef4c342SEd Tanous             "AccountLockoutThreshold", lockoutThreshold, "MaxPasswordLength",
13811ef4c342SEd Tanous             maxPasswordLength, "MinPasswordLength", minPasswordLength, "LDAP",
13821ef4c342SEd Tanous             ldapObject, "ActiveDirectory", activeDirectoryObject, "Oem",
1383f5ffd806SEd Tanous             oemObject))
1384f5ffd806SEd Tanous     {
1385f5ffd806SEd Tanous         return;
1386f5ffd806SEd Tanous     }
1387f5ffd806SEd Tanous 
1388f5ffd806SEd Tanous     if (minPasswordLength)
1389f5ffd806SEd Tanous     {
1390*d02aad39SEd Tanous         setDbusProperty(
1391*d02aad39SEd Tanous             asyncResp, "xyz.openbmc_project.User.Manager",
1392*d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
13939ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy", "MinPasswordLength",
1394*d02aad39SEd Tanous             "MinPasswordLength", *minPasswordLength);
1395f5ffd806SEd Tanous     }
1396f5ffd806SEd Tanous 
1397f5ffd806SEd Tanous     if (maxPasswordLength)
1398f5ffd806SEd Tanous     {
13991ef4c342SEd Tanous         messages::propertyNotWritable(asyncResp->res, "MaxPasswordLength");
1400f5ffd806SEd Tanous     }
1401f5ffd806SEd Tanous 
1402f5ffd806SEd Tanous     if (ldapObject)
1403f5ffd806SEd Tanous     {
1404f5ffd806SEd Tanous         handleLDAPPatch(*ldapObject, asyncResp, "LDAP");
1405f5ffd806SEd Tanous     }
1406f5ffd806SEd Tanous 
1407f5ffd806SEd Tanous     if (std::optional<nlohmann::json> oemOpenBMCObject;
14081ef4c342SEd Tanous         oemObject && json_util::readJson(*oemObject, asyncResp->res, "OpenBMC",
1409f5ffd806SEd Tanous                                          oemOpenBMCObject))
1410f5ffd806SEd Tanous     {
1411f5ffd806SEd Tanous         if (std::optional<nlohmann::json> authMethodsObject;
1412f5ffd806SEd Tanous             oemOpenBMCObject &&
1413f5ffd806SEd Tanous             json_util::readJson(*oemOpenBMCObject, asyncResp->res,
1414f5ffd806SEd Tanous                                 "AuthMethods", authMethodsObject))
1415f5ffd806SEd Tanous         {
1416f5ffd806SEd Tanous             if (authMethodsObject)
1417f5ffd806SEd Tanous             {
14181ef4c342SEd Tanous                 handleAuthMethodsPatch(*authMethodsObject, asyncResp);
1419f5ffd806SEd Tanous             }
1420f5ffd806SEd Tanous         }
1421f5ffd806SEd Tanous     }
1422f5ffd806SEd Tanous 
1423f5ffd806SEd Tanous     if (activeDirectoryObject)
1424f5ffd806SEd Tanous     {
14251ef4c342SEd Tanous         handleLDAPPatch(*activeDirectoryObject, asyncResp, "ActiveDirectory");
1426f5ffd806SEd Tanous     }
1427f5ffd806SEd Tanous 
1428f5ffd806SEd Tanous     if (unlockTimeout)
1429f5ffd806SEd Tanous     {
1430*d02aad39SEd Tanous         setDbusProperty(
1431*d02aad39SEd Tanous             asyncResp, "xyz.openbmc_project.User.Manager",
1432*d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
14339ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy", "AccountUnlockTimeout",
1434*d02aad39SEd Tanous             "AccountLockoutDuration", *unlockTimeout);
1435f5ffd806SEd Tanous     }
1436f5ffd806SEd Tanous     if (lockoutThreshold)
1437f5ffd806SEd Tanous     {
1438*d02aad39SEd Tanous         setDbusProperty(
1439*d02aad39SEd Tanous             asyncResp, "xyz.openbmc_project.User.Manager",
1440*d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
14419ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy",
1442*d02aad39SEd Tanous             "MaxLoginAttemptBeforeLockout", "AccountLockoutThreshold",
1443*d02aad39SEd Tanous             *lockoutThreshold);
1444f5ffd806SEd Tanous     }
14451ef4c342SEd Tanous }
1446f5ffd806SEd Tanous 
14474c7d4d33SEd Tanous inline void handleAccountCollectionHead(
14481ef4c342SEd Tanous     App& app, const crow::Request& req,
14491ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
14501ef4c342SEd Tanous {
14513ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
145245ca1b86SEd Tanous     {
145345ca1b86SEd Tanous         return;
145445ca1b86SEd Tanous     }
14554c7d4d33SEd Tanous     asyncResp->res.addHeader(
14564c7d4d33SEd Tanous         boost::beast::http::field::link,
14574c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/ManagerAccountCollection.json>; rel=describedby");
14584c7d4d33SEd Tanous }
14594c7d4d33SEd Tanous 
14604c7d4d33SEd Tanous inline void handleAccountCollectionGet(
14614c7d4d33SEd Tanous     App& app, const crow::Request& req,
14624c7d4d33SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
14634c7d4d33SEd Tanous {
1464afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1465afd369c6SJiaqing Zhao     {
1466afd369c6SJiaqing Zhao         return;
1467afd369c6SJiaqing Zhao     }
14683e72c202SNinad Palsule 
14693e72c202SNinad Palsule     if (req.session == nullptr)
14703e72c202SNinad Palsule     {
14713e72c202SNinad Palsule         messages::internalError(asyncResp->res);
14723e72c202SNinad Palsule         return;
14733e72c202SNinad Palsule     }
14743e72c202SNinad Palsule 
1475afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1476afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1477afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/ManagerAccountCollection.json>; rel=describedby");
14781476687dSEd Tanous 
14791476687dSEd Tanous     asyncResp->res.jsonValue["@odata.id"] =
14801476687dSEd Tanous         "/redfish/v1/AccountService/Accounts";
14811ef4c342SEd Tanous     asyncResp->res.jsonValue["@odata.type"] = "#ManagerAccountCollection."
14821476687dSEd Tanous                                               "ManagerAccountCollection";
14831476687dSEd Tanous     asyncResp->res.jsonValue["Name"] = "Accounts Collection";
14841476687dSEd Tanous     asyncResp->res.jsonValue["Description"] = "BMC User Accounts";
14850f74e643SEd Tanous 
14866c51eab1SEd Tanous     Privileges effectiveUserPrivileges =
14873e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
14886c51eab1SEd Tanous 
1489f5e29f33SJunLin Chen     std::string thisUser;
1490f5e29f33SJunLin Chen     if (req.session)
1491f5e29f33SJunLin Chen     {
1492f5e29f33SJunLin Chen         thisUser = req.session->username;
1493f5e29f33SJunLin Chen     }
14945eb468daSGeorge Liu     sdbusplus::message::object_path path("/xyz/openbmc_project/user");
14955eb468daSGeorge Liu     dbus::utility::getManagedObjects(
14965eb468daSGeorge Liu         "xyz.openbmc_project.User.Manager", path,
1497cef1ddfbSEd Tanous         [asyncResp, thisUser, effectiveUserPrivileges](
14985e7e2dc5SEd Tanous             const boost::system::error_code& ec,
1499711ac7a9SEd Tanous             const dbus::utility::ManagedObjectType& users) {
1500b9b2e0b2SEd Tanous         if (ec)
1501b9b2e0b2SEd Tanous         {
1502f12894f8SJason M. Bills             messages::internalError(asyncResp->res);
1503b9b2e0b2SEd Tanous             return;
1504b9b2e0b2SEd Tanous         }
1505b9b2e0b2SEd Tanous 
1506cef1ddfbSEd Tanous         bool userCanSeeAllAccounts =
1507002d39b4SEd Tanous             effectiveUserPrivileges.isSupersetOf({"ConfigureUsers"});
1508cef1ddfbSEd Tanous 
1509cef1ddfbSEd Tanous         bool userCanSeeSelf =
1510002d39b4SEd Tanous             effectiveUserPrivileges.isSupersetOf({"ConfigureSelf"});
1511cef1ddfbSEd Tanous 
1512002d39b4SEd Tanous         nlohmann::json& memberArray = asyncResp->res.jsonValue["Members"];
1513b9b2e0b2SEd Tanous         memberArray = nlohmann::json::array();
1514b9b2e0b2SEd Tanous 
15159eb808c1SEd Tanous         for (const auto& userpath : users)
1516b9b2e0b2SEd Tanous         {
15172dfd18efSEd Tanous             std::string user = userpath.first.filename();
15182dfd18efSEd Tanous             if (user.empty())
1519b9b2e0b2SEd Tanous             {
15202dfd18efSEd Tanous                 messages::internalError(asyncResp->res);
152162598e31SEd Tanous                 BMCWEB_LOG_ERROR("Invalid firmware ID");
15222dfd18efSEd Tanous 
15232dfd18efSEd Tanous                 return;
1524b9b2e0b2SEd Tanous             }
1525f365910cSGunnar Mills 
1526f365910cSGunnar Mills             // As clarified by Redfish here:
1527f365910cSGunnar Mills             // https://redfishforum.com/thread/281/manageraccountcollection-change-allows-account-enumeration
15286c51eab1SEd Tanous             // Users without ConfigureUsers, only see their own
15296c51eab1SEd Tanous             // account. Users with ConfigureUsers, see all
15306c51eab1SEd Tanous             // accounts.
15311ef4c342SEd Tanous             if (userCanSeeAllAccounts || (thisUser == user && userCanSeeSelf))
1532f365910cSGunnar Mills             {
15331476687dSEd Tanous                 nlohmann::json::object_t member;
15343b32780dSEd Tanous                 member["@odata.id"] = boost::urls::format(
15353b32780dSEd Tanous                     "/redfish/v1/AccountService/Accounts/{}", user);
1536b2ba3072SPatrick Williams                 memberArray.emplace_back(std::move(member));
1537b9b2e0b2SEd Tanous             }
1538f365910cSGunnar Mills         }
15391ef4c342SEd Tanous         asyncResp->res.jsonValue["Members@odata.count"] = memberArray.size();
15405eb468daSGeorge Liu     });
15411ef4c342SEd Tanous }
15426c51eab1SEd Tanous 
154397e90da3SNinad Palsule inline void processAfterCreateUser(
154497e90da3SNinad Palsule     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
154597e90da3SNinad Palsule     const std::string& username, const std::string& password,
154697e90da3SNinad Palsule     const boost::system::error_code& ec, sdbusplus::message_t& m)
154797e90da3SNinad Palsule {
154897e90da3SNinad Palsule     if (ec)
154997e90da3SNinad Palsule     {
155097e90da3SNinad Palsule         userErrorMessageHandler(m.get_error(), asyncResp, username, "");
155197e90da3SNinad Palsule         return;
155297e90da3SNinad Palsule     }
155397e90da3SNinad Palsule 
155497e90da3SNinad Palsule     if (pamUpdatePassword(username, password) != PAM_SUCCESS)
155597e90da3SNinad Palsule     {
155697e90da3SNinad Palsule         // At this point we have a user that's been
155797e90da3SNinad Palsule         // created, but the password set
155897e90da3SNinad Palsule         // failed.Something is wrong, so delete the user
155997e90da3SNinad Palsule         // that we've already created
156097e90da3SNinad Palsule         sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
156197e90da3SNinad Palsule         tempObjPath /= username;
156297e90da3SNinad Palsule         const std::string userPath(tempObjPath);
156397e90da3SNinad Palsule 
156497e90da3SNinad Palsule         crow::connections::systemBus->async_method_call(
156597e90da3SNinad Palsule             [asyncResp, password](const boost::system::error_code& ec3) {
156697e90da3SNinad Palsule             if (ec3)
156797e90da3SNinad Palsule             {
156897e90da3SNinad Palsule                 messages::internalError(asyncResp->res);
156997e90da3SNinad Palsule                 return;
157097e90da3SNinad Palsule             }
157197e90da3SNinad Palsule 
157297e90da3SNinad Palsule             // If password is invalid
15739bd80831SJason M. Bills             messages::propertyValueFormatError(asyncResp->res, nullptr,
157497e90da3SNinad Palsule                                                "Password");
157597e90da3SNinad Palsule         },
157697e90da3SNinad Palsule             "xyz.openbmc_project.User.Manager", userPath,
157797e90da3SNinad Palsule             "xyz.openbmc_project.Object.Delete", "Delete");
157897e90da3SNinad Palsule 
157962598e31SEd Tanous         BMCWEB_LOG_ERROR("pamUpdatePassword Failed");
158097e90da3SNinad Palsule         return;
158197e90da3SNinad Palsule     }
158297e90da3SNinad Palsule 
158397e90da3SNinad Palsule     messages::created(asyncResp->res);
158497e90da3SNinad Palsule     asyncResp->res.addHeader("Location",
158597e90da3SNinad Palsule                              "/redfish/v1/AccountService/Accounts/" + username);
158697e90da3SNinad Palsule }
158797e90da3SNinad Palsule 
158897e90da3SNinad Palsule inline void processAfterGetAllGroups(
158997e90da3SNinad Palsule     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
159097e90da3SNinad Palsule     const std::string& username, const std::string& password,
1591e01d0c36SEd Tanous     const std::string& roleId, bool enabled,
15929ba73934SNinad Palsule     std::optional<std::vector<std::string>> accountTypes,
159397e90da3SNinad Palsule     const std::vector<std::string>& allGroupsList)
159497e90da3SNinad Palsule {
15953e72c202SNinad Palsule     std::vector<std::string> userGroups;
15969ba73934SNinad Palsule     std::vector<std::string> accountTypeUserGroups;
15979ba73934SNinad Palsule 
15989ba73934SNinad Palsule     // If user specified account types then convert them to unix user groups
15999ba73934SNinad Palsule     if (accountTypes)
16009ba73934SNinad Palsule     {
16019ba73934SNinad Palsule         if (!getUserGroupFromAccountType(asyncResp->res, *accountTypes,
16029ba73934SNinad Palsule                                          accountTypeUserGroups))
16039ba73934SNinad Palsule         {
16049ba73934SNinad Palsule             // Problem in mapping Account Types to User Groups, Error already
16059ba73934SNinad Palsule             // logged.
16069ba73934SNinad Palsule             return;
16079ba73934SNinad Palsule         }
16089ba73934SNinad Palsule     }
16099ba73934SNinad Palsule 
16103e72c202SNinad Palsule     for (const auto& grp : allGroupsList)
16113e72c202SNinad Palsule     {
16129ba73934SNinad Palsule         // If user specified the account type then only accept groups which are
16139ba73934SNinad Palsule         // in the account types group list.
16149ba73934SNinad Palsule         if (!accountTypeUserGroups.empty())
16159ba73934SNinad Palsule         {
16169ba73934SNinad Palsule             bool found = false;
16179ba73934SNinad Palsule             for (const auto& grp1 : accountTypeUserGroups)
16189ba73934SNinad Palsule             {
16199ba73934SNinad Palsule                 if (grp == grp1)
16209ba73934SNinad Palsule                 {
16219ba73934SNinad Palsule                     found = true;
16229ba73934SNinad Palsule                     break;
16239ba73934SNinad Palsule                 }
16249ba73934SNinad Palsule             }
16259ba73934SNinad Palsule             if (!found)
16269ba73934SNinad Palsule             {
16279ba73934SNinad Palsule                 continue;
16289ba73934SNinad Palsule             }
16299ba73934SNinad Palsule         }
16309ba73934SNinad Palsule 
16313e72c202SNinad Palsule         // Console access is provided to the user who is a member of
16323e72c202SNinad Palsule         // hostconsole group and has a administrator role. So, set
16333e72c202SNinad Palsule         // hostconsole group only for the administrator.
16349ba73934SNinad Palsule         if ((grp == "hostconsole") && (roleId != "priv-admin"))
16353e72c202SNinad Palsule         {
16369ba73934SNinad Palsule             if (!accountTypeUserGroups.empty())
16379ba73934SNinad Palsule             {
163862598e31SEd Tanous                 BMCWEB_LOG_ERROR(
163962598e31SEd Tanous                     "Only administrator can get HostConsole access");
16409ba73934SNinad Palsule                 asyncResp->res.result(boost::beast::http::status::bad_request);
16419ba73934SNinad Palsule                 return;
16429ba73934SNinad Palsule             }
16439ba73934SNinad Palsule             continue;
16449ba73934SNinad Palsule         }
16453e72c202SNinad Palsule         userGroups.emplace_back(grp);
16463e72c202SNinad Palsule     }
16479ba73934SNinad Palsule 
16489ba73934SNinad Palsule     // Make sure user specified groups are valid. This is internal error because
16499ba73934SNinad Palsule     // it some inconsistencies between user manager and bmcweb.
16509ba73934SNinad Palsule     if (!accountTypeUserGroups.empty() &&
16519ba73934SNinad Palsule         accountTypeUserGroups.size() != userGroups.size())
16529ba73934SNinad Palsule     {
16539ba73934SNinad Palsule         messages::internalError(asyncResp->res);
16549ba73934SNinad Palsule         return;
16553e72c202SNinad Palsule     }
165697e90da3SNinad Palsule     crow::connections::systemBus->async_method_call(
165797e90da3SNinad Palsule         [asyncResp, username, password](const boost::system::error_code& ec2,
165897e90da3SNinad Palsule                                         sdbusplus::message_t& m) {
165997e90da3SNinad Palsule         processAfterCreateUser(asyncResp, username, password, ec2, m);
166097e90da3SNinad Palsule     },
166197e90da3SNinad Palsule         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
16623e72c202SNinad Palsule         "xyz.openbmc_project.User.Manager", "CreateUser", username, userGroups,
1663e01d0c36SEd Tanous         roleId, enabled);
166497e90da3SNinad Palsule }
166597e90da3SNinad Palsule 
16661ef4c342SEd Tanous inline void handleAccountCollectionPost(
16671ef4c342SEd Tanous     App& app, const crow::Request& req,
16681ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
16691ef4c342SEd Tanous {
16703ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
167145ca1b86SEd Tanous     {
167245ca1b86SEd Tanous         return;
167345ca1b86SEd Tanous     }
16749712f8acSEd Tanous     std::string username;
16759712f8acSEd Tanous     std::string password;
1676e01d0c36SEd Tanous     std::optional<std::string> roleIdJson;
1677e01d0c36SEd Tanous     std::optional<bool> enabledJson;
16789ba73934SNinad Palsule     std::optional<std::vector<std::string>> accountTypes;
1679e01d0c36SEd Tanous     if (!json_util::readJsonPatch(req, asyncResp->res, "UserName", username,
1680e01d0c36SEd Tanous                                   "Password", password, "RoleId", roleIdJson,
1681e01d0c36SEd Tanous                                   "Enabled", enabledJson, "AccountTypes",
1682e01d0c36SEd Tanous                                   accountTypes))
168304ae99ecSEd Tanous     {
168404ae99ecSEd Tanous         return;
168504ae99ecSEd Tanous     }
168604ae99ecSEd Tanous 
1687e01d0c36SEd Tanous     std::string roleId = roleIdJson.value_or("User");
1688e01d0c36SEd Tanous     std::string priv = getPrivilegeFromRoleId(roleId);
168984e12cb7SAppaRao Puli     if (priv.empty())
169004ae99ecSEd Tanous     {
1691e01d0c36SEd Tanous         messages::propertyValueNotInList(asyncResp->res, roleId, "RoleId");
169204ae99ecSEd Tanous         return;
169304ae99ecSEd Tanous     }
16949712f8acSEd Tanous     roleId = priv;
169504ae99ecSEd Tanous 
1696e01d0c36SEd Tanous     bool enabled = enabledJson.value_or(true);
1697e01d0c36SEd Tanous 
1698599c71d8SAyushi Smriti     // Reading AllGroups property
16991e1e598dSJonathan Doman     sdbusplus::asio::getProperty<std::vector<std::string>>(
17001ef4c342SEd Tanous         *crow::connections::systemBus, "xyz.openbmc_project.User.Manager",
17011ef4c342SEd Tanous         "/xyz/openbmc_project/user", "xyz.openbmc_project.User.Manager",
17021ef4c342SEd Tanous         "AllGroups",
17039ba73934SNinad Palsule         [asyncResp, username, password{std::move(password)}, roleId, enabled,
17049ba73934SNinad Palsule          accountTypes](const boost::system::error_code& ec,
17051e1e598dSJonathan Doman                        const std::vector<std::string>& allGroupsList) {
1706599c71d8SAyushi Smriti         if (ec)
1707599c71d8SAyushi Smriti         {
170862598e31SEd Tanous             BMCWEB_LOG_DEBUG("ERROR with async_method_call");
1709599c71d8SAyushi Smriti             messages::internalError(asyncResp->res);
1710599c71d8SAyushi Smriti             return;
1711599c71d8SAyushi Smriti         }
1712599c71d8SAyushi Smriti 
17131e1e598dSJonathan Doman         if (allGroupsList.empty())
1714599c71d8SAyushi Smriti         {
1715599c71d8SAyushi Smriti             messages::internalError(asyncResp->res);
1716599c71d8SAyushi Smriti             return;
1717599c71d8SAyushi Smriti         }
1718599c71d8SAyushi Smriti 
171997e90da3SNinad Palsule         processAfterGetAllGroups(asyncResp, username, password, roleId, enabled,
17209ba73934SNinad Palsule                                  accountTypes, allGroupsList);
17211e1e598dSJonathan Doman     });
17221ef4c342SEd Tanous }
1723b9b2e0b2SEd Tanous 
17241ef4c342SEd Tanous inline void
17254c7d4d33SEd Tanous     handleAccountHead(App& app, const crow::Request& req,
17266c51eab1SEd Tanous                       const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
17274c7d4d33SEd Tanous                       const std::string& /*accountName*/)
17281ef4c342SEd Tanous {
17293ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
173045ca1b86SEd Tanous     {
173145ca1b86SEd Tanous         return;
173245ca1b86SEd Tanous     }
17334c7d4d33SEd Tanous     asyncResp->res.addHeader(
17344c7d4d33SEd Tanous         boost::beast::http::field::link,
17354c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/ManagerAccount/ManagerAccount.json>; rel=describedby");
17364c7d4d33SEd Tanous }
1737afd369c6SJiaqing Zhao 
17384c7d4d33SEd Tanous inline void
17394c7d4d33SEd Tanous     handleAccountGet(App& app, const crow::Request& req,
17404c7d4d33SEd Tanous                      const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
17414c7d4d33SEd Tanous                      const std::string& accountName)
17424c7d4d33SEd Tanous {
1743afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1744afd369c6SJiaqing Zhao     {
1745afd369c6SJiaqing Zhao         return;
1746afd369c6SJiaqing Zhao     }
1747afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1748afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1749afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/ManagerAccount/ManagerAccount.json>; rel=describedby");
1750afd369c6SJiaqing Zhao 
17511ef4c342SEd Tanous #ifdef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
1752031514fbSJunLin Chen     // If authentication is disabled, there are no user accounts
1753d8a5d5d8SJiaqing Zhao     messages::resourceNotFound(asyncResp->res, "ManagerAccount", accountName);
1754031514fbSJunLin Chen     return;
17551ef4c342SEd Tanous #endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
1756afd369c6SJiaqing Zhao 
1757031514fbSJunLin Chen     if (req.session == nullptr)
1758031514fbSJunLin Chen     {
1759031514fbSJunLin Chen         messages::internalError(asyncResp->res);
1760031514fbSJunLin Chen         return;
1761031514fbSJunLin Chen     }
17626c51eab1SEd Tanous     if (req.session->username != accountName)
1763b9b2e0b2SEd Tanous     {
17646c51eab1SEd Tanous         // At this point we've determined that the user is trying to
17651ef4c342SEd Tanous         // modify a user that isn't them.  We need to verify that they
17661ef4c342SEd Tanous         // have permissions to modify other users, so re-run the auth
17671ef4c342SEd Tanous         // check with the same permissions, minus ConfigureSelf.
17686c51eab1SEd Tanous         Privileges effectiveUserPrivileges =
17693e72c202SNinad Palsule             redfish::getUserPrivileges(*req.session);
17701ef4c342SEd Tanous         Privileges requiredPermissionsToChangeNonSelf = {"ConfigureUsers",
17711ef4c342SEd Tanous                                                          "ConfigureManager"};
17726c51eab1SEd Tanous         if (!effectiveUserPrivileges.isSupersetOf(
17736c51eab1SEd Tanous                 requiredPermissionsToChangeNonSelf))
1774900f9497SJoseph Reynolds         {
177562598e31SEd Tanous             BMCWEB_LOG_DEBUG("GET Account denied access");
1776900f9497SJoseph Reynolds             messages::insufficientPrivilege(asyncResp->res);
1777900f9497SJoseph Reynolds             return;
1778900f9497SJoseph Reynolds         }
1779900f9497SJoseph Reynolds     }
1780900f9497SJoseph Reynolds 
17815eb468daSGeorge Liu     sdbusplus::message::object_path path("/xyz/openbmc_project/user");
17825eb468daSGeorge Liu     dbus::utility::getManagedObjects(
17835eb468daSGeorge Liu         "xyz.openbmc_project.User.Manager", path,
17841ef4c342SEd Tanous         [asyncResp,
17855e7e2dc5SEd Tanous          accountName](const boost::system::error_code& ec,
1786711ac7a9SEd Tanous                       const dbus::utility::ManagedObjectType& users) {
1787b9b2e0b2SEd Tanous         if (ec)
1788b9b2e0b2SEd Tanous         {
1789f12894f8SJason M. Bills             messages::internalError(asyncResp->res);
1790b9b2e0b2SEd Tanous             return;
1791b9b2e0b2SEd Tanous         }
17923544d2a7SEd Tanous         const auto userIt = std::ranges::find_if(
179380f79a40SMichael Shen             users,
179480f79a40SMichael Shen             [accountName](
1795b477fd44SP Dheeraj Srujan Kumar                 const std::pair<sdbusplus::message::object_path,
179680f79a40SMichael Shen                                 dbus::utility::DBusInterfacesMap>& user) {
179755f79e6fSEd Tanous             return accountName == user.first.filename();
1798b477fd44SP Dheeraj Srujan Kumar         });
1799b9b2e0b2SEd Tanous 
180084e12cb7SAppaRao Puli         if (userIt == users.end())
1801b9b2e0b2SEd Tanous         {
1802002d39b4SEd Tanous             messages::resourceNotFound(asyncResp->res, "ManagerAccount",
1803002d39b4SEd Tanous                                        accountName);
180484e12cb7SAppaRao Puli             return;
180584e12cb7SAppaRao Puli         }
18064e68c45bSAyushi Smriti 
18071476687dSEd Tanous         asyncResp->res.jsonValue["@odata.type"] =
180858345856SAbhishek Patel             "#ManagerAccount.v1_7_0.ManagerAccount";
18091476687dSEd Tanous         asyncResp->res.jsonValue["Name"] = "User Account";
18101476687dSEd Tanous         asyncResp->res.jsonValue["Description"] = "User Account";
18111476687dSEd Tanous         asyncResp->res.jsonValue["Password"] = nullptr;
181258345856SAbhishek Patel         asyncResp->res.jsonValue["StrictAccountTypes"] = true;
18134e68c45bSAyushi Smriti 
181484e12cb7SAppaRao Puli         for (const auto& interface : userIt->second)
181565b0dc32SEd Tanous         {
1816002d39b4SEd Tanous             if (interface.first == "xyz.openbmc_project.User.Attributes")
181765b0dc32SEd Tanous             {
181865b0dc32SEd Tanous                 for (const auto& property : interface.second)
181965b0dc32SEd Tanous                 {
182065b0dc32SEd Tanous                     if (property.first == "UserEnabled")
182165b0dc32SEd Tanous                     {
182265b0dc32SEd Tanous                         const bool* userEnabled =
1823abf2add6SEd Tanous                             std::get_if<bool>(&property.second);
182465b0dc32SEd Tanous                         if (userEnabled == nullptr)
182565b0dc32SEd Tanous                         {
182662598e31SEd Tanous                             BMCWEB_LOG_ERROR("UserEnabled wasn't a bool");
182784e12cb7SAppaRao Puli                             messages::internalError(asyncResp->res);
182884e12cb7SAppaRao Puli                             return;
182965b0dc32SEd Tanous                         }
1830002d39b4SEd Tanous                         asyncResp->res.jsonValue["Enabled"] = *userEnabled;
183165b0dc32SEd Tanous                     }
1832002d39b4SEd Tanous                     else if (property.first == "UserLockedForFailedAttempt")
183365b0dc32SEd Tanous                     {
183465b0dc32SEd Tanous                         const bool* userLocked =
1835abf2add6SEd Tanous                             std::get_if<bool>(&property.second);
183665b0dc32SEd Tanous                         if (userLocked == nullptr)
183765b0dc32SEd Tanous                         {
183862598e31SEd Tanous                             BMCWEB_LOG_ERROR("UserLockedForF"
183984e12cb7SAppaRao Puli                                              "ailedAttempt "
184062598e31SEd Tanous                                              "wasn't a bool");
184184e12cb7SAppaRao Puli                             messages::internalError(asyncResp->res);
184284e12cb7SAppaRao Puli                             return;
184365b0dc32SEd Tanous                         }
1844002d39b4SEd Tanous                         asyncResp->res.jsonValue["Locked"] = *userLocked;
1845002d39b4SEd Tanous                         asyncResp->res
1846002d39b4SEd Tanous                             .jsonValue["Locked@Redfish.AllowableValues"] = {
18473bf4e632SJoseph Reynolds                             "false"}; // can only unlock accounts
184865b0dc32SEd Tanous                     }
184984e12cb7SAppaRao Puli                     else if (property.first == "UserPrivilege")
185084e12cb7SAppaRao Puli                     {
185154fc587aSNagaraju Goruganti                         const std::string* userPrivPtr =
1852002d39b4SEd Tanous                             std::get_if<std::string>(&property.second);
185354fc587aSNagaraju Goruganti                         if (userPrivPtr == nullptr)
185484e12cb7SAppaRao Puli                         {
185562598e31SEd Tanous                             BMCWEB_LOG_ERROR("UserPrivilege wasn't a "
185662598e31SEd Tanous                                              "string");
185784e12cb7SAppaRao Puli                             messages::internalError(asyncResp->res);
185884e12cb7SAppaRao Puli                             return;
185984e12cb7SAppaRao Puli                         }
18601ef4c342SEd Tanous                         std::string role = getRoleIdFromPrivilege(*userPrivPtr);
186154fc587aSNagaraju Goruganti                         if (role.empty())
186284e12cb7SAppaRao Puli                         {
186362598e31SEd Tanous                             BMCWEB_LOG_ERROR("Invalid user role");
186484e12cb7SAppaRao Puli                             messages::internalError(asyncResp->res);
186584e12cb7SAppaRao Puli                             return;
186684e12cb7SAppaRao Puli                         }
186754fc587aSNagaraju Goruganti                         asyncResp->res.jsonValue["RoleId"] = role;
186884e12cb7SAppaRao Puli 
18691476687dSEd Tanous                         nlohmann::json& roleEntry =
1870002d39b4SEd Tanous                             asyncResp->res.jsonValue["Links"]["Role"];
18713b32780dSEd Tanous                         roleEntry["@odata.id"] = boost::urls::format(
18723b32780dSEd Tanous                             "/redfish/v1/AccountService/Roles/{}", role);
187384e12cb7SAppaRao Puli                     }
1874002d39b4SEd Tanous                     else if (property.first == "UserPasswordExpired")
18753bf4e632SJoseph Reynolds                     {
18763bf4e632SJoseph Reynolds                         const bool* userPasswordExpired =
18773bf4e632SJoseph Reynolds                             std::get_if<bool>(&property.second);
18783bf4e632SJoseph Reynolds                         if (userPasswordExpired == nullptr)
18793bf4e632SJoseph Reynolds                         {
188062598e31SEd Tanous                             BMCWEB_LOG_ERROR(
188162598e31SEd Tanous                                 "UserPasswordExpired wasn't a bool");
18823bf4e632SJoseph Reynolds                             messages::internalError(asyncResp->res);
18833bf4e632SJoseph Reynolds                             return;
18843bf4e632SJoseph Reynolds                         }
1885002d39b4SEd Tanous                         asyncResp->res.jsonValue["PasswordChangeRequired"] =
18863bf4e632SJoseph Reynolds                             *userPasswordExpired;
18873bf4e632SJoseph Reynolds                     }
1888c7229815SAbhishek Patel                     else if (property.first == "UserGroups")
1889c7229815SAbhishek Patel                     {
1890c7229815SAbhishek Patel                         const std::vector<std::string>* userGroups =
1891c7229815SAbhishek Patel                             std::get_if<std::vector<std::string>>(
1892c7229815SAbhishek Patel                                 &property.second);
1893c7229815SAbhishek Patel                         if (userGroups == nullptr)
1894c7229815SAbhishek Patel                         {
189562598e31SEd Tanous                             BMCWEB_LOG_ERROR(
189662598e31SEd Tanous                                 "userGroups wasn't a string vector");
1897c7229815SAbhishek Patel                             messages::internalError(asyncResp->res);
1898c7229815SAbhishek Patel                             return;
1899c7229815SAbhishek Patel                         }
1900c7229815SAbhishek Patel                         if (!translateUserGroup(*userGroups, asyncResp->res))
1901c7229815SAbhishek Patel                         {
190262598e31SEd Tanous                             BMCWEB_LOG_ERROR("userGroups mapping failed");
1903c7229815SAbhishek Patel                             messages::internalError(asyncResp->res);
1904c7229815SAbhishek Patel                             return;
1905c7229815SAbhishek Patel                         }
1906c7229815SAbhishek Patel                     }
190765b0dc32SEd Tanous                 }
190865b0dc32SEd Tanous             }
190965b0dc32SEd Tanous         }
191065b0dc32SEd Tanous 
19113b32780dSEd Tanous         asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
19123b32780dSEd Tanous             "/redfish/v1/AccountService/Accounts/{}", accountName);
1913b9b2e0b2SEd Tanous         asyncResp->res.jsonValue["Id"] = accountName;
1914b9b2e0b2SEd Tanous         asyncResp->res.jsonValue["UserName"] = accountName;
19155eb468daSGeorge Liu     });
19161ef4c342SEd Tanous }
1917a840879dSEd Tanous 
19181ef4c342SEd Tanous inline void
191920fc307fSGunnar Mills     handleAccountDelete(App& app, const crow::Request& req,
19206c51eab1SEd Tanous                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
19211ef4c342SEd Tanous                         const std::string& username)
19221ef4c342SEd Tanous {
19233ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
192445ca1b86SEd Tanous     {
192545ca1b86SEd Tanous         return;
192645ca1b86SEd Tanous     }
19271ef4c342SEd Tanous 
19281ef4c342SEd Tanous #ifdef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
1929031514fbSJunLin Chen     // If authentication is disabled, there are no user accounts
1930d8a5d5d8SJiaqing Zhao     messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
1931031514fbSJunLin Chen     return;
1932031514fbSJunLin Chen 
19331ef4c342SEd Tanous #endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
19341ef4c342SEd Tanous     sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
19351ef4c342SEd Tanous     tempObjPath /= username;
19361ef4c342SEd Tanous     const std::string userPath(tempObjPath);
19371ef4c342SEd Tanous 
19381ef4c342SEd Tanous     crow::connections::systemBus->async_method_call(
19395e7e2dc5SEd Tanous         [asyncResp, username](const boost::system::error_code& ec) {
19401ef4c342SEd Tanous         if (ec)
19411ef4c342SEd Tanous         {
1942d8a5d5d8SJiaqing Zhao             messages::resourceNotFound(asyncResp->res, "ManagerAccount",
19431ef4c342SEd Tanous                                        username);
19441ef4c342SEd Tanous             return;
19451ef4c342SEd Tanous         }
19461ef4c342SEd Tanous 
19471ef4c342SEd Tanous         messages::accountRemoved(asyncResp->res);
19481ef4c342SEd Tanous     },
19491ef4c342SEd Tanous         "xyz.openbmc_project.User.Manager", userPath,
19501ef4c342SEd Tanous         "xyz.openbmc_project.Object.Delete", "Delete");
19511ef4c342SEd Tanous }
19521ef4c342SEd Tanous 
19531ef4c342SEd Tanous inline void
19541ef4c342SEd Tanous     handleAccountPatch(App& app, const crow::Request& req,
19551ef4c342SEd Tanous                        const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
19561ef4c342SEd Tanous                        const std::string& username)
19571ef4c342SEd Tanous {
19581ef4c342SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
19591ef4c342SEd Tanous     {
19601ef4c342SEd Tanous         return;
19611ef4c342SEd Tanous     }
19621ef4c342SEd Tanous #ifdef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
19631ef4c342SEd Tanous     // If authentication is disabled, there are no user accounts
1964d8a5d5d8SJiaqing Zhao     messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
19651ef4c342SEd Tanous     return;
19661ef4c342SEd Tanous 
19671ef4c342SEd Tanous #endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
1968a24526dcSEd Tanous     std::optional<std::string> newUserName;
1969a24526dcSEd Tanous     std::optional<std::string> password;
1970a24526dcSEd Tanous     std::optional<bool> enabled;
1971a24526dcSEd Tanous     std::optional<std::string> roleId;
197224c8542dSRatan Gupta     std::optional<bool> locked;
197358345856SAbhishek Patel     std::optional<std::vector<std::string>> accountTypes;
197458345856SAbhishek Patel 
197558345856SAbhishek Patel     bool userSelf = (username == req.session->username);
1976e9cc5172SEd Tanous 
1977031514fbSJunLin Chen     if (req.session == nullptr)
1978031514fbSJunLin Chen     {
1979031514fbSJunLin Chen         messages::internalError(asyncResp->res);
1980031514fbSJunLin Chen         return;
1981031514fbSJunLin Chen     }
1982031514fbSJunLin Chen 
1983e9cc5172SEd Tanous     Privileges effectiveUserPrivileges =
19843e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
1985e9cc5172SEd Tanous     Privileges configureUsers = {"ConfigureUsers"};
1986e9cc5172SEd Tanous     bool userHasConfigureUsers =
1987e9cc5172SEd Tanous         effectiveUserPrivileges.isSupersetOf(configureUsers);
1988e9cc5172SEd Tanous     if (userHasConfigureUsers)
1989e9cc5172SEd Tanous     {
1990e9cc5172SEd Tanous         // Users with ConfigureUsers can modify for all users
199158345856SAbhishek Patel         if (!json_util::readJsonPatch(
199258345856SAbhishek Patel                 req, asyncResp->res, "UserName", newUserName, "Password",
199358345856SAbhishek Patel                 password, "RoleId", roleId, "Enabled", enabled, "Locked",
199458345856SAbhishek Patel                 locked, "AccountTypes", accountTypes))
1995a840879dSEd Tanous         {
1996a840879dSEd Tanous             return;
1997a840879dSEd Tanous         }
1998e9cc5172SEd Tanous     }
1999e9cc5172SEd Tanous     else
2000900f9497SJoseph Reynolds     {
2001e9cc5172SEd Tanous         // ConfigureSelf accounts can only modify their own account
200258345856SAbhishek Patel         if (!userSelf)
2003900f9497SJoseph Reynolds         {
2004900f9497SJoseph Reynolds             messages::insufficientPrivilege(asyncResp->res);
2005900f9497SJoseph Reynolds             return;
2006900f9497SJoseph Reynolds         }
2007031514fbSJunLin Chen 
2008e9cc5172SEd Tanous         // ConfigureSelf accounts can only modify their password
20091ef4c342SEd Tanous         if (!json_util::readJsonPatch(req, asyncResp->res, "Password",
20101ef4c342SEd Tanous                                       password))
2011e9cc5172SEd Tanous         {
2012e9cc5172SEd Tanous             return;
2013e9cc5172SEd Tanous         }
2014900f9497SJoseph Reynolds     }
2015900f9497SJoseph Reynolds 
201666b5ca76Sjayaprakash Mutyala     // if user name is not provided in the patch method or if it
20176c51eab1SEd Tanous     // matches the user name in the URI, then we are treating it as
20186c51eab1SEd Tanous     // updating user properties other then username. If username
20196c51eab1SEd Tanous     // provided doesn't match the URI, then we are treating this as
20206c51eab1SEd Tanous     // user rename request.
202166b5ca76Sjayaprakash Mutyala     if (!newUserName || (newUserName.value() == username))
2022a840879dSEd Tanous     {
20231ef4c342SEd Tanous         updateUserProperties(asyncResp, username, password, enabled, roleId,
202458345856SAbhishek Patel                              locked, accountTypes, userSelf);
202584e12cb7SAppaRao Puli         return;
202684e12cb7SAppaRao Puli     }
202784e12cb7SAppaRao Puli     crow::connections::systemBus->async_method_call(
20286c51eab1SEd Tanous         [asyncResp, username, password(std::move(password)),
20291ef4c342SEd Tanous          roleId(std::move(roleId)), enabled, newUser{std::string(*newUserName)},
203058345856SAbhishek Patel          locked, userSelf, accountTypes(std::move(accountTypes))](
2031e81de512SEd Tanous             const boost::system::error_code& ec, sdbusplus::message_t& m) {
203284e12cb7SAppaRao Puli         if (ec)
203384e12cb7SAppaRao Puli         {
2034002d39b4SEd Tanous             userErrorMessageHandler(m.get_error(), asyncResp, newUser,
2035002d39b4SEd Tanous                                     username);
2036a840879dSEd Tanous             return;
2037a840879dSEd Tanous         }
2038a840879dSEd Tanous 
2039002d39b4SEd Tanous         updateUserProperties(asyncResp, newUser, password, enabled, roleId,
204058345856SAbhishek Patel                              locked, accountTypes, userSelf);
204184e12cb7SAppaRao Puli     },
20421ef4c342SEd Tanous         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
204384e12cb7SAppaRao Puli         "xyz.openbmc_project.User.Manager", "RenameUser", username,
204484e12cb7SAppaRao Puli         *newUserName);
20451ef4c342SEd Tanous }
20461ef4c342SEd Tanous 
20471ef4c342SEd Tanous inline void requestAccountServiceRoutes(App& app)
20481ef4c342SEd Tanous {
20491ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
20504c7d4d33SEd Tanous         .privileges(redfish::privileges::headAccountService)
20514c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
20524c7d4d33SEd Tanous             std::bind_front(handleAccountServiceHead, std::ref(app)));
20534c7d4d33SEd Tanous 
20544c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
20551ef4c342SEd Tanous         .privileges(redfish::privileges::getAccountService)
20561ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
20571ef4c342SEd Tanous             std::bind_front(handleAccountServiceGet, std::ref(app)));
20581ef4c342SEd Tanous 
20591ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
20601ef4c342SEd Tanous         .privileges(redfish::privileges::patchAccountService)
20611ef4c342SEd Tanous         .methods(boost::beast::http::verb::patch)(
20621ef4c342SEd Tanous             std::bind_front(handleAccountServicePatch, std::ref(app)));
20631ef4c342SEd Tanous 
20641ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
20654c7d4d33SEd Tanous         .privileges(redfish::privileges::headManagerAccountCollection)
20664c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
20674c7d4d33SEd Tanous             std::bind_front(handleAccountCollectionHead, std::ref(app)));
20684c7d4d33SEd Tanous 
20694c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
20701ef4c342SEd Tanous         .privileges(redfish::privileges::getManagerAccountCollection)
20711ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
20721ef4c342SEd Tanous             std::bind_front(handleAccountCollectionGet, std::ref(app)));
20731ef4c342SEd Tanous 
20741ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
20751ef4c342SEd Tanous         .privileges(redfish::privileges::postManagerAccountCollection)
20761ef4c342SEd Tanous         .methods(boost::beast::http::verb::post)(
20771ef4c342SEd Tanous             std::bind_front(handleAccountCollectionPost, std::ref(app)));
20781ef4c342SEd Tanous 
20791ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
20804c7d4d33SEd Tanous         .privileges(redfish::privileges::headManagerAccount)
20814c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
20824c7d4d33SEd Tanous             std::bind_front(handleAccountHead, std::ref(app)));
20834c7d4d33SEd Tanous 
20844c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
20851ef4c342SEd Tanous         .privileges(redfish::privileges::getManagerAccount)
20861ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
20871ef4c342SEd Tanous             std::bind_front(handleAccountGet, std::ref(app)));
20881ef4c342SEd Tanous 
20891ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
20901ef4c342SEd Tanous         // TODO this privilege should be using the generated endpoints, but
20911ef4c342SEd Tanous         // because of the special handling of ConfigureSelf, it's not able to
20921ef4c342SEd Tanous         // yet
20931ef4c342SEd Tanous         .privileges({{"ConfigureUsers"}, {"ConfigureSelf"}})
20941ef4c342SEd Tanous         .methods(boost::beast::http::verb::patch)(
20951ef4c342SEd Tanous             std::bind_front(handleAccountPatch, std::ref(app)));
209684e12cb7SAppaRao Puli 
20976c51eab1SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
2098ed398213SEd Tanous         .privileges(redfish::privileges::deleteManagerAccount)
20996c51eab1SEd Tanous         .methods(boost::beast::http::verb::delete_)(
210020fc307fSGunnar Mills             std::bind_front(handleAccountDelete, std::ref(app)));
210106e086d9SEd Tanous }
210288d16c9aSLewanczyk, Dawid 
210388d16c9aSLewanczyk, Dawid } // namespace redfish
2104