xref: /openbmc/bmcweb/features/redfish/lib/account_service.hpp (revision 482a69e72d6be4d9fdefa7b45207e8ac83d4a1a5)
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     }
261d02aad39SEd Tanous     setDbusProperty(asyncResp, "xyz.openbmc_project.User.Manager",
262d02aad39SEd Tanous                     dbusObjectPath, "xyz.openbmc_project.User.Attributes",
263d02aad39SEd 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,
363c1019828SEd Tanous     const std::string& serverType,
364c1019828SEd Tanous     std::vector<std::variant<nlohmann::json::object_t, std::nullptr_t>>& input)
36506785244SRatan Gupta {
36606785244SRatan Gupta     for (size_t index = 0; index < input.size(); index++)
36706785244SRatan Gupta     {
368c1019828SEd Tanous         std::variant<nlohmann::json::object_t, std::nullptr_t>& thisJson =
369c1019828SEd Tanous             input[index];
370c1019828SEd Tanous         nlohmann::json::object_t* obj =
371c1019828SEd Tanous             std::get_if<nlohmann::json::object_t>(&thisJson);
372c1019828SEd Tanous         if (obj == nullptr)
37306785244SRatan Gupta         {
37406785244SRatan Gupta             // delete the existing object
37506785244SRatan Gupta             if (index < roleMapObjData.size())
37606785244SRatan Gupta             {
37706785244SRatan Gupta                 crow::connections::systemBus->async_method_call(
37806785244SRatan Gupta                     [asyncResp, roleMapObjData, serverType,
3795e7e2dc5SEd Tanous                      index](const boost::system::error_code& ec) {
38006785244SRatan Gupta                     if (ec)
38106785244SRatan Gupta                     {
38262598e31SEd Tanous                         BMCWEB_LOG_ERROR("DBUS response error: {}", ec);
38306785244SRatan Gupta                         messages::internalError(asyncResp->res);
38406785244SRatan Gupta                         return;
38506785244SRatan Gupta                     }
38689492a15SPatrick Williams                     asyncResp->res.jsonValue[serverType]["RemoteRoleMapping"]
38789492a15SPatrick Williams                                             [index] = nullptr;
38806785244SRatan Gupta                 },
38906785244SRatan Gupta                     ldapDbusService, roleMapObjData[index].first,
39006785244SRatan Gupta                     "xyz.openbmc_project.Object.Delete", "Delete");
39106785244SRatan Gupta             }
39206785244SRatan Gupta             else
39306785244SRatan Gupta             {
39462598e31SEd Tanous                 BMCWEB_LOG_ERROR("Can't delete the object");
395c1019828SEd Tanous                 messages::propertyValueTypeError(asyncResp->res, "null",
3962e8c4bdaSEd Tanous                                                  "RemoteRoleMapping/" +
3972e8c4bdaSEd Tanous                                                      std::to_string(index));
39806785244SRatan Gupta                 return;
39906785244SRatan Gupta             }
40006785244SRatan Gupta         }
401c1019828SEd Tanous         else if (obj->empty())
40206785244SRatan Gupta         {
40306785244SRatan Gupta             // Don't do anything for the empty objects,parse next json
40406785244SRatan Gupta             // eg {"RemoteRoleMapping",[{}]}
40506785244SRatan Gupta         }
40606785244SRatan Gupta         else
40706785244SRatan Gupta         {
40806785244SRatan Gupta             // update/create the object
40906785244SRatan Gupta             std::optional<std::string> remoteGroup;
41006785244SRatan Gupta             std::optional<std::string> localRole;
41106785244SRatan Gupta 
412c1019828SEd Tanous             if (!json_util::readJsonObject(*obj, asyncResp->res, "RemoteGroup",
413c1019828SEd Tanous                                            remoteGroup, "LocalRole", localRole))
41406785244SRatan Gupta             {
41506785244SRatan Gupta                 continue;
41606785244SRatan Gupta             }
41706785244SRatan Gupta 
41806785244SRatan Gupta             // Update existing RoleMapping Object
41906785244SRatan Gupta             if (index < roleMapObjData.size())
42006785244SRatan Gupta             {
42162598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Update Role Map Object");
42206785244SRatan Gupta                 // If "RemoteGroup" info is provided
42306785244SRatan Gupta                 if (remoteGroup)
42406785244SRatan Gupta                 {
425d02aad39SEd Tanous                     setDbusProperty(
426d02aad39SEd Tanous                         asyncResp, ldapDbusService, roleMapObjData[index].first,
4279ae226faSGeorge Liu                         "xyz.openbmc_project.User.PrivilegeMapperEntry",
428d02aad39SEd Tanous                         "GroupName",
429d02aad39SEd Tanous                         std::format("RemoteRoleMapping/{}/RemoteGroup", index),
43025e055a3SRavi Teja                         *remoteGroup);
43106785244SRatan Gupta                 }
43206785244SRatan Gupta 
43306785244SRatan Gupta                 // If "LocalRole" info is provided
43406785244SRatan Gupta                 if (localRole)
43506785244SRatan Gupta                 {
436d02aad39SEd Tanous                     setDbusProperty(
437d02aad39SEd Tanous                         asyncResp, ldapDbusService, roleMapObjData[index].first,
4389ae226faSGeorge Liu                         "xyz.openbmc_project.User.PrivilegeMapperEntry",
439d02aad39SEd Tanous                         "Privilege",
440d02aad39SEd Tanous                         std::format("RemoteRoleMapping/{}/LocalRole", index),
441d02aad39SEd Tanous                         *localRole);
44206785244SRatan Gupta                 }
44306785244SRatan Gupta             }
44406785244SRatan Gupta             // Create a new RoleMapping Object.
44506785244SRatan Gupta             else
44606785244SRatan Gupta             {
44762598e31SEd Tanous                 BMCWEB_LOG_DEBUG(
44862598e31SEd Tanous                     "setRoleMappingProperties: Creating new Object");
44989492a15SPatrick Williams                 std::string pathString = "RemoteRoleMapping/" +
45089492a15SPatrick Williams                                          std::to_string(index);
45106785244SRatan Gupta 
45206785244SRatan Gupta                 if (!localRole)
45306785244SRatan Gupta                 {
45406785244SRatan Gupta                     messages::propertyMissing(asyncResp->res,
45506785244SRatan Gupta                                               pathString + "/LocalRole");
45606785244SRatan Gupta                     continue;
45706785244SRatan Gupta                 }
45806785244SRatan Gupta                 if (!remoteGroup)
45906785244SRatan Gupta                 {
46006785244SRatan Gupta                     messages::propertyMissing(asyncResp->res,
46106785244SRatan Gupta                                               pathString + "/RemoteGroup");
46206785244SRatan Gupta                     continue;
46306785244SRatan Gupta                 }
46406785244SRatan Gupta 
46506785244SRatan Gupta                 std::string dbusObjectPath;
46606785244SRatan Gupta                 if (serverType == "ActiveDirectory")
46706785244SRatan Gupta                 {
4682c70f800SEd Tanous                     dbusObjectPath = adConfigObject;
46906785244SRatan Gupta                 }
47006785244SRatan Gupta                 else if (serverType == "LDAP")
47106785244SRatan Gupta                 {
47223a21a1cSEd Tanous                     dbusObjectPath = ldapConfigObjectName;
47306785244SRatan Gupta                 }
47406785244SRatan Gupta 
47562598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Remote Group={},LocalRole={}", *remoteGroup,
47662598e31SEd Tanous                                  *localRole);
47706785244SRatan Gupta 
47806785244SRatan Gupta                 crow::connections::systemBus->async_method_call(
479271584abSEd Tanous                     [asyncResp, serverType, localRole,
4805e7e2dc5SEd Tanous                      remoteGroup](const boost::system::error_code& ec) {
48106785244SRatan Gupta                     if (ec)
48206785244SRatan Gupta                     {
48362598e31SEd Tanous                         BMCWEB_LOG_ERROR("DBUS response error: {}", ec);
48406785244SRatan Gupta                         messages::internalError(asyncResp->res);
48506785244SRatan Gupta                         return;
48606785244SRatan Gupta                     }
48706785244SRatan Gupta                     nlohmann::json& remoteRoleJson =
48806785244SRatan Gupta                         asyncResp->res
48906785244SRatan Gupta                             .jsonValue[serverType]["RemoteRoleMapping"];
4901476687dSEd Tanous                     nlohmann::json::object_t roleMapEntry;
4911476687dSEd Tanous                     roleMapEntry["LocalRole"] = *localRole;
4921476687dSEd Tanous                     roleMapEntry["RemoteGroup"] = *remoteGroup;
493b2ba3072SPatrick Williams                     remoteRoleJson.emplace_back(std::move(roleMapEntry));
49406785244SRatan Gupta                 },
49506785244SRatan Gupta                     ldapDbusService, dbusObjectPath, ldapPrivMapperInterface,
4963174e4dfSEd Tanous                     "Create", *remoteGroup,
49706785244SRatan Gupta                     getPrivilegeFromRoleId(std::move(*localRole)));
49806785244SRatan Gupta             }
49906785244SRatan Gupta         }
50006785244SRatan Gupta     }
50106785244SRatan Gupta }
50206785244SRatan Gupta 
50306785244SRatan Gupta /**
5046973a582SRatan Gupta  * Function that retrieves all properties for LDAP config object
5056973a582SRatan Gupta  * into JSON
5066973a582SRatan Gupta  */
5076973a582SRatan Gupta template <typename CallbackFunc>
5086973a582SRatan Gupta inline void getLDAPConfigData(const std::string& ldapType,
5096973a582SRatan Gupta                               CallbackFunc&& callback)
5106973a582SRatan Gupta {
5112b73119cSGeorge Liu     constexpr std::array<std::string_view, 2> interfaces = {
5122b73119cSGeorge Liu         ldapEnableInterface, ldapConfigInterface};
51354fc587aSNagaraju Goruganti 
5142b73119cSGeorge Liu     dbus::utility::getDbusObject(
5152b73119cSGeorge Liu         ldapConfigObjectName, interfaces,
5168cb2c024SEd Tanous         [callback = std::forward<CallbackFunc>(callback),
517c1019828SEd Tanous          ldapType](const boost::system::error_code& ec,
518c1019828SEd Tanous                    const dbus::utility::MapperGetObject& resp) mutable {
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,
531c1019828SEd Tanous             [callback, ldapType](
532c1019828SEd Tanous                 const boost::system::error_code& ec2,
533c1019828SEd Tanous                 const dbus::utility::ManagedObjectType& ldapObjects) mutable {
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 updates the LDAP server address and updates the
6738a07d286SRatan Gupta           json response with the new value.
6748a07d286SRatan Gupta  * @param serviceAddressList address to be updated.
6758a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
6768a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
6778a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
6788a07d286SRatan Gupta  */
6798a07d286SRatan Gupta 
6804f48d5f6SEd Tanous inline void handleServiceAddressPatch(
6818a07d286SRatan Gupta     const std::vector<std::string>& serviceAddressList,
6828d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
6838a07d286SRatan Gupta     const std::string& ldapServerElementName,
6848a07d286SRatan Gupta     const std::string& ldapConfigObject)
6858a07d286SRatan Gupta {
686d02aad39SEd Tanous     setDbusProperty(asyncResp, ldapDbusService, ldapConfigObject,
687d02aad39SEd Tanous                     ldapConfigInterface, "LDAPServerURI",
688d02aad39SEd Tanous                     ldapServerElementName + "/ServiceAddress",
68925e055a3SRavi Teja                     serviceAddressList.front());
6908a07d286SRatan Gupta }
6918a07d286SRatan Gupta /**
6928a07d286SRatan Gupta  * @brief updates the LDAP Bind DN and updates the
6938a07d286SRatan Gupta           json response with the new value.
6948a07d286SRatan Gupta  * @param username name of the user which needs to be updated.
6958a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
6968a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
6978a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
6988a07d286SRatan Gupta  */
6998a07d286SRatan Gupta 
7004f48d5f6SEd Tanous inline void
7014f48d5f6SEd Tanous     handleUserNamePatch(const std::string& username,
7028d1b46d7Szhanghch05                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7038a07d286SRatan Gupta                         const std::string& ldapServerElementName,
7048a07d286SRatan Gupta                         const std::string& ldapConfigObject)
7058a07d286SRatan Gupta {
706d02aad39SEd Tanous     setDbusProperty(asyncResp, ldapDbusService, ldapConfigObject,
707d02aad39SEd Tanous                     ldapConfigInterface, "LDAPBindDN",
708d02aad39SEd Tanous                     ldapServerElementName + "/Authentication/Username",
709d02aad39SEd Tanous                     username);
7108a07d286SRatan Gupta }
7118a07d286SRatan Gupta 
7128a07d286SRatan Gupta /**
7138a07d286SRatan Gupta  * @brief updates the LDAP password
7148a07d286SRatan Gupta  * @param password : ldap password which needs to be updated.
7158a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7168a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7178a07d286SRatan Gupta  *        server(openLDAP/ActiveDirectory)
7188a07d286SRatan Gupta  */
7198a07d286SRatan Gupta 
7204f48d5f6SEd Tanous inline void
7214f48d5f6SEd Tanous     handlePasswordPatch(const std::string& password,
7228d1b46d7Szhanghch05                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7238a07d286SRatan Gupta                         const std::string& ldapServerElementName,
7248a07d286SRatan Gupta                         const std::string& ldapConfigObject)
7258a07d286SRatan Gupta {
726d02aad39SEd Tanous     setDbusProperty(asyncResp, ldapDbusService, ldapConfigObject,
727d02aad39SEd Tanous                     ldapConfigInterface, "LDAPBindDNPassword",
728d02aad39SEd Tanous                     ldapServerElementName + "/Authentication/Password",
729d02aad39SEd Tanous                     password);
7308a07d286SRatan Gupta }
7318a07d286SRatan Gupta 
7328a07d286SRatan Gupta /**
7338a07d286SRatan Gupta  * @brief updates the LDAP BaseDN and updates the
7348a07d286SRatan Gupta           json response with the new value.
7358a07d286SRatan Gupta  * @param baseDNList baseDN list which needs to be updated.
7368a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7378a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7388a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7398a07d286SRatan Gupta  */
7408a07d286SRatan Gupta 
7414f48d5f6SEd Tanous inline void
7424f48d5f6SEd Tanous     handleBaseDNPatch(const std::vector<std::string>& baseDNList,
7438d1b46d7Szhanghch05                       const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7448a07d286SRatan Gupta                       const std::string& ldapServerElementName,
7458a07d286SRatan Gupta                       const std::string& ldapConfigObject)
7468a07d286SRatan Gupta {
747d02aad39SEd Tanous     setDbusProperty(asyncResp, ldapDbusService, ldapConfigObject,
748d02aad39SEd Tanous                     ldapConfigInterface, "LDAPBaseDN",
749d02aad39SEd Tanous                     ldapServerElementName +
750d02aad39SEd Tanous                         "/LDAPService/SearchSettings/BaseDistinguishedNames",
75125e055a3SRavi Teja                     baseDNList.front());
7528a07d286SRatan Gupta }
7538a07d286SRatan Gupta /**
7548a07d286SRatan Gupta  * @brief updates the LDAP user name attribute and updates the
7558a07d286SRatan Gupta           json response with the new value.
7568a07d286SRatan Gupta  * @param userNameAttribute attribute to be updated.
7578a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7588a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7598a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7608a07d286SRatan Gupta  */
7618a07d286SRatan Gupta 
7624f48d5f6SEd Tanous inline void
7634f48d5f6SEd Tanous     handleUserNameAttrPatch(const std::string& userNameAttribute,
7648d1b46d7Szhanghch05                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7658a07d286SRatan Gupta                             const std::string& ldapServerElementName,
7668a07d286SRatan Gupta                             const std::string& ldapConfigObject)
7678a07d286SRatan Gupta {
768d02aad39SEd Tanous     setDbusProperty(asyncResp, ldapDbusService, ldapConfigObject,
769d02aad39SEd Tanous                     ldapConfigInterface, "UserNameAttribute",
770d02aad39SEd Tanous                     ldapServerElementName +
771d02aad39SEd Tanous                         "LDAPService/SearchSettings/UsernameAttribute",
772d02aad39SEd Tanous                     userNameAttribute);
7738a07d286SRatan Gupta }
7748a07d286SRatan Gupta /**
7758a07d286SRatan Gupta  * @brief updates the LDAP group attribute and updates the
7768a07d286SRatan Gupta           json response with the new value.
7778a07d286SRatan Gupta  * @param groupsAttribute attribute to be updated.
7788a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7798a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7808a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7818a07d286SRatan Gupta  */
7828a07d286SRatan Gupta 
7834f48d5f6SEd Tanous inline void handleGroupNameAttrPatch(
7848d1b46d7Szhanghch05     const std::string& groupsAttribute,
7858d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7868a07d286SRatan Gupta     const std::string& ldapServerElementName,
7878a07d286SRatan Gupta     const std::string& ldapConfigObject)
7888a07d286SRatan Gupta {
789d02aad39SEd Tanous     setDbusProperty(asyncResp, ldapDbusService, ldapConfigObject,
790d02aad39SEd Tanous                     ldapConfigInterface, "GroupNameAttribute",
791d02aad39SEd Tanous                     ldapServerElementName +
792d02aad39SEd Tanous                         "/LDAPService/SearchSettings/GroupsAttribute",
793d02aad39SEd Tanous                     groupsAttribute);
7948a07d286SRatan Gupta }
7958a07d286SRatan Gupta /**
7968a07d286SRatan Gupta  * @brief updates the LDAP service enable and updates the
7978a07d286SRatan Gupta           json response with the new value.
7988a07d286SRatan Gupta  * @param input JSON data.
7998a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
8008a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
8018a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
8028a07d286SRatan Gupta  */
8038a07d286SRatan Gupta 
8044f48d5f6SEd Tanous inline void handleServiceEnablePatch(
8056c51eab1SEd Tanous     bool serviceEnabled, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8068a07d286SRatan Gupta     const std::string& ldapServerElementName,
8078a07d286SRatan Gupta     const std::string& ldapConfigObject)
8088a07d286SRatan Gupta {
809d02aad39SEd Tanous     setDbusProperty(asyncResp, ldapDbusService, ldapConfigObject,
810d02aad39SEd Tanous                     ldapEnableInterface, "Enabled",
811d02aad39SEd Tanous                     ldapServerElementName + "/ServiceEnabled", serviceEnabled);
8128a07d286SRatan Gupta }
8138a07d286SRatan Gupta 
814c1019828SEd Tanous struct AuthMethods
81578158631SZbigniew Kurzynski {
81678158631SZbigniew Kurzynski     std::optional<bool> basicAuth;
81778158631SZbigniew Kurzynski     std::optional<bool> cookie;
81878158631SZbigniew Kurzynski     std::optional<bool> sessionToken;
81978158631SZbigniew Kurzynski     std::optional<bool> xToken;
820501f1e58SZbigniew Kurzynski     std::optional<bool> tls;
821c1019828SEd Tanous };
82278158631SZbigniew Kurzynski 
823c1019828SEd Tanous inline void
824c1019828SEd Tanous     handleAuthMethodsPatch(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
825c1019828SEd Tanous                            const AuthMethods& auth)
82678158631SZbigniew Kurzynski {
827c1019828SEd Tanous     persistent_data::AuthConfigMethods& authMethodsConfig =
82852cc112dSEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
82978158631SZbigniew Kurzynski 
830c1019828SEd Tanous     if (auth.basicAuth)
83178158631SZbigniew Kurzynski     {
832f16f6263SAlan Kuo #ifndef BMCWEB_ENABLE_BASIC_AUTHENTICATION
833f16f6263SAlan Kuo         messages::actionNotSupported(
8340fda0f12SGeorge Liu             asyncResp->res,
8350fda0f12SGeorge Liu             "Setting BasicAuth when basic-auth feature is disabled");
836f16f6263SAlan Kuo         return;
837f16f6263SAlan Kuo #endif
838c1019828SEd Tanous         authMethodsConfig.basic = *auth.basicAuth;
83978158631SZbigniew Kurzynski     }
84078158631SZbigniew Kurzynski 
841c1019828SEd Tanous     if (auth.cookie)
84278158631SZbigniew Kurzynski     {
843f16f6263SAlan Kuo #ifndef BMCWEB_ENABLE_COOKIE_AUTHENTICATION
8440fda0f12SGeorge Liu         messages::actionNotSupported(
8450fda0f12SGeorge Liu             asyncResp->res,
8460fda0f12SGeorge Liu             "Setting Cookie when cookie-auth feature is disabled");
847f16f6263SAlan Kuo         return;
848f16f6263SAlan Kuo #endif
849c1019828SEd Tanous         authMethodsConfig.cookie = *auth.cookie;
85078158631SZbigniew Kurzynski     }
85178158631SZbigniew Kurzynski 
852c1019828SEd Tanous     if (auth.sessionToken)
85378158631SZbigniew Kurzynski     {
854f16f6263SAlan Kuo #ifndef BMCWEB_ENABLE_SESSION_AUTHENTICATION
855f16f6263SAlan Kuo         messages::actionNotSupported(
8560fda0f12SGeorge Liu             asyncResp->res,
8570fda0f12SGeorge Liu             "Setting SessionToken when session-auth feature is disabled");
858f16f6263SAlan Kuo         return;
859f16f6263SAlan Kuo #endif
860c1019828SEd Tanous         authMethodsConfig.sessionToken = *auth.sessionToken;
86178158631SZbigniew Kurzynski     }
86278158631SZbigniew Kurzynski 
863c1019828SEd Tanous     if (auth.xToken)
86478158631SZbigniew Kurzynski     {
865f16f6263SAlan Kuo #ifndef BMCWEB_ENABLE_XTOKEN_AUTHENTICATION
8660fda0f12SGeorge Liu         messages::actionNotSupported(
8670fda0f12SGeorge Liu             asyncResp->res,
8680fda0f12SGeorge Liu             "Setting XToken when xtoken-auth feature is disabled");
869f16f6263SAlan Kuo         return;
870f16f6263SAlan Kuo #endif
871c1019828SEd Tanous         authMethodsConfig.xtoken = *auth.xToken;
87278158631SZbigniew Kurzynski     }
87378158631SZbigniew Kurzynski 
874c1019828SEd Tanous     if (auth.tls)
875501f1e58SZbigniew Kurzynski     {
876f16f6263SAlan Kuo #ifndef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
8770fda0f12SGeorge Liu         messages::actionNotSupported(
8780fda0f12SGeorge Liu             asyncResp->res,
8790fda0f12SGeorge Liu             "Setting TLS when mutual-tls-auth feature is disabled");
880f16f6263SAlan Kuo         return;
881f16f6263SAlan Kuo #endif
882c1019828SEd Tanous         authMethodsConfig.tls = *auth.tls;
883501f1e58SZbigniew Kurzynski     }
884501f1e58SZbigniew Kurzynski 
88578158631SZbigniew Kurzynski     if (!authMethodsConfig.basic && !authMethodsConfig.cookie &&
886501f1e58SZbigniew Kurzynski         !authMethodsConfig.sessionToken && !authMethodsConfig.xtoken &&
887501f1e58SZbigniew Kurzynski         !authMethodsConfig.tls)
88878158631SZbigniew Kurzynski     {
88978158631SZbigniew Kurzynski         // Do not allow user to disable everything
89078158631SZbigniew Kurzynski         messages::actionNotSupported(asyncResp->res,
89178158631SZbigniew Kurzynski                                      "of disabling all available methods");
89278158631SZbigniew Kurzynski         return;
89378158631SZbigniew Kurzynski     }
89478158631SZbigniew Kurzynski 
89552cc112dSEd Tanous     persistent_data::SessionStore::getInstance().updateAuthMethodsConfig(
89652cc112dSEd Tanous         authMethodsConfig);
89778158631SZbigniew Kurzynski     // Save configuration immediately
89852cc112dSEd Tanous     persistent_data::getConfig().writeData();
89978158631SZbigniew Kurzynski 
90078158631SZbigniew Kurzynski     messages::success(asyncResp->res);
90178158631SZbigniew Kurzynski }
90278158631SZbigniew Kurzynski 
9038a07d286SRatan Gupta /**
9048a07d286SRatan Gupta  * @brief Get the required values from the given JSON, validates the
9058a07d286SRatan Gupta  *        value and create the LDAP config object.
9068a07d286SRatan Gupta  * @param input JSON data
9078a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
9088a07d286SRatan Gupta  * @param serverType Type of LDAP server(openLDAP/ActiveDirectory)
9098a07d286SRatan Gupta  */
9108a07d286SRatan Gupta 
91110cb44f3SEd Tanous struct LdapPatchParams
91210cb44f3SEd Tanous {
91310cb44f3SEd Tanous     std::optional<std::string> authType;
91410cb44f3SEd Tanous     std::optional<std::vector<std::string>> serviceAddressList;
91510cb44f3SEd Tanous     std::optional<bool> serviceEnabled;
91610cb44f3SEd Tanous     std::optional<std::vector<std::string>> baseDNList;
91710cb44f3SEd Tanous     std::optional<std::string> userNameAttribute;
91810cb44f3SEd Tanous     std::optional<std::string> groupsAttribute;
91910cb44f3SEd Tanous     std::optional<std::string> userName;
92010cb44f3SEd Tanous     std::optional<std::string> password;
92110cb44f3SEd Tanous     std::optional<
92210cb44f3SEd Tanous         std::vector<std::variant<nlohmann::json::object_t, std::nullptr_t>>>
92310cb44f3SEd Tanous         remoteRoleMapData;
92410cb44f3SEd Tanous };
92510cb44f3SEd Tanous 
92610cb44f3SEd Tanous inline void handleLDAPPatch(LdapPatchParams&& input,
9278d1b46d7Szhanghch05                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
9288a07d286SRatan Gupta                             const std::string& serverType)
9298a07d286SRatan Gupta {
930eb2bbe56SRatan Gupta     std::string dbusObjectPath;
931eb2bbe56SRatan Gupta     if (serverType == "ActiveDirectory")
932eb2bbe56SRatan Gupta     {
9332c70f800SEd Tanous         dbusObjectPath = adConfigObject;
934eb2bbe56SRatan Gupta     }
935eb2bbe56SRatan Gupta     else if (serverType == "LDAP")
936eb2bbe56SRatan Gupta     {
93723a21a1cSEd Tanous         dbusObjectPath = ldapConfigObjectName;
938eb2bbe56SRatan Gupta     }
939cb13a392SEd Tanous     else
940cb13a392SEd Tanous     {
94110cb44f3SEd Tanous         BMCWEB_LOG_ERROR("serverType wasn't AD or LDAP but was {}????",
94210cb44f3SEd Tanous                          serverType);
943cb13a392SEd Tanous         return;
944cb13a392SEd Tanous     }
945eb2bbe56SRatan Gupta 
94610cb44f3SEd Tanous     if (input.authType && *input.authType != "UsernameAndPassword")
9478a07d286SRatan Gupta     {
94810cb44f3SEd Tanous         messages::propertyValueNotInList(asyncResp->res, *input.authType,
949c1019828SEd Tanous                                          "AuthenticationType");
950c1019828SEd Tanous         return;
9518a07d286SRatan Gupta     }
952c1019828SEd Tanous 
95310cb44f3SEd Tanous     if (input.serviceAddressList)
9548a07d286SRatan Gupta     {
95510cb44f3SEd Tanous         if (input.serviceAddressList->empty())
9568a07d286SRatan Gupta         {
957e2616cc5SEd Tanous             messages::propertyValueNotInList(
95810cb44f3SEd Tanous                 asyncResp->res, *input.serviceAddressList, "ServiceAddress");
9598a07d286SRatan Gupta             return;
9608a07d286SRatan Gupta         }
9618a07d286SRatan Gupta     }
96210cb44f3SEd Tanous     if (input.baseDNList)
9638a07d286SRatan Gupta     {
96410cb44f3SEd Tanous         if (input.baseDNList->empty())
9658a07d286SRatan Gupta         {
96610cb44f3SEd Tanous             messages::propertyValueNotInList(asyncResp->res, *input.baseDNList,
9678a07d286SRatan Gupta                                              "BaseDistinguishedNames");
9688a07d286SRatan Gupta             return;
9698a07d286SRatan Gupta         }
9708a07d286SRatan Gupta     }
9718a07d286SRatan Gupta 
9728a07d286SRatan Gupta     // nothing to update, then return
97310cb44f3SEd Tanous     if (!input.userName && !input.password && !input.serviceAddressList &&
97410cb44f3SEd Tanous         !input.baseDNList && !input.userNameAttribute &&
97510cb44f3SEd Tanous         !input.groupsAttribute && !input.serviceEnabled &&
97610cb44f3SEd Tanous         !input.remoteRoleMapData)
9778a07d286SRatan Gupta     {
9788a07d286SRatan Gupta         return;
9798a07d286SRatan Gupta     }
9808a07d286SRatan Gupta 
9818a07d286SRatan Gupta     // Get the existing resource first then keep modifying
9828a07d286SRatan Gupta     // whenever any property gets updated.
98310cb44f3SEd Tanous     getLDAPConfigData(serverType,
98410cb44f3SEd Tanous                       [asyncResp, input = std::move(input),
98510cb44f3SEd Tanous                        dbusObjectPath = std::move(dbusObjectPath)](
98610cb44f3SEd Tanous                           bool success, const LDAPConfigData& confData,
987c1019828SEd Tanous                           const std::string& serverT) mutable {
9888a07d286SRatan Gupta         if (!success)
9898a07d286SRatan Gupta         {
9908a07d286SRatan Gupta             messages::internalError(asyncResp->res);
9918a07d286SRatan Gupta             return;
9928a07d286SRatan Gupta         }
9936c51eab1SEd Tanous         parseLDAPConfigData(asyncResp->res.jsonValue, confData, serverT);
9948a07d286SRatan Gupta         if (confData.serviceEnabled)
9958a07d286SRatan Gupta         {
9968a07d286SRatan Gupta             // Disable the service first and update the rest of
9978a07d286SRatan Gupta             // the properties.
9986c51eab1SEd Tanous             handleServiceEnablePatch(false, asyncResp, serverT, dbusObjectPath);
9998a07d286SRatan Gupta         }
10008a07d286SRatan Gupta 
100110cb44f3SEd Tanous         if (input.serviceAddressList)
10028a07d286SRatan Gupta         {
100310cb44f3SEd Tanous             handleServiceAddressPatch(*input.serviceAddressList, asyncResp,
100410cb44f3SEd Tanous                                       serverT, dbusObjectPath);
100510cb44f3SEd Tanous         }
100610cb44f3SEd Tanous         if (input.userName)
100710cb44f3SEd Tanous         {
100810cb44f3SEd Tanous             handleUserNamePatch(*input.userName, asyncResp, serverT,
10096c51eab1SEd Tanous                                 dbusObjectPath);
10108a07d286SRatan Gupta         }
101110cb44f3SEd Tanous         if (input.password)
10128a07d286SRatan Gupta         {
101310cb44f3SEd Tanous             handlePasswordPatch(*input.password, asyncResp, serverT,
101410cb44f3SEd Tanous                                 dbusObjectPath);
10158a07d286SRatan Gupta         }
10168a07d286SRatan Gupta 
101710cb44f3SEd Tanous         if (input.baseDNList)
10188a07d286SRatan Gupta         {
101910cb44f3SEd Tanous             handleBaseDNPatch(*input.baseDNList, asyncResp, serverT,
10206c51eab1SEd Tanous                               dbusObjectPath);
10218a07d286SRatan Gupta         }
102210cb44f3SEd Tanous         if (input.userNameAttribute)
10238a07d286SRatan Gupta         {
102410cb44f3SEd Tanous             handleUserNameAttrPatch(*input.userNameAttribute, asyncResp,
102510cb44f3SEd Tanous                                     serverT, dbusObjectPath);
102610cb44f3SEd Tanous         }
102710cb44f3SEd Tanous         if (input.groupsAttribute)
102810cb44f3SEd Tanous         {
102910cb44f3SEd Tanous             handleGroupNameAttrPatch(*input.groupsAttribute, asyncResp, serverT,
10306c51eab1SEd Tanous                                      dbusObjectPath);
10318a07d286SRatan Gupta         }
103210cb44f3SEd Tanous         if (input.serviceEnabled)
10338a07d286SRatan Gupta         {
10348a07d286SRatan Gupta             // if user has given the value as true then enable
10358a07d286SRatan Gupta             // the service. if user has given false then no-op
10368a07d286SRatan Gupta             // as service is already stopped.
103710cb44f3SEd Tanous             if (*input.serviceEnabled)
10388a07d286SRatan Gupta             {
103910cb44f3SEd Tanous                 handleServiceEnablePatch(*input.serviceEnabled, asyncResp,
104010cb44f3SEd Tanous                                          serverT, dbusObjectPath);
10418a07d286SRatan Gupta             }
10428a07d286SRatan Gupta         }
10438a07d286SRatan Gupta         else
10448a07d286SRatan Gupta         {
10458a07d286SRatan Gupta             // if user has not given the service enabled value
10468a07d286SRatan Gupta             // then revert it to the same state as it was
10478a07d286SRatan Gupta             // before.
10488a07d286SRatan Gupta             handleServiceEnablePatch(confData.serviceEnabled, asyncResp,
104923a21a1cSEd Tanous                                      serverT, dbusObjectPath);
10508a07d286SRatan Gupta         }
105106785244SRatan Gupta 
105210cb44f3SEd Tanous         if (input.remoteRoleMapData)
105306785244SRatan Gupta         {
10546c51eab1SEd Tanous             handleRoleMapPatch(asyncResp, confData.groupRoleList, serverT,
105510cb44f3SEd Tanous                                *input.remoteRoleMapData);
105606785244SRatan Gupta         }
10578a07d286SRatan Gupta     });
10588a07d286SRatan Gupta }
1059d4b5443fSEd Tanous 
106058345856SAbhishek Patel inline void updateUserProperties(
106158345856SAbhishek Patel     std::shared_ptr<bmcweb::AsyncResp> asyncResp, const std::string& username,
1062618c14b4SEd Tanous     const std::optional<std::string>& password,
1063618c14b4SEd Tanous     const std::optional<bool>& enabled,
106458345856SAbhishek Patel     const std::optional<std::string>& roleId, const std::optional<bool>& locked,
106558345856SAbhishek Patel     std::optional<std::vector<std::string>> accountTypes, bool userSelf)
10661abe55efSEd Tanous {
1067b477fd44SP Dheeraj Srujan Kumar     sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
1068b477fd44SP Dheeraj Srujan Kumar     tempObjPath /= username;
1069b477fd44SP Dheeraj Srujan Kumar     std::string dbusObjectPath(tempObjPath);
10706c51eab1SEd Tanous 
10716c51eab1SEd Tanous     dbus::utility::checkDbusPathExists(
1072618c14b4SEd Tanous         dbusObjectPath, [dbusObjectPath, username, password, roleId, enabled,
107358345856SAbhishek Patel                          locked, accountTypes(std::move(accountTypes)),
107458345856SAbhishek Patel                          userSelf, asyncResp{std::move(asyncResp)}](int rc) {
1075e662eae8SEd Tanous         if (rc <= 0)
10766c51eab1SEd Tanous         {
1077d8a5d5d8SJiaqing Zhao             messages::resourceNotFound(asyncResp->res, "ManagerAccount",
10786c51eab1SEd Tanous                                        username);
10796c51eab1SEd Tanous             return;
10806c51eab1SEd Tanous         }
10816c51eab1SEd Tanous 
10826c51eab1SEd Tanous         if (password)
10836c51eab1SEd Tanous         {
10846c51eab1SEd Tanous             int retval = pamUpdatePassword(username, *password);
10856c51eab1SEd Tanous 
10866c51eab1SEd Tanous             if (retval == PAM_USER_UNKNOWN)
10876c51eab1SEd Tanous             {
1088d8a5d5d8SJiaqing Zhao                 messages::resourceNotFound(asyncResp->res, "ManagerAccount",
10896c51eab1SEd Tanous                                            username);
10906c51eab1SEd Tanous             }
10916c51eab1SEd Tanous             else if (retval == PAM_AUTHTOK_ERR)
10926c51eab1SEd Tanous             {
10936c51eab1SEd Tanous                 // If password is invalid
10949bd80831SJason M. Bills                 messages::propertyValueFormatError(asyncResp->res, nullptr,
10959bd80831SJason M. Bills                                                    "Password");
109662598e31SEd Tanous                 BMCWEB_LOG_ERROR("pamUpdatePassword Failed");
10976c51eab1SEd Tanous             }
10986c51eab1SEd Tanous             else if (retval != PAM_SUCCESS)
10996c51eab1SEd Tanous             {
11006c51eab1SEd Tanous                 messages::internalError(asyncResp->res);
11016c51eab1SEd Tanous                 return;
11026c51eab1SEd Tanous             }
1103e7b1b62bSEd Tanous             else
1104e7b1b62bSEd Tanous             {
1105e7b1b62bSEd Tanous                 messages::success(asyncResp->res);
1106e7b1b62bSEd Tanous             }
11076c51eab1SEd Tanous         }
11086c51eab1SEd Tanous 
11096c51eab1SEd Tanous         if (enabled)
11106c51eab1SEd Tanous         {
1111d02aad39SEd Tanous             setDbusProperty(asyncResp, "xyz.openbmc_project.User.Manager",
1112d02aad39SEd Tanous                             dbusObjectPath,
1113d02aad39SEd Tanous                             "xyz.openbmc_project.User.Attributes",
1114d02aad39SEd Tanous                             "UserEnabled", "Enabled", *enabled);
11156c51eab1SEd Tanous         }
11166c51eab1SEd Tanous 
11176c51eab1SEd Tanous         if (roleId)
11186c51eab1SEd Tanous         {
11196c51eab1SEd Tanous             std::string priv = getPrivilegeFromRoleId(*roleId);
11206c51eab1SEd Tanous             if (priv.empty())
11216c51eab1SEd Tanous             {
1122e2616cc5SEd Tanous                 messages::propertyValueNotInList(asyncResp->res, true,
1123e2616cc5SEd Tanous                                                  "Locked");
11246c51eab1SEd Tanous                 return;
11256c51eab1SEd Tanous             }
1126d02aad39SEd Tanous             setDbusProperty(asyncResp, "xyz.openbmc_project.User.Manager",
1127d02aad39SEd Tanous                             dbusObjectPath,
1128d02aad39SEd Tanous                             "xyz.openbmc_project.User.Attributes",
1129d02aad39SEd Tanous                             "UserPrivilege", "RoleId", priv);
11306c51eab1SEd Tanous         }
11316c51eab1SEd Tanous 
11326c51eab1SEd Tanous         if (locked)
11336c51eab1SEd Tanous         {
11346c51eab1SEd Tanous             // admin can unlock the account which is locked by
11356c51eab1SEd Tanous             // successive authentication failures but admin should
11366c51eab1SEd Tanous             // not be allowed to lock an account.
11376c51eab1SEd Tanous             if (*locked)
11386c51eab1SEd Tanous             {
11396c51eab1SEd Tanous                 messages::propertyValueNotInList(asyncResp->res, "true",
11406c51eab1SEd Tanous                                                  "Locked");
11416c51eab1SEd Tanous                 return;
11426c51eab1SEd Tanous             }
1143d02aad39SEd Tanous             setDbusProperty(asyncResp, "xyz.openbmc_project.User.Manager",
1144d02aad39SEd Tanous                             dbusObjectPath,
11459ae226faSGeorge Liu                             "xyz.openbmc_project.User.Attributes",
1146d02aad39SEd Tanous                             "UserLockedForFailedAttempt", "Locked", *locked);
11476c51eab1SEd Tanous         }
114858345856SAbhishek Patel 
114958345856SAbhishek Patel         if (accountTypes)
115058345856SAbhishek Patel         {
115158345856SAbhishek Patel             patchAccountTypes(*accountTypes, asyncResp, dbusObjectPath,
115258345856SAbhishek Patel                               userSelf);
115358345856SAbhishek Patel         }
11546c51eab1SEd Tanous     });
11556c51eab1SEd Tanous }
11566c51eab1SEd Tanous 
11574c7d4d33SEd Tanous inline void handleAccountServiceHead(
11584c7d4d33SEd Tanous     App& app, const crow::Request& req,
11591ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
11606c51eab1SEd Tanous {
11613ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
116245ca1b86SEd Tanous     {
116345ca1b86SEd Tanous         return;
116445ca1b86SEd Tanous     }
11654c7d4d33SEd Tanous     asyncResp->res.addHeader(
11664c7d4d33SEd Tanous         boost::beast::http::field::link,
11674c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/AccountService/AccountService.json>; rel=describedby");
11684c7d4d33SEd Tanous }
11694c7d4d33SEd Tanous 
11704c7d4d33SEd Tanous inline void
11714c7d4d33SEd Tanous     handleAccountServiceGet(App& app, const crow::Request& req,
11724c7d4d33SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
11734c7d4d33SEd Tanous {
1174afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1175afd369c6SJiaqing Zhao     {
1176afd369c6SJiaqing Zhao         return;
1177afd369c6SJiaqing Zhao     }
11783e72c202SNinad Palsule 
11793e72c202SNinad Palsule     if (req.session == nullptr)
11803e72c202SNinad Palsule     {
11813e72c202SNinad Palsule         messages::internalError(asyncResp->res);
11823e72c202SNinad Palsule         return;
11833e72c202SNinad Palsule     }
11843e72c202SNinad Palsule 
1185c1019828SEd Tanous     const persistent_data::AuthConfigMethods& authMethodsConfig =
1186c1019828SEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
1187c1019828SEd Tanous 
1188afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1189afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1190afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/AccountService/AccountService.json>; rel=describedby");
1191afd369c6SJiaqing Zhao 
11921476687dSEd Tanous     nlohmann::json& json = asyncResp->res.jsonValue;
11931476687dSEd Tanous     json["@odata.id"] = "/redfish/v1/AccountService";
1194*482a69e7SRavi Teja     json["@odata.type"] = "#AccountService.v1_15_0.AccountService";
11951476687dSEd Tanous     json["Id"] = "AccountService";
11961476687dSEd Tanous     json["Name"] = "Account Service";
11971476687dSEd Tanous     json["Description"] = "Account Service";
11981476687dSEd Tanous     json["ServiceEnabled"] = true;
11991476687dSEd Tanous     json["MaxPasswordLength"] = 20;
12001ef4c342SEd Tanous     json["Accounts"]["@odata.id"] = "/redfish/v1/AccountService/Accounts";
12011476687dSEd Tanous     json["Roles"]["@odata.id"] = "/redfish/v1/AccountService/Roles";
1202*482a69e7SRavi Teja     json["HTTPBasicAuth"] = authMethodsConfig.basic
1203*482a69e7SRavi Teja                                 ? account_service::BasicAuthState::Enabled
1204*482a69e7SRavi Teja                                 : account_service::BasicAuthState::Disabled;
1205*482a69e7SRavi Teja 
1206*482a69e7SRavi Teja     nlohmann::json::array_t allowed;
1207*482a69e7SRavi Teja     allowed.emplace_back(account_service::BasicAuthState::Enabled);
1208*482a69e7SRavi Teja     allowed.emplace_back(account_service::BasicAuthState::Disabled);
1209*482a69e7SRavi Teja     json["HTTPBasicAuth@AllowableValues"] = std::move(allowed);
1210*482a69e7SRavi Teja 
12111476687dSEd Tanous     json["Oem"]["OpenBMC"]["@odata.type"] =
12125b5574acSEd Tanous         "#OpenBMCAccountService.v1_0_0.AccountService";
12131476687dSEd Tanous     json["Oem"]["OpenBMC"]["@odata.id"] =
12141476687dSEd Tanous         "/redfish/v1/AccountService#/Oem/OpenBMC";
12151476687dSEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["BasicAuth"] =
12161476687dSEd Tanous         authMethodsConfig.basic;
12171476687dSEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["SessionToken"] =
12181476687dSEd Tanous         authMethodsConfig.sessionToken;
12191ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["XToken"] = authMethodsConfig.xtoken;
12201ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["Cookie"] = authMethodsConfig.cookie;
12211ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["TLS"] = authMethodsConfig.tls;
12221476687dSEd Tanous 
12231ef4c342SEd Tanous     // /redfish/v1/AccountService/LDAP/Certificates is something only
12241ef4c342SEd Tanous     // ConfigureManager can access then only display when the user has
12251ef4c342SEd Tanous     // permissions ConfigureManager
122672048780SAbhishek Patel     Privileges effectiveUserPrivileges =
12273e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
122872048780SAbhishek Patel 
122972048780SAbhishek Patel     if (isOperationAllowedWithPrivileges({{"ConfigureManager"}},
123072048780SAbhishek Patel                                          effectiveUserPrivileges))
123172048780SAbhishek Patel     {
12321ef4c342SEd Tanous         asyncResp->res.jsonValue["LDAP"]["Certificates"]["@odata.id"] =
12331476687dSEd Tanous             "/redfish/v1/AccountService/LDAP/Certificates";
123472048780SAbhishek Patel     }
1235d1bde9e5SKrzysztof Grobelny     sdbusplus::asio::getAllProperties(
1236d1bde9e5SKrzysztof Grobelny         *crow::connections::systemBus, "xyz.openbmc_project.User.Manager",
1237d1bde9e5SKrzysztof Grobelny         "/xyz/openbmc_project/user", "xyz.openbmc_project.User.AccountPolicy",
12385e7e2dc5SEd Tanous         [asyncResp](const boost::system::error_code& ec,
12391ef4c342SEd Tanous                     const dbus::utility::DBusPropertiesMap& propertiesList) {
12403d958bbcSAppaRao Puli         if (ec)
12413d958bbcSAppaRao Puli         {
12423d958bbcSAppaRao Puli             messages::internalError(asyncResp->res);
12433d958bbcSAppaRao Puli             return;
12443d958bbcSAppaRao Puli         }
1245d1bde9e5SKrzysztof Grobelny 
124662598e31SEd Tanous         BMCWEB_LOG_DEBUG("Got {}properties for AccountService",
124762598e31SEd Tanous                          propertiesList.size());
1248d1bde9e5SKrzysztof Grobelny 
1249d1bde9e5SKrzysztof Grobelny         const uint8_t* minPasswordLength = nullptr;
1250d1bde9e5SKrzysztof Grobelny         const uint32_t* accountUnlockTimeout = nullptr;
1251d1bde9e5SKrzysztof Grobelny         const uint16_t* maxLoginAttemptBeforeLockout = nullptr;
1252d1bde9e5SKrzysztof Grobelny 
1253d1bde9e5SKrzysztof Grobelny         const bool success = sdbusplus::unpackPropertiesNoThrow(
1254d1bde9e5SKrzysztof Grobelny             dbus_utils::UnpackErrorPrinter(), propertiesList,
1255d1bde9e5SKrzysztof Grobelny             "MinPasswordLength", minPasswordLength, "AccountUnlockTimeout",
1256d1bde9e5SKrzysztof Grobelny             accountUnlockTimeout, "MaxLoginAttemptBeforeLockout",
1257d1bde9e5SKrzysztof Grobelny             maxLoginAttemptBeforeLockout);
1258d1bde9e5SKrzysztof Grobelny 
1259d1bde9e5SKrzysztof Grobelny         if (!success)
12603d958bbcSAppaRao Puli         {
1261d1bde9e5SKrzysztof Grobelny             messages::internalError(asyncResp->res);
1262d1bde9e5SKrzysztof Grobelny             return;
12633d958bbcSAppaRao Puli         }
1264d1bde9e5SKrzysztof Grobelny 
1265d1bde9e5SKrzysztof Grobelny         if (minPasswordLength != nullptr)
12663d958bbcSAppaRao Puli         {
1267d1bde9e5SKrzysztof Grobelny             asyncResp->res.jsonValue["MinPasswordLength"] = *minPasswordLength;
12683d958bbcSAppaRao Puli         }
1269d1bde9e5SKrzysztof Grobelny 
1270d1bde9e5SKrzysztof Grobelny         if (accountUnlockTimeout != nullptr)
12713d958bbcSAppaRao Puli         {
1272d1bde9e5SKrzysztof Grobelny             asyncResp->res.jsonValue["AccountLockoutDuration"] =
1273d1bde9e5SKrzysztof Grobelny                 *accountUnlockTimeout;
1274d1bde9e5SKrzysztof Grobelny         }
1275d1bde9e5SKrzysztof Grobelny 
1276d1bde9e5SKrzysztof Grobelny         if (maxLoginAttemptBeforeLockout != nullptr)
12773d958bbcSAppaRao Puli         {
1278002d39b4SEd Tanous             asyncResp->res.jsonValue["AccountLockoutThreshold"] =
1279d1bde9e5SKrzysztof Grobelny                 *maxLoginAttemptBeforeLockout;
12803d958bbcSAppaRao Puli         }
1281d1bde9e5SKrzysztof Grobelny     });
12826973a582SRatan Gupta 
128302cad96eSEd Tanous     auto callback = [asyncResp](bool success, const LDAPConfigData& confData,
1284ab828d7cSRatan Gupta                                 const std::string& ldapType) {
1285cb13a392SEd Tanous         if (!success)
1286cb13a392SEd Tanous         {
1287cb13a392SEd Tanous             return;
1288cb13a392SEd Tanous         }
1289002d39b4SEd Tanous         parseLDAPConfigData(asyncResp->res.jsonValue, confData, ldapType);
1290ab828d7cSRatan Gupta     };
1291ab828d7cSRatan Gupta 
1292ab828d7cSRatan Gupta     getLDAPConfigData("LDAP", callback);
1293ab828d7cSRatan Gupta     getLDAPConfigData("ActiveDirectory", callback);
12941ef4c342SEd Tanous }
12956973a582SRatan Gupta 
12961ef4c342SEd Tanous inline void handleAccountServicePatch(
12971ef4c342SEd Tanous     App& app, const crow::Request& req,
12981ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
12991ef4c342SEd Tanous {
13003ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
130145ca1b86SEd Tanous     {
130245ca1b86SEd Tanous         return;
130345ca1b86SEd Tanous     }
1304f5ffd806SEd Tanous     std::optional<uint32_t> unlockTimeout;
1305f5ffd806SEd Tanous     std::optional<uint16_t> lockoutThreshold;
1306ef73ad0dSPaul Fertser     std::optional<uint8_t> minPasswordLength;
1307f5ffd806SEd Tanous     std::optional<uint16_t> maxPasswordLength;
130810cb44f3SEd Tanous     LdapPatchParams ldapObject;
130910cb44f3SEd Tanous     LdapPatchParams activeDirectoryObject;
1310c1019828SEd Tanous     AuthMethods auth;
1311*482a69e7SRavi Teja     std::optional<std::string> httpBasicAuth;
1312c1019828SEd Tanous     // clang-format off
131315ed6780SWilly Tu     if (!json_util::readJsonPatch(
1314c1019828SEd Tanous             req, asyncResp->res,
1315c1019828SEd Tanous             "AccountLockoutDuration", unlockTimeout,
1316c1019828SEd Tanous             "AccountLockoutThreshold", lockoutThreshold,
131710cb44f3SEd Tanous             "ActiveDirectory/Authentication/AuthenticationType", activeDirectoryObject.authType,
131810cb44f3SEd Tanous             "ActiveDirectory/Authentication/Password", activeDirectoryObject.password,
131910cb44f3SEd Tanous             "ActiveDirectory/Authentication/Username", activeDirectoryObject.userName,
132010cb44f3SEd Tanous             "ActiveDirectory/LDAPService/SearchSettings/BaseDistinguishedNames", activeDirectoryObject.baseDNList,
132110cb44f3SEd Tanous             "ActiveDirectory/LDAPService/SearchSettings/GroupsAttribute", activeDirectoryObject.groupsAttribute,
132210cb44f3SEd Tanous             "ActiveDirectory/LDAPService/SearchSettings/UsernameAttribute", activeDirectoryObject.userNameAttribute,
132310cb44f3SEd Tanous             "ActiveDirectory/RemoteRoleMapping", activeDirectoryObject.remoteRoleMapData,
132410cb44f3SEd Tanous             "ActiveDirectory/ServiceAddresses", activeDirectoryObject.serviceAddressList,
132510cb44f3SEd Tanous             "ActiveDirectory/ServiceEnabled", activeDirectoryObject.serviceEnabled,
132610cb44f3SEd Tanous             "LDAP/Authentication/AuthenticationType", ldapObject.authType,
132710cb44f3SEd Tanous             "LDAP/Authentication/Password", ldapObject.password,
132810cb44f3SEd Tanous             "LDAP/Authentication/Username", ldapObject.userName,
132910cb44f3SEd Tanous             "LDAP/LDAPService/SearchSettings/BaseDistinguishedNames", ldapObject.baseDNList,
133010cb44f3SEd Tanous             "LDAP/LDAPService/SearchSettings/GroupsAttribute", ldapObject.groupsAttribute,
133110cb44f3SEd Tanous             "LDAP/LDAPService/SearchSettings/UsernameAttribute", ldapObject.userNameAttribute,
133210cb44f3SEd Tanous             "LDAP/RemoteRoleMapping", ldapObject.remoteRoleMapData,
133310cb44f3SEd Tanous             "LDAP/ServiceAddresses", ldapObject.serviceAddressList,
133410cb44f3SEd Tanous             "LDAP/ServiceEnabled", ldapObject.serviceEnabled,
1335c1019828SEd Tanous             "MaxPasswordLength", maxPasswordLength,
1336c1019828SEd Tanous             "MinPasswordLength", minPasswordLength,
1337c1019828SEd Tanous             "Oem/OpenBMC/AuthMethods/BasicAuth", auth.basicAuth,
1338c1019828SEd Tanous             "Oem/OpenBMC/AuthMethods/Cookie", auth.cookie,
1339c1019828SEd Tanous             "Oem/OpenBMC/AuthMethods/SessionToken", auth.sessionToken,
134010cb44f3SEd Tanous             "Oem/OpenBMC/AuthMethods/TLS", auth.tls,
1341*482a69e7SRavi Teja             "Oem/OpenBMC/AuthMethods/XToken", auth.xToken,
1342*482a69e7SRavi Teja             "HTTPBasicAuth", httpBasicAuth))
1343f5ffd806SEd Tanous     {
1344f5ffd806SEd Tanous         return;
1345f5ffd806SEd Tanous     }
1346c1019828SEd Tanous     // clang-format on
1347f5ffd806SEd Tanous 
1348*482a69e7SRavi Teja     if (httpBasicAuth)
1349*482a69e7SRavi Teja     {
1350*482a69e7SRavi Teja         if (*httpBasicAuth == "Enabled")
1351*482a69e7SRavi Teja         {
1352*482a69e7SRavi Teja             auth.basicAuth = true;
1353*482a69e7SRavi Teja         }
1354*482a69e7SRavi Teja         else if (*httpBasicAuth == "Disabled")
1355*482a69e7SRavi Teja         {
1356*482a69e7SRavi Teja             auth.basicAuth = false;
1357*482a69e7SRavi Teja         }
1358*482a69e7SRavi Teja         else
1359*482a69e7SRavi Teja         {
1360*482a69e7SRavi Teja             messages::propertyValueNotInList(asyncResp->res, "HttpBasicAuth",
1361*482a69e7SRavi Teja                                              *httpBasicAuth);
1362*482a69e7SRavi Teja         }
1363*482a69e7SRavi Teja     }
1364*482a69e7SRavi Teja 
1365f5ffd806SEd Tanous     if (minPasswordLength)
1366f5ffd806SEd Tanous     {
1367d02aad39SEd Tanous         setDbusProperty(
1368d02aad39SEd Tanous             asyncResp, "xyz.openbmc_project.User.Manager",
1369d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
13709ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy", "MinPasswordLength",
1371d02aad39SEd Tanous             "MinPasswordLength", *minPasswordLength);
1372f5ffd806SEd Tanous     }
1373f5ffd806SEd Tanous 
1374f5ffd806SEd Tanous     if (maxPasswordLength)
1375f5ffd806SEd Tanous     {
13761ef4c342SEd Tanous         messages::propertyNotWritable(asyncResp->res, "MaxPasswordLength");
1377f5ffd806SEd Tanous     }
1378f5ffd806SEd Tanous 
137910cb44f3SEd Tanous     handleLDAPPatch(std::move(activeDirectoryObject), asyncResp,
138010cb44f3SEd Tanous                     "ActiveDirectory");
138110cb44f3SEd Tanous     handleLDAPPatch(std::move(ldapObject), asyncResp, "LDAP");
1382f5ffd806SEd Tanous 
1383c1019828SEd Tanous     handleAuthMethodsPatch(asyncResp, auth);
1384f5ffd806SEd Tanous 
1385f5ffd806SEd Tanous     if (unlockTimeout)
1386f5ffd806SEd Tanous     {
1387d02aad39SEd Tanous         setDbusProperty(
1388d02aad39SEd Tanous             asyncResp, "xyz.openbmc_project.User.Manager",
1389d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
13909ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy", "AccountUnlockTimeout",
1391d02aad39SEd Tanous             "AccountLockoutDuration", *unlockTimeout);
1392f5ffd806SEd Tanous     }
1393f5ffd806SEd Tanous     if (lockoutThreshold)
1394f5ffd806SEd Tanous     {
1395d02aad39SEd Tanous         setDbusProperty(
1396d02aad39SEd Tanous             asyncResp, "xyz.openbmc_project.User.Manager",
1397d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
13989ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy",
1399d02aad39SEd Tanous             "MaxLoginAttemptBeforeLockout", "AccountLockoutThreshold",
1400d02aad39SEd Tanous             *lockoutThreshold);
1401f5ffd806SEd Tanous     }
14021ef4c342SEd Tanous }
1403f5ffd806SEd Tanous 
14044c7d4d33SEd Tanous inline void handleAccountCollectionHead(
14051ef4c342SEd Tanous     App& app, const crow::Request& req,
14061ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
14071ef4c342SEd Tanous {
14083ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
140945ca1b86SEd Tanous     {
141045ca1b86SEd Tanous         return;
141145ca1b86SEd Tanous     }
14124c7d4d33SEd Tanous     asyncResp->res.addHeader(
14134c7d4d33SEd Tanous         boost::beast::http::field::link,
14144c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/ManagerAccountCollection.json>; rel=describedby");
14154c7d4d33SEd Tanous }
14164c7d4d33SEd Tanous 
14174c7d4d33SEd Tanous inline void handleAccountCollectionGet(
14184c7d4d33SEd Tanous     App& app, const crow::Request& req,
14194c7d4d33SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
14204c7d4d33SEd Tanous {
1421afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1422afd369c6SJiaqing Zhao     {
1423afd369c6SJiaqing Zhao         return;
1424afd369c6SJiaqing Zhao     }
14253e72c202SNinad Palsule 
14263e72c202SNinad Palsule     if (req.session == nullptr)
14273e72c202SNinad Palsule     {
14283e72c202SNinad Palsule         messages::internalError(asyncResp->res);
14293e72c202SNinad Palsule         return;
14303e72c202SNinad Palsule     }
14313e72c202SNinad Palsule 
1432afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1433afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1434afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/ManagerAccountCollection.json>; rel=describedby");
14351476687dSEd Tanous 
14361476687dSEd Tanous     asyncResp->res.jsonValue["@odata.id"] =
14371476687dSEd Tanous         "/redfish/v1/AccountService/Accounts";
14381ef4c342SEd Tanous     asyncResp->res.jsonValue["@odata.type"] = "#ManagerAccountCollection."
14391476687dSEd Tanous                                               "ManagerAccountCollection";
14401476687dSEd Tanous     asyncResp->res.jsonValue["Name"] = "Accounts Collection";
14411476687dSEd Tanous     asyncResp->res.jsonValue["Description"] = "BMC User Accounts";
14420f74e643SEd Tanous 
14436c51eab1SEd Tanous     Privileges effectiveUserPrivileges =
14443e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
14456c51eab1SEd Tanous 
1446f5e29f33SJunLin Chen     std::string thisUser;
1447f5e29f33SJunLin Chen     if (req.session)
1448f5e29f33SJunLin Chen     {
1449f5e29f33SJunLin Chen         thisUser = req.session->username;
1450f5e29f33SJunLin Chen     }
14515eb468daSGeorge Liu     sdbusplus::message::object_path path("/xyz/openbmc_project/user");
14525eb468daSGeorge Liu     dbus::utility::getManagedObjects(
14535eb468daSGeorge Liu         "xyz.openbmc_project.User.Manager", path,
1454cef1ddfbSEd Tanous         [asyncResp, thisUser, effectiveUserPrivileges](
14555e7e2dc5SEd Tanous             const boost::system::error_code& ec,
1456711ac7a9SEd Tanous             const dbus::utility::ManagedObjectType& users) {
1457b9b2e0b2SEd Tanous         if (ec)
1458b9b2e0b2SEd Tanous         {
1459f12894f8SJason M. Bills             messages::internalError(asyncResp->res);
1460b9b2e0b2SEd Tanous             return;
1461b9b2e0b2SEd Tanous         }
1462b9b2e0b2SEd Tanous 
1463cef1ddfbSEd Tanous         bool userCanSeeAllAccounts =
1464002d39b4SEd Tanous             effectiveUserPrivileges.isSupersetOf({"ConfigureUsers"});
1465cef1ddfbSEd Tanous 
1466cef1ddfbSEd Tanous         bool userCanSeeSelf =
1467002d39b4SEd Tanous             effectiveUserPrivileges.isSupersetOf({"ConfigureSelf"});
1468cef1ddfbSEd Tanous 
1469002d39b4SEd Tanous         nlohmann::json& memberArray = asyncResp->res.jsonValue["Members"];
1470b9b2e0b2SEd Tanous         memberArray = nlohmann::json::array();
1471b9b2e0b2SEd Tanous 
14729eb808c1SEd Tanous         for (const auto& userpath : users)
1473b9b2e0b2SEd Tanous         {
14742dfd18efSEd Tanous             std::string user = userpath.first.filename();
14752dfd18efSEd Tanous             if (user.empty())
1476b9b2e0b2SEd Tanous             {
14772dfd18efSEd Tanous                 messages::internalError(asyncResp->res);
147862598e31SEd Tanous                 BMCWEB_LOG_ERROR("Invalid firmware ID");
14792dfd18efSEd Tanous 
14802dfd18efSEd Tanous                 return;
1481b9b2e0b2SEd Tanous             }
1482f365910cSGunnar Mills 
1483f365910cSGunnar Mills             // As clarified by Redfish here:
1484f365910cSGunnar Mills             // https://redfishforum.com/thread/281/manageraccountcollection-change-allows-account-enumeration
14856c51eab1SEd Tanous             // Users without ConfigureUsers, only see their own
14866c51eab1SEd Tanous             // account. Users with ConfigureUsers, see all
14876c51eab1SEd Tanous             // accounts.
14881ef4c342SEd Tanous             if (userCanSeeAllAccounts || (thisUser == user && userCanSeeSelf))
1489f365910cSGunnar Mills             {
14901476687dSEd Tanous                 nlohmann::json::object_t member;
14913b32780dSEd Tanous                 member["@odata.id"] = boost::urls::format(
14923b32780dSEd Tanous                     "/redfish/v1/AccountService/Accounts/{}", user);
1493b2ba3072SPatrick Williams                 memberArray.emplace_back(std::move(member));
1494b9b2e0b2SEd Tanous             }
1495f365910cSGunnar Mills         }
14961ef4c342SEd Tanous         asyncResp->res.jsonValue["Members@odata.count"] = memberArray.size();
14975eb468daSGeorge Liu     });
14981ef4c342SEd Tanous }
14996c51eab1SEd Tanous 
150097e90da3SNinad Palsule inline void processAfterCreateUser(
150197e90da3SNinad Palsule     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
150297e90da3SNinad Palsule     const std::string& username, const std::string& password,
150397e90da3SNinad Palsule     const boost::system::error_code& ec, sdbusplus::message_t& m)
150497e90da3SNinad Palsule {
150597e90da3SNinad Palsule     if (ec)
150697e90da3SNinad Palsule     {
150797e90da3SNinad Palsule         userErrorMessageHandler(m.get_error(), asyncResp, username, "");
150897e90da3SNinad Palsule         return;
150997e90da3SNinad Palsule     }
151097e90da3SNinad Palsule 
151197e90da3SNinad Palsule     if (pamUpdatePassword(username, password) != PAM_SUCCESS)
151297e90da3SNinad Palsule     {
151397e90da3SNinad Palsule         // At this point we have a user that's been
151497e90da3SNinad Palsule         // created, but the password set
151597e90da3SNinad Palsule         // failed.Something is wrong, so delete the user
151697e90da3SNinad Palsule         // that we've already created
151797e90da3SNinad Palsule         sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
151897e90da3SNinad Palsule         tempObjPath /= username;
151997e90da3SNinad Palsule         const std::string userPath(tempObjPath);
152097e90da3SNinad Palsule 
152197e90da3SNinad Palsule         crow::connections::systemBus->async_method_call(
152297e90da3SNinad Palsule             [asyncResp, password](const boost::system::error_code& ec3) {
152397e90da3SNinad Palsule             if (ec3)
152497e90da3SNinad Palsule             {
152597e90da3SNinad Palsule                 messages::internalError(asyncResp->res);
152697e90da3SNinad Palsule                 return;
152797e90da3SNinad Palsule             }
152897e90da3SNinad Palsule 
152997e90da3SNinad Palsule             // If password is invalid
15309bd80831SJason M. Bills             messages::propertyValueFormatError(asyncResp->res, nullptr,
153197e90da3SNinad Palsule                                                "Password");
153297e90da3SNinad Palsule         },
153397e90da3SNinad Palsule             "xyz.openbmc_project.User.Manager", userPath,
153497e90da3SNinad Palsule             "xyz.openbmc_project.Object.Delete", "Delete");
153597e90da3SNinad Palsule 
153662598e31SEd Tanous         BMCWEB_LOG_ERROR("pamUpdatePassword Failed");
153797e90da3SNinad Palsule         return;
153897e90da3SNinad Palsule     }
153997e90da3SNinad Palsule 
154097e90da3SNinad Palsule     messages::created(asyncResp->res);
154197e90da3SNinad Palsule     asyncResp->res.addHeader("Location",
154297e90da3SNinad Palsule                              "/redfish/v1/AccountService/Accounts/" + username);
154397e90da3SNinad Palsule }
154497e90da3SNinad Palsule 
154597e90da3SNinad Palsule inline void processAfterGetAllGroups(
154697e90da3SNinad Palsule     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
154797e90da3SNinad Palsule     const std::string& username, const std::string& password,
1548e01d0c36SEd Tanous     const std::string& roleId, bool enabled,
15499ba73934SNinad Palsule     std::optional<std::vector<std::string>> accountTypes,
155097e90da3SNinad Palsule     const std::vector<std::string>& allGroupsList)
155197e90da3SNinad Palsule {
15523e72c202SNinad Palsule     std::vector<std::string> userGroups;
15539ba73934SNinad Palsule     std::vector<std::string> accountTypeUserGroups;
15549ba73934SNinad Palsule 
15559ba73934SNinad Palsule     // If user specified account types then convert them to unix user groups
15569ba73934SNinad Palsule     if (accountTypes)
15579ba73934SNinad Palsule     {
15589ba73934SNinad Palsule         if (!getUserGroupFromAccountType(asyncResp->res, *accountTypes,
15599ba73934SNinad Palsule                                          accountTypeUserGroups))
15609ba73934SNinad Palsule         {
15619ba73934SNinad Palsule             // Problem in mapping Account Types to User Groups, Error already
15629ba73934SNinad Palsule             // logged.
15639ba73934SNinad Palsule             return;
15649ba73934SNinad Palsule         }
15659ba73934SNinad Palsule     }
15669ba73934SNinad Palsule 
15673e72c202SNinad Palsule     for (const auto& grp : allGroupsList)
15683e72c202SNinad Palsule     {
15699ba73934SNinad Palsule         // If user specified the account type then only accept groups which are
15709ba73934SNinad Palsule         // in the account types group list.
15719ba73934SNinad Palsule         if (!accountTypeUserGroups.empty())
15729ba73934SNinad Palsule         {
15739ba73934SNinad Palsule             bool found = false;
15749ba73934SNinad Palsule             for (const auto& grp1 : accountTypeUserGroups)
15759ba73934SNinad Palsule             {
15769ba73934SNinad Palsule                 if (grp == grp1)
15779ba73934SNinad Palsule                 {
15789ba73934SNinad Palsule                     found = true;
15799ba73934SNinad Palsule                     break;
15809ba73934SNinad Palsule                 }
15819ba73934SNinad Palsule             }
15829ba73934SNinad Palsule             if (!found)
15839ba73934SNinad Palsule             {
15849ba73934SNinad Palsule                 continue;
15859ba73934SNinad Palsule             }
15869ba73934SNinad Palsule         }
15879ba73934SNinad Palsule 
15883e72c202SNinad Palsule         // Console access is provided to the user who is a member of
15893e72c202SNinad Palsule         // hostconsole group and has a administrator role. So, set
15903e72c202SNinad Palsule         // hostconsole group only for the administrator.
15919ba73934SNinad Palsule         if ((grp == "hostconsole") && (roleId != "priv-admin"))
15923e72c202SNinad Palsule         {
15939ba73934SNinad Palsule             if (!accountTypeUserGroups.empty())
15949ba73934SNinad Palsule             {
159562598e31SEd Tanous                 BMCWEB_LOG_ERROR(
159662598e31SEd Tanous                     "Only administrator can get HostConsole access");
15979ba73934SNinad Palsule                 asyncResp->res.result(boost::beast::http::status::bad_request);
15989ba73934SNinad Palsule                 return;
15999ba73934SNinad Palsule             }
16009ba73934SNinad Palsule             continue;
16019ba73934SNinad Palsule         }
16023e72c202SNinad Palsule         userGroups.emplace_back(grp);
16033e72c202SNinad Palsule     }
16049ba73934SNinad Palsule 
16059ba73934SNinad Palsule     // Make sure user specified groups are valid. This is internal error because
16069ba73934SNinad Palsule     // it some inconsistencies between user manager and bmcweb.
16079ba73934SNinad Palsule     if (!accountTypeUserGroups.empty() &&
16089ba73934SNinad Palsule         accountTypeUserGroups.size() != userGroups.size())
16099ba73934SNinad Palsule     {
16109ba73934SNinad Palsule         messages::internalError(asyncResp->res);
16119ba73934SNinad Palsule         return;
16123e72c202SNinad Palsule     }
161397e90da3SNinad Palsule     crow::connections::systemBus->async_method_call(
161497e90da3SNinad Palsule         [asyncResp, username, password](const boost::system::error_code& ec2,
161597e90da3SNinad Palsule                                         sdbusplus::message_t& m) {
161697e90da3SNinad Palsule         processAfterCreateUser(asyncResp, username, password, ec2, m);
161797e90da3SNinad Palsule     },
161897e90da3SNinad Palsule         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
16193e72c202SNinad Palsule         "xyz.openbmc_project.User.Manager", "CreateUser", username, userGroups,
1620e01d0c36SEd Tanous         roleId, enabled);
162197e90da3SNinad Palsule }
162297e90da3SNinad Palsule 
16231ef4c342SEd Tanous inline void handleAccountCollectionPost(
16241ef4c342SEd Tanous     App& app, const crow::Request& req,
16251ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
16261ef4c342SEd Tanous {
16273ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
162845ca1b86SEd Tanous     {
162945ca1b86SEd Tanous         return;
163045ca1b86SEd Tanous     }
16319712f8acSEd Tanous     std::string username;
16329712f8acSEd Tanous     std::string password;
1633e01d0c36SEd Tanous     std::optional<std::string> roleIdJson;
1634e01d0c36SEd Tanous     std::optional<bool> enabledJson;
16359ba73934SNinad Palsule     std::optional<std::vector<std::string>> accountTypes;
1636e01d0c36SEd Tanous     if (!json_util::readJsonPatch(req, asyncResp->res, "UserName", username,
1637e01d0c36SEd Tanous                                   "Password", password, "RoleId", roleIdJson,
1638e01d0c36SEd Tanous                                   "Enabled", enabledJson, "AccountTypes",
1639e01d0c36SEd Tanous                                   accountTypes))
164004ae99ecSEd Tanous     {
164104ae99ecSEd Tanous         return;
164204ae99ecSEd Tanous     }
164304ae99ecSEd Tanous 
1644e01d0c36SEd Tanous     std::string roleId = roleIdJson.value_or("User");
1645e01d0c36SEd Tanous     std::string priv = getPrivilegeFromRoleId(roleId);
164684e12cb7SAppaRao Puli     if (priv.empty())
164704ae99ecSEd Tanous     {
1648e01d0c36SEd Tanous         messages::propertyValueNotInList(asyncResp->res, roleId, "RoleId");
164904ae99ecSEd Tanous         return;
165004ae99ecSEd Tanous     }
16519712f8acSEd Tanous     roleId = priv;
165204ae99ecSEd Tanous 
1653e01d0c36SEd Tanous     bool enabled = enabledJson.value_or(true);
1654e01d0c36SEd Tanous 
1655599c71d8SAyushi Smriti     // Reading AllGroups property
16561e1e598dSJonathan Doman     sdbusplus::asio::getProperty<std::vector<std::string>>(
16571ef4c342SEd Tanous         *crow::connections::systemBus, "xyz.openbmc_project.User.Manager",
16581ef4c342SEd Tanous         "/xyz/openbmc_project/user", "xyz.openbmc_project.User.Manager",
16591ef4c342SEd Tanous         "AllGroups",
16609ba73934SNinad Palsule         [asyncResp, username, password{std::move(password)}, roleId, enabled,
16619ba73934SNinad Palsule          accountTypes](const boost::system::error_code& ec,
16621e1e598dSJonathan Doman                        const std::vector<std::string>& allGroupsList) {
1663599c71d8SAyushi Smriti         if (ec)
1664599c71d8SAyushi Smriti         {
166562598e31SEd Tanous             BMCWEB_LOG_DEBUG("ERROR with async_method_call");
1666599c71d8SAyushi Smriti             messages::internalError(asyncResp->res);
1667599c71d8SAyushi Smriti             return;
1668599c71d8SAyushi Smriti         }
1669599c71d8SAyushi Smriti 
16701e1e598dSJonathan Doman         if (allGroupsList.empty())
1671599c71d8SAyushi Smriti         {
1672599c71d8SAyushi Smriti             messages::internalError(asyncResp->res);
1673599c71d8SAyushi Smriti             return;
1674599c71d8SAyushi Smriti         }
1675599c71d8SAyushi Smriti 
167697e90da3SNinad Palsule         processAfterGetAllGroups(asyncResp, username, password, roleId, enabled,
16779ba73934SNinad Palsule                                  accountTypes, allGroupsList);
16781e1e598dSJonathan Doman     });
16791ef4c342SEd Tanous }
1680b9b2e0b2SEd Tanous 
16811ef4c342SEd Tanous inline void
16824c7d4d33SEd Tanous     handleAccountHead(App& app, const crow::Request& req,
16836c51eab1SEd Tanous                       const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
16844c7d4d33SEd Tanous                       const std::string& /*accountName*/)
16851ef4c342SEd Tanous {
16863ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
168745ca1b86SEd Tanous     {
168845ca1b86SEd Tanous         return;
168945ca1b86SEd Tanous     }
16904c7d4d33SEd Tanous     asyncResp->res.addHeader(
16914c7d4d33SEd Tanous         boost::beast::http::field::link,
16924c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/ManagerAccount/ManagerAccount.json>; rel=describedby");
16934c7d4d33SEd Tanous }
1694afd369c6SJiaqing Zhao 
16954c7d4d33SEd Tanous inline void
16964c7d4d33SEd Tanous     handleAccountGet(App& app, const crow::Request& req,
16974c7d4d33SEd Tanous                      const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
16984c7d4d33SEd Tanous                      const std::string& accountName)
16994c7d4d33SEd Tanous {
1700afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1701afd369c6SJiaqing Zhao     {
1702afd369c6SJiaqing Zhao         return;
1703afd369c6SJiaqing Zhao     }
1704afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1705afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1706afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/ManagerAccount/ManagerAccount.json>; rel=describedby");
1707afd369c6SJiaqing Zhao 
17081ef4c342SEd Tanous #ifdef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
1709031514fbSJunLin Chen     // If authentication is disabled, there are no user accounts
1710d8a5d5d8SJiaqing Zhao     messages::resourceNotFound(asyncResp->res, "ManagerAccount", accountName);
1711031514fbSJunLin Chen     return;
17121ef4c342SEd Tanous #endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
1713afd369c6SJiaqing Zhao 
1714031514fbSJunLin Chen     if (req.session == nullptr)
1715031514fbSJunLin Chen     {
1716031514fbSJunLin Chen         messages::internalError(asyncResp->res);
1717031514fbSJunLin Chen         return;
1718031514fbSJunLin Chen     }
17196c51eab1SEd Tanous     if (req.session->username != accountName)
1720b9b2e0b2SEd Tanous     {
17216c51eab1SEd Tanous         // At this point we've determined that the user is trying to
17221ef4c342SEd Tanous         // modify a user that isn't them.  We need to verify that they
17231ef4c342SEd Tanous         // have permissions to modify other users, so re-run the auth
17241ef4c342SEd Tanous         // check with the same permissions, minus ConfigureSelf.
17256c51eab1SEd Tanous         Privileges effectiveUserPrivileges =
17263e72c202SNinad Palsule             redfish::getUserPrivileges(*req.session);
17271ef4c342SEd Tanous         Privileges requiredPermissionsToChangeNonSelf = {"ConfigureUsers",
17281ef4c342SEd Tanous                                                          "ConfigureManager"};
17296c51eab1SEd Tanous         if (!effectiveUserPrivileges.isSupersetOf(
17306c51eab1SEd Tanous                 requiredPermissionsToChangeNonSelf))
1731900f9497SJoseph Reynolds         {
173262598e31SEd Tanous             BMCWEB_LOG_DEBUG("GET Account denied access");
1733900f9497SJoseph Reynolds             messages::insufficientPrivilege(asyncResp->res);
1734900f9497SJoseph Reynolds             return;
1735900f9497SJoseph Reynolds         }
1736900f9497SJoseph Reynolds     }
1737900f9497SJoseph Reynolds 
17385eb468daSGeorge Liu     sdbusplus::message::object_path path("/xyz/openbmc_project/user");
17395eb468daSGeorge Liu     dbus::utility::getManagedObjects(
17405eb468daSGeorge Liu         "xyz.openbmc_project.User.Manager", path,
17411ef4c342SEd Tanous         [asyncResp,
17425e7e2dc5SEd Tanous          accountName](const boost::system::error_code& ec,
1743711ac7a9SEd Tanous                       const dbus::utility::ManagedObjectType& users) {
1744b9b2e0b2SEd Tanous         if (ec)
1745b9b2e0b2SEd Tanous         {
1746f12894f8SJason M. Bills             messages::internalError(asyncResp->res);
1747b9b2e0b2SEd Tanous             return;
1748b9b2e0b2SEd Tanous         }
17493544d2a7SEd Tanous         const auto userIt = std::ranges::find_if(
175080f79a40SMichael Shen             users,
175180f79a40SMichael Shen             [accountName](
1752b477fd44SP Dheeraj Srujan Kumar                 const std::pair<sdbusplus::message::object_path,
175380f79a40SMichael Shen                                 dbus::utility::DBusInterfacesMap>& user) {
175455f79e6fSEd Tanous             return accountName == user.first.filename();
1755b477fd44SP Dheeraj Srujan Kumar         });
1756b9b2e0b2SEd Tanous 
175784e12cb7SAppaRao Puli         if (userIt == users.end())
1758b9b2e0b2SEd Tanous         {
1759002d39b4SEd Tanous             messages::resourceNotFound(asyncResp->res, "ManagerAccount",
1760002d39b4SEd Tanous                                        accountName);
176184e12cb7SAppaRao Puli             return;
176284e12cb7SAppaRao Puli         }
17634e68c45bSAyushi Smriti 
17641476687dSEd Tanous         asyncResp->res.jsonValue["@odata.type"] =
176558345856SAbhishek Patel             "#ManagerAccount.v1_7_0.ManagerAccount";
17661476687dSEd Tanous         asyncResp->res.jsonValue["Name"] = "User Account";
17671476687dSEd Tanous         asyncResp->res.jsonValue["Description"] = "User Account";
17681476687dSEd Tanous         asyncResp->res.jsonValue["Password"] = nullptr;
176958345856SAbhishek Patel         asyncResp->res.jsonValue["StrictAccountTypes"] = true;
17704e68c45bSAyushi Smriti 
177184e12cb7SAppaRao Puli         for (const auto& interface : userIt->second)
177265b0dc32SEd Tanous         {
1773002d39b4SEd Tanous             if (interface.first == "xyz.openbmc_project.User.Attributes")
177465b0dc32SEd Tanous             {
177565b0dc32SEd Tanous                 for (const auto& property : interface.second)
177665b0dc32SEd Tanous                 {
177765b0dc32SEd Tanous                     if (property.first == "UserEnabled")
177865b0dc32SEd Tanous                     {
177965b0dc32SEd Tanous                         const bool* userEnabled =
1780abf2add6SEd Tanous                             std::get_if<bool>(&property.second);
178165b0dc32SEd Tanous                         if (userEnabled == nullptr)
178265b0dc32SEd Tanous                         {
178362598e31SEd Tanous                             BMCWEB_LOG_ERROR("UserEnabled wasn't a bool");
178484e12cb7SAppaRao Puli                             messages::internalError(asyncResp->res);
178584e12cb7SAppaRao Puli                             return;
178665b0dc32SEd Tanous                         }
1787002d39b4SEd Tanous                         asyncResp->res.jsonValue["Enabled"] = *userEnabled;
178865b0dc32SEd Tanous                     }
1789002d39b4SEd Tanous                     else if (property.first == "UserLockedForFailedAttempt")
179065b0dc32SEd Tanous                     {
179165b0dc32SEd Tanous                         const bool* userLocked =
1792abf2add6SEd Tanous                             std::get_if<bool>(&property.second);
179365b0dc32SEd Tanous                         if (userLocked == nullptr)
179465b0dc32SEd Tanous                         {
179562598e31SEd Tanous                             BMCWEB_LOG_ERROR("UserLockedForF"
179684e12cb7SAppaRao Puli                                              "ailedAttempt "
179762598e31SEd Tanous                                              "wasn't a bool");
179884e12cb7SAppaRao Puli                             messages::internalError(asyncResp->res);
179984e12cb7SAppaRao Puli                             return;
180065b0dc32SEd Tanous                         }
1801002d39b4SEd Tanous                         asyncResp->res.jsonValue["Locked"] = *userLocked;
1802002d39b4SEd Tanous                         asyncResp->res
1803002d39b4SEd Tanous                             .jsonValue["Locked@Redfish.AllowableValues"] = {
18043bf4e632SJoseph Reynolds                             "false"}; // can only unlock accounts
180565b0dc32SEd Tanous                     }
180684e12cb7SAppaRao Puli                     else if (property.first == "UserPrivilege")
180784e12cb7SAppaRao Puli                     {
180854fc587aSNagaraju Goruganti                         const std::string* userPrivPtr =
1809002d39b4SEd Tanous                             std::get_if<std::string>(&property.second);
181054fc587aSNagaraju Goruganti                         if (userPrivPtr == nullptr)
181184e12cb7SAppaRao Puli                         {
181262598e31SEd Tanous                             BMCWEB_LOG_ERROR("UserPrivilege wasn't a "
181362598e31SEd Tanous                                              "string");
181484e12cb7SAppaRao Puli                             messages::internalError(asyncResp->res);
181584e12cb7SAppaRao Puli                             return;
181684e12cb7SAppaRao Puli                         }
18171ef4c342SEd Tanous                         std::string role = getRoleIdFromPrivilege(*userPrivPtr);
181854fc587aSNagaraju Goruganti                         if (role.empty())
181984e12cb7SAppaRao Puli                         {
182062598e31SEd Tanous                             BMCWEB_LOG_ERROR("Invalid user role");
182184e12cb7SAppaRao Puli                             messages::internalError(asyncResp->res);
182284e12cb7SAppaRao Puli                             return;
182384e12cb7SAppaRao Puli                         }
182454fc587aSNagaraju Goruganti                         asyncResp->res.jsonValue["RoleId"] = role;
182584e12cb7SAppaRao Puli 
18261476687dSEd Tanous                         nlohmann::json& roleEntry =
1827002d39b4SEd Tanous                             asyncResp->res.jsonValue["Links"]["Role"];
18283b32780dSEd Tanous                         roleEntry["@odata.id"] = boost::urls::format(
18293b32780dSEd Tanous                             "/redfish/v1/AccountService/Roles/{}", role);
183084e12cb7SAppaRao Puli                     }
1831002d39b4SEd Tanous                     else if (property.first == "UserPasswordExpired")
18323bf4e632SJoseph Reynolds                     {
18333bf4e632SJoseph Reynolds                         const bool* userPasswordExpired =
18343bf4e632SJoseph Reynolds                             std::get_if<bool>(&property.second);
18353bf4e632SJoseph Reynolds                         if (userPasswordExpired == nullptr)
18363bf4e632SJoseph Reynolds                         {
183762598e31SEd Tanous                             BMCWEB_LOG_ERROR(
183862598e31SEd Tanous                                 "UserPasswordExpired wasn't a bool");
18393bf4e632SJoseph Reynolds                             messages::internalError(asyncResp->res);
18403bf4e632SJoseph Reynolds                             return;
18413bf4e632SJoseph Reynolds                         }
1842002d39b4SEd Tanous                         asyncResp->res.jsonValue["PasswordChangeRequired"] =
18433bf4e632SJoseph Reynolds                             *userPasswordExpired;
18443bf4e632SJoseph Reynolds                     }
1845c7229815SAbhishek Patel                     else if (property.first == "UserGroups")
1846c7229815SAbhishek Patel                     {
1847c7229815SAbhishek Patel                         const std::vector<std::string>* userGroups =
1848c7229815SAbhishek Patel                             std::get_if<std::vector<std::string>>(
1849c7229815SAbhishek Patel                                 &property.second);
1850c7229815SAbhishek Patel                         if (userGroups == nullptr)
1851c7229815SAbhishek Patel                         {
185262598e31SEd Tanous                             BMCWEB_LOG_ERROR(
185362598e31SEd Tanous                                 "userGroups wasn't a string vector");
1854c7229815SAbhishek Patel                             messages::internalError(asyncResp->res);
1855c7229815SAbhishek Patel                             return;
1856c7229815SAbhishek Patel                         }
1857c7229815SAbhishek Patel                         if (!translateUserGroup(*userGroups, asyncResp->res))
1858c7229815SAbhishek Patel                         {
185962598e31SEd Tanous                             BMCWEB_LOG_ERROR("userGroups mapping failed");
1860c7229815SAbhishek Patel                             messages::internalError(asyncResp->res);
1861c7229815SAbhishek Patel                             return;
1862c7229815SAbhishek Patel                         }
1863c7229815SAbhishek Patel                     }
186465b0dc32SEd Tanous                 }
186565b0dc32SEd Tanous             }
186665b0dc32SEd Tanous         }
186765b0dc32SEd Tanous 
18683b32780dSEd Tanous         asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
18693b32780dSEd Tanous             "/redfish/v1/AccountService/Accounts/{}", accountName);
1870b9b2e0b2SEd Tanous         asyncResp->res.jsonValue["Id"] = accountName;
1871b9b2e0b2SEd Tanous         asyncResp->res.jsonValue["UserName"] = accountName;
18725eb468daSGeorge Liu     });
18731ef4c342SEd Tanous }
1874a840879dSEd Tanous 
18751ef4c342SEd Tanous inline void
187620fc307fSGunnar Mills     handleAccountDelete(App& app, const crow::Request& req,
18776c51eab1SEd Tanous                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
18781ef4c342SEd Tanous                         const std::string& username)
18791ef4c342SEd Tanous {
18803ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
188145ca1b86SEd Tanous     {
188245ca1b86SEd Tanous         return;
188345ca1b86SEd Tanous     }
18841ef4c342SEd Tanous 
18851ef4c342SEd Tanous #ifdef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
1886031514fbSJunLin Chen     // If authentication is disabled, there are no user accounts
1887d8a5d5d8SJiaqing Zhao     messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
1888031514fbSJunLin Chen     return;
1889031514fbSJunLin Chen 
18901ef4c342SEd Tanous #endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
18911ef4c342SEd Tanous     sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
18921ef4c342SEd Tanous     tempObjPath /= username;
18931ef4c342SEd Tanous     const std::string userPath(tempObjPath);
18941ef4c342SEd Tanous 
18951ef4c342SEd Tanous     crow::connections::systemBus->async_method_call(
18965e7e2dc5SEd Tanous         [asyncResp, username](const boost::system::error_code& ec) {
18971ef4c342SEd Tanous         if (ec)
18981ef4c342SEd Tanous         {
1899d8a5d5d8SJiaqing Zhao             messages::resourceNotFound(asyncResp->res, "ManagerAccount",
19001ef4c342SEd Tanous                                        username);
19011ef4c342SEd Tanous             return;
19021ef4c342SEd Tanous         }
19031ef4c342SEd Tanous 
19041ef4c342SEd Tanous         messages::accountRemoved(asyncResp->res);
19051ef4c342SEd Tanous     },
19061ef4c342SEd Tanous         "xyz.openbmc_project.User.Manager", userPath,
19071ef4c342SEd Tanous         "xyz.openbmc_project.Object.Delete", "Delete");
19081ef4c342SEd Tanous }
19091ef4c342SEd Tanous 
19101ef4c342SEd Tanous inline void
19111ef4c342SEd Tanous     handleAccountPatch(App& app, const crow::Request& req,
19121ef4c342SEd Tanous                        const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
19131ef4c342SEd Tanous                        const std::string& username)
19141ef4c342SEd Tanous {
19151ef4c342SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
19161ef4c342SEd Tanous     {
19171ef4c342SEd Tanous         return;
19181ef4c342SEd Tanous     }
19191ef4c342SEd Tanous #ifdef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
19201ef4c342SEd Tanous     // If authentication is disabled, there are no user accounts
1921d8a5d5d8SJiaqing Zhao     messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
19221ef4c342SEd Tanous     return;
19231ef4c342SEd Tanous 
19241ef4c342SEd Tanous #endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
1925a24526dcSEd Tanous     std::optional<std::string> newUserName;
1926a24526dcSEd Tanous     std::optional<std::string> password;
1927a24526dcSEd Tanous     std::optional<bool> enabled;
1928a24526dcSEd Tanous     std::optional<std::string> roleId;
192924c8542dSRatan Gupta     std::optional<bool> locked;
193058345856SAbhishek Patel     std::optional<std::vector<std::string>> accountTypes;
193158345856SAbhishek Patel 
1932031514fbSJunLin Chen     if (req.session == nullptr)
1933031514fbSJunLin Chen     {
1934031514fbSJunLin Chen         messages::internalError(asyncResp->res);
1935031514fbSJunLin Chen         return;
1936031514fbSJunLin Chen     }
1937031514fbSJunLin Chen 
19382b9c1dfeSEd Tanous     bool userSelf = (username == req.session->username);
19392b9c1dfeSEd Tanous 
1940e9cc5172SEd Tanous     Privileges effectiveUserPrivileges =
19413e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
1942e9cc5172SEd Tanous     Privileges configureUsers = {"ConfigureUsers"};
1943e9cc5172SEd Tanous     bool userHasConfigureUsers =
1944e9cc5172SEd Tanous         effectiveUserPrivileges.isSupersetOf(configureUsers);
1945e9cc5172SEd Tanous     if (userHasConfigureUsers)
1946e9cc5172SEd Tanous     {
1947e9cc5172SEd Tanous         // Users with ConfigureUsers can modify for all users
194858345856SAbhishek Patel         if (!json_util::readJsonPatch(
194958345856SAbhishek Patel                 req, asyncResp->res, "UserName", newUserName, "Password",
195058345856SAbhishek Patel                 password, "RoleId", roleId, "Enabled", enabled, "Locked",
195158345856SAbhishek Patel                 locked, "AccountTypes", accountTypes))
1952a840879dSEd Tanous         {
1953a840879dSEd Tanous             return;
1954a840879dSEd Tanous         }
1955e9cc5172SEd Tanous     }
1956e9cc5172SEd Tanous     else
1957900f9497SJoseph Reynolds     {
1958e9cc5172SEd Tanous         // ConfigureSelf accounts can only modify their own account
195958345856SAbhishek Patel         if (!userSelf)
1960900f9497SJoseph Reynolds         {
1961900f9497SJoseph Reynolds             messages::insufficientPrivilege(asyncResp->res);
1962900f9497SJoseph Reynolds             return;
1963900f9497SJoseph Reynolds         }
1964031514fbSJunLin Chen 
1965e9cc5172SEd Tanous         // ConfigureSelf accounts can only modify their password
19661ef4c342SEd Tanous         if (!json_util::readJsonPatch(req, asyncResp->res, "Password",
19671ef4c342SEd Tanous                                       password))
1968e9cc5172SEd Tanous         {
1969e9cc5172SEd Tanous             return;
1970e9cc5172SEd Tanous         }
1971900f9497SJoseph Reynolds     }
1972900f9497SJoseph Reynolds 
197366b5ca76Sjayaprakash Mutyala     // if user name is not provided in the patch method or if it
19746c51eab1SEd Tanous     // matches the user name in the URI, then we are treating it as
19756c51eab1SEd Tanous     // updating user properties other then username. If username
19766c51eab1SEd Tanous     // provided doesn't match the URI, then we are treating this as
19776c51eab1SEd Tanous     // user rename request.
197866b5ca76Sjayaprakash Mutyala     if (!newUserName || (newUserName.value() == username))
1979a840879dSEd Tanous     {
19801ef4c342SEd Tanous         updateUserProperties(asyncResp, username, password, enabled, roleId,
198158345856SAbhishek Patel                              locked, accountTypes, userSelf);
198284e12cb7SAppaRao Puli         return;
198384e12cb7SAppaRao Puli     }
198484e12cb7SAppaRao Puli     crow::connections::systemBus->async_method_call(
19856c51eab1SEd Tanous         [asyncResp, username, password(std::move(password)),
19861ef4c342SEd Tanous          roleId(std::move(roleId)), enabled, newUser{std::string(*newUserName)},
198758345856SAbhishek Patel          locked, userSelf, accountTypes(std::move(accountTypes))](
1988e81de512SEd Tanous             const boost::system::error_code& ec, sdbusplus::message_t& m) {
198984e12cb7SAppaRao Puli         if (ec)
199084e12cb7SAppaRao Puli         {
1991002d39b4SEd Tanous             userErrorMessageHandler(m.get_error(), asyncResp, newUser,
1992002d39b4SEd Tanous                                     username);
1993a840879dSEd Tanous             return;
1994a840879dSEd Tanous         }
1995a840879dSEd Tanous 
1996002d39b4SEd Tanous         updateUserProperties(asyncResp, newUser, password, enabled, roleId,
199758345856SAbhishek Patel                              locked, accountTypes, userSelf);
199884e12cb7SAppaRao Puli     },
19991ef4c342SEd Tanous         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
200084e12cb7SAppaRao Puli         "xyz.openbmc_project.User.Manager", "RenameUser", username,
200184e12cb7SAppaRao Puli         *newUserName);
20021ef4c342SEd Tanous }
20031ef4c342SEd Tanous 
20041ef4c342SEd Tanous inline void requestAccountServiceRoutes(App& app)
20051ef4c342SEd Tanous {
20061ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
20074c7d4d33SEd Tanous         .privileges(redfish::privileges::headAccountService)
20084c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
20094c7d4d33SEd Tanous             std::bind_front(handleAccountServiceHead, std::ref(app)));
20104c7d4d33SEd Tanous 
20114c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
20121ef4c342SEd Tanous         .privileges(redfish::privileges::getAccountService)
20131ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
20141ef4c342SEd Tanous             std::bind_front(handleAccountServiceGet, std::ref(app)));
20151ef4c342SEd Tanous 
20161ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
20171ef4c342SEd Tanous         .privileges(redfish::privileges::patchAccountService)
20181ef4c342SEd Tanous         .methods(boost::beast::http::verb::patch)(
20191ef4c342SEd Tanous             std::bind_front(handleAccountServicePatch, std::ref(app)));
20201ef4c342SEd Tanous 
20211ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
20224c7d4d33SEd Tanous         .privileges(redfish::privileges::headManagerAccountCollection)
20234c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
20244c7d4d33SEd Tanous             std::bind_front(handleAccountCollectionHead, std::ref(app)));
20254c7d4d33SEd Tanous 
20264c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
20271ef4c342SEd Tanous         .privileges(redfish::privileges::getManagerAccountCollection)
20281ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
20291ef4c342SEd Tanous             std::bind_front(handleAccountCollectionGet, std::ref(app)));
20301ef4c342SEd Tanous 
20311ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
20321ef4c342SEd Tanous         .privileges(redfish::privileges::postManagerAccountCollection)
20331ef4c342SEd Tanous         .methods(boost::beast::http::verb::post)(
20341ef4c342SEd Tanous             std::bind_front(handleAccountCollectionPost, std::ref(app)));
20351ef4c342SEd Tanous 
20361ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
20374c7d4d33SEd Tanous         .privileges(redfish::privileges::headManagerAccount)
20384c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
20394c7d4d33SEd Tanous             std::bind_front(handleAccountHead, std::ref(app)));
20404c7d4d33SEd Tanous 
20414c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
20421ef4c342SEd Tanous         .privileges(redfish::privileges::getManagerAccount)
20431ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
20441ef4c342SEd Tanous             std::bind_front(handleAccountGet, std::ref(app)));
20451ef4c342SEd Tanous 
20461ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
20471ef4c342SEd Tanous         // TODO this privilege should be using the generated endpoints, but
20481ef4c342SEd Tanous         // because of the special handling of ConfigureSelf, it's not able to
20491ef4c342SEd Tanous         // yet
20501ef4c342SEd Tanous         .privileges({{"ConfigureUsers"}, {"ConfigureSelf"}})
20511ef4c342SEd Tanous         .methods(boost::beast::http::verb::patch)(
20521ef4c342SEd Tanous             std::bind_front(handleAccountPatch, std::ref(app)));
205384e12cb7SAppaRao Puli 
20546c51eab1SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
2055ed398213SEd Tanous         .privileges(redfish::privileges::deleteManagerAccount)
20566c51eab1SEd Tanous         .methods(boost::beast::http::verb::delete_)(
205720fc307fSGunnar Mills             std::bind_front(handleAccountDelete, std::ref(app)));
205806e086d9SEd Tanous }
205988d16c9aSLewanczyk, Dawid 
206088d16c9aSLewanczyk, Dawid } // namespace redfish
2061