xref: /openbmc/bmcweb/features/redfish/lib/account_service.hpp (revision c1019828b612ffacea8408eec4a826a8ac601f13)
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,
363*c1019828SEd Tanous     const std::string& serverType,
364*c1019828SEd 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     {
368*c1019828SEd Tanous         std::variant<nlohmann::json::object_t, std::nullptr_t>& thisJson =
369*c1019828SEd Tanous             input[index];
370*c1019828SEd Tanous         nlohmann::json::object_t* obj =
371*c1019828SEd Tanous             std::get_if<nlohmann::json::object_t>(&thisJson);
372*c1019828SEd 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");
395*c1019828SEd Tanous                 messages::propertyValueTypeError(asyncResp->res, "null",
3962e8c4bdaSEd Tanous                                                  "RemoteRoleMapping/" +
3972e8c4bdaSEd Tanous                                                      std::to_string(index));
39806785244SRatan Gupta                 return;
39906785244SRatan Gupta             }
40006785244SRatan Gupta         }
401*c1019828SEd 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 
412*c1019828SEd Tanous             if (!json_util::readJsonObject(*obj, asyncResp->res, "RemoteGroup",
413*c1019828SEd 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,
516*c1019828SEd Tanous         [callback,
517*c1019828SEd Tanous          ldapType](const boost::system::error_code& ec,
518*c1019828SEd 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,
531*c1019828SEd Tanous             [callback, ldapType](
532*c1019828SEd Tanous                 const boost::system::error_code& ec2,
533*c1019828SEd 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 
814*c1019828SEd 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;
821*c1019828SEd Tanous };
82278158631SZbigniew Kurzynski 
823*c1019828SEd Tanous inline void
824*c1019828SEd Tanous     handleAuthMethodsPatch(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
825*c1019828SEd Tanous                            const AuthMethods& auth)
82678158631SZbigniew Kurzynski {
827*c1019828SEd Tanous     persistent_data::AuthConfigMethods& authMethodsConfig =
82852cc112dSEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
82978158631SZbigniew Kurzynski 
830*c1019828SEd 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
838*c1019828SEd Tanous         authMethodsConfig.basic = *auth.basicAuth;
83978158631SZbigniew Kurzynski     }
84078158631SZbigniew Kurzynski 
841*c1019828SEd 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
849*c1019828SEd Tanous         authMethodsConfig.cookie = *auth.cookie;
85078158631SZbigniew Kurzynski     }
85178158631SZbigniew Kurzynski 
852*c1019828SEd 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
860*c1019828SEd Tanous         authMethodsConfig.sessionToken = *auth.sessionToken;
86178158631SZbigniew Kurzynski     }
86278158631SZbigniew Kurzynski 
863*c1019828SEd 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
871*c1019828SEd Tanous         authMethodsConfig.xtoken = *auth.xToken;
87278158631SZbigniew Kurzynski     }
87378158631SZbigniew Kurzynski 
874*c1019828SEd 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
882*c1019828SEd 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 
911*c1019828SEd Tanous inline void handleLDAPPatch(nlohmann::json::object_t& input,
9128d1b46d7Szhanghch05                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
9138a07d286SRatan Gupta                             const std::string& serverType)
9148a07d286SRatan Gupta {
915eb2bbe56SRatan Gupta     std::string dbusObjectPath;
916eb2bbe56SRatan Gupta     if (serverType == "ActiveDirectory")
917eb2bbe56SRatan Gupta     {
9182c70f800SEd Tanous         dbusObjectPath = adConfigObject;
919eb2bbe56SRatan Gupta     }
920eb2bbe56SRatan Gupta     else if (serverType == "LDAP")
921eb2bbe56SRatan Gupta     {
92223a21a1cSEd Tanous         dbusObjectPath = ldapConfigObjectName;
923eb2bbe56SRatan Gupta     }
924cb13a392SEd Tanous     else
925cb13a392SEd Tanous     {
926cb13a392SEd Tanous         return;
927cb13a392SEd Tanous     }
928eb2bbe56SRatan Gupta 
929*c1019828SEd Tanous     std::optional<std::string> authType;
9308a07d286SRatan Gupta     std::optional<std::vector<std::string>> serviceAddressList;
9318a07d286SRatan Gupta     std::optional<bool> serviceEnabled;
9328a07d286SRatan Gupta     std::optional<std::vector<std::string>> baseDNList;
9338a07d286SRatan Gupta     std::optional<std::string> userNameAttribute;
9348a07d286SRatan Gupta     std::optional<std::string> groupsAttribute;
9358a07d286SRatan Gupta     std::optional<std::string> userName;
9368a07d286SRatan Gupta     std::optional<std::string> password;
937*c1019828SEd Tanous     std::optional<
938*c1019828SEd Tanous         std::vector<std::variant<nlohmann::json::object_t, std::nullptr_t>>>
939*c1019828SEd Tanous         remoteRoleMapData;
940*c1019828SEd Tanous     // clang-format off
941*c1019828SEd Tanous     if (!json_util::readJsonObject(input, asyncResp->res,
942*c1019828SEd Tanous           "Authentication/AuthenticationType", authType,
943*c1019828SEd Tanous           "Authentication/Username", userName,
944*c1019828SEd Tanous           "Authentication/Password", password,
945*c1019828SEd Tanous           "LDAPService/SearchSettings/BaseDistinguishedNames", baseDNList,
946*c1019828SEd Tanous           "LDAPService/SearchSettings/UsernameAttribute", userNameAttribute,
947*c1019828SEd Tanous           "LDAPService/SearchSettings/GroupsAttribute", groupsAttribute,
9488a07d286SRatan Gupta           "ServiceAddresses", serviceAddressList,
94906785244SRatan Gupta           "ServiceEnabled", serviceEnabled,
95006785244SRatan Gupta           "RemoteRoleMapping", remoteRoleMapData))
9518a07d286SRatan Gupta     {
9528a07d286SRatan Gupta         return;
9538a07d286SRatan Gupta     }
954*c1019828SEd Tanous     // clang-format on
9558a07d286SRatan Gupta 
956*c1019828SEd Tanous     if (authType && *authType != "UsernameAndPassword")
9578a07d286SRatan Gupta     {
958*c1019828SEd Tanous         messages::propertyValueNotInList(asyncResp->res, *authType,
959*c1019828SEd Tanous                                          "AuthenticationType");
960*c1019828SEd Tanous         return;
9618a07d286SRatan Gupta     }
962*c1019828SEd Tanous 
9638a07d286SRatan Gupta     if (serviceAddressList)
9648a07d286SRatan Gupta     {
96526f6976fSEd Tanous         if (serviceAddressList->empty())
9668a07d286SRatan Gupta         {
967e2616cc5SEd Tanous             messages::propertyValueNotInList(
968e2616cc5SEd Tanous                 asyncResp->res, *serviceAddressList, "ServiceAddress");
9698a07d286SRatan Gupta             return;
9708a07d286SRatan Gupta         }
9718a07d286SRatan Gupta     }
9728a07d286SRatan Gupta     if (baseDNList)
9738a07d286SRatan Gupta     {
97426f6976fSEd Tanous         if (baseDNList->empty())
9758a07d286SRatan Gupta         {
976e2616cc5SEd Tanous             messages::propertyValueNotInList(asyncResp->res, *baseDNList,
9778a07d286SRatan Gupta                                              "BaseDistinguishedNames");
9788a07d286SRatan Gupta             return;
9798a07d286SRatan Gupta         }
9808a07d286SRatan Gupta     }
9818a07d286SRatan Gupta 
9828a07d286SRatan Gupta     // nothing to update, then return
9838a07d286SRatan Gupta     if (!userName && !password && !serviceAddressList && !baseDNList &&
98406785244SRatan Gupta         !userNameAttribute && !groupsAttribute && !serviceEnabled &&
98506785244SRatan Gupta         !remoteRoleMapData)
9868a07d286SRatan Gupta     {
9878a07d286SRatan Gupta         return;
9888a07d286SRatan Gupta     }
9898a07d286SRatan Gupta 
9908a07d286SRatan Gupta     // Get the existing resource first then keep modifying
9918a07d286SRatan Gupta     // whenever any property gets updated.
992002d39b4SEd Tanous     getLDAPConfigData(
993002d39b4SEd Tanous         serverType,
994002d39b4SEd Tanous         [asyncResp, userName, password, baseDNList, userNameAttribute,
995002d39b4SEd Tanous          groupsAttribute, serviceAddressList, serviceEnabled, dbusObjectPath,
996002d39b4SEd Tanous          remoteRoleMapData](bool success, const LDAPConfigData& confData,
997*c1019828SEd Tanous                             const std::string& serverT) mutable {
9988a07d286SRatan Gupta         if (!success)
9998a07d286SRatan Gupta         {
10008a07d286SRatan Gupta             messages::internalError(asyncResp->res);
10018a07d286SRatan Gupta             return;
10028a07d286SRatan Gupta         }
10036c51eab1SEd Tanous         parseLDAPConfigData(asyncResp->res.jsonValue, confData, serverT);
10048a07d286SRatan Gupta         if (confData.serviceEnabled)
10058a07d286SRatan Gupta         {
10068a07d286SRatan Gupta             // Disable the service first and update the rest of
10078a07d286SRatan Gupta             // the properties.
10086c51eab1SEd Tanous             handleServiceEnablePatch(false, asyncResp, serverT, dbusObjectPath);
10098a07d286SRatan Gupta         }
10108a07d286SRatan Gupta 
10118a07d286SRatan Gupta         if (serviceAddressList)
10128a07d286SRatan Gupta         {
10136c51eab1SEd Tanous             handleServiceAddressPatch(*serviceAddressList, asyncResp, serverT,
10146c51eab1SEd Tanous                                       dbusObjectPath);
10158a07d286SRatan Gupta         }
10168a07d286SRatan Gupta         if (userName)
10178a07d286SRatan Gupta         {
10186c51eab1SEd Tanous             handleUserNamePatch(*userName, asyncResp, serverT, dbusObjectPath);
10198a07d286SRatan Gupta         }
10208a07d286SRatan Gupta         if (password)
10218a07d286SRatan Gupta         {
10226c51eab1SEd Tanous             handlePasswordPatch(*password, asyncResp, serverT, dbusObjectPath);
10238a07d286SRatan Gupta         }
10248a07d286SRatan Gupta 
10258a07d286SRatan Gupta         if (baseDNList)
10268a07d286SRatan Gupta         {
10276c51eab1SEd Tanous             handleBaseDNPatch(*baseDNList, asyncResp, serverT, dbusObjectPath);
10288a07d286SRatan Gupta         }
10298a07d286SRatan Gupta         if (userNameAttribute)
10308a07d286SRatan Gupta         {
10316c51eab1SEd Tanous             handleUserNameAttrPatch(*userNameAttribute, asyncResp, serverT,
10326c51eab1SEd Tanous                                     dbusObjectPath);
10338a07d286SRatan Gupta         }
10348a07d286SRatan Gupta         if (groupsAttribute)
10358a07d286SRatan Gupta         {
10366c51eab1SEd Tanous             handleGroupNameAttrPatch(*groupsAttribute, asyncResp, serverT,
10376c51eab1SEd Tanous                                      dbusObjectPath);
10388a07d286SRatan Gupta         }
10398a07d286SRatan Gupta         if (serviceEnabled)
10408a07d286SRatan Gupta         {
10418a07d286SRatan Gupta             // if user has given the value as true then enable
10428a07d286SRatan Gupta             // the service. if user has given false then no-op
10438a07d286SRatan Gupta             // as service is already stopped.
10448a07d286SRatan Gupta             if (*serviceEnabled)
10458a07d286SRatan Gupta             {
10466c51eab1SEd Tanous                 handleServiceEnablePatch(*serviceEnabled, asyncResp, serverT,
10476c51eab1SEd Tanous                                          dbusObjectPath);
10488a07d286SRatan Gupta             }
10498a07d286SRatan Gupta         }
10508a07d286SRatan Gupta         else
10518a07d286SRatan Gupta         {
10528a07d286SRatan Gupta             // if user has not given the service enabled value
10538a07d286SRatan Gupta             // then revert it to the same state as it was
10548a07d286SRatan Gupta             // before.
10558a07d286SRatan Gupta             handleServiceEnablePatch(confData.serviceEnabled, asyncResp,
105623a21a1cSEd Tanous                                      serverT, dbusObjectPath);
10578a07d286SRatan Gupta         }
105806785244SRatan Gupta 
105906785244SRatan Gupta         if (remoteRoleMapData)
106006785244SRatan Gupta         {
10616c51eab1SEd Tanous             handleRoleMapPatch(asyncResp, confData.groupRoleList, serverT,
10626c51eab1SEd Tanous                                *remoteRoleMapData);
106306785244SRatan Gupta         }
10648a07d286SRatan Gupta     });
10658a07d286SRatan Gupta }
1066d4b5443fSEd Tanous 
106758345856SAbhishek Patel inline void updateUserProperties(
106858345856SAbhishek Patel     std::shared_ptr<bmcweb::AsyncResp> asyncResp, const std::string& username,
1069618c14b4SEd Tanous     const std::optional<std::string>& password,
1070618c14b4SEd Tanous     const std::optional<bool>& enabled,
107158345856SAbhishek Patel     const std::optional<std::string>& roleId, const std::optional<bool>& locked,
107258345856SAbhishek Patel     std::optional<std::vector<std::string>> accountTypes, bool userSelf)
10731abe55efSEd Tanous {
1074b477fd44SP Dheeraj Srujan Kumar     sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
1075b477fd44SP Dheeraj Srujan Kumar     tempObjPath /= username;
1076b477fd44SP Dheeraj Srujan Kumar     std::string dbusObjectPath(tempObjPath);
10776c51eab1SEd Tanous 
10786c51eab1SEd Tanous     dbus::utility::checkDbusPathExists(
1079618c14b4SEd Tanous         dbusObjectPath, [dbusObjectPath, username, password, roleId, enabled,
108058345856SAbhishek Patel                          locked, accountTypes(std::move(accountTypes)),
108158345856SAbhishek Patel                          userSelf, asyncResp{std::move(asyncResp)}](int rc) {
1082e662eae8SEd Tanous         if (rc <= 0)
10836c51eab1SEd Tanous         {
1084d8a5d5d8SJiaqing Zhao             messages::resourceNotFound(asyncResp->res, "ManagerAccount",
10856c51eab1SEd Tanous                                        username);
10866c51eab1SEd Tanous             return;
10876c51eab1SEd Tanous         }
10886c51eab1SEd Tanous 
10896c51eab1SEd Tanous         if (password)
10906c51eab1SEd Tanous         {
10916c51eab1SEd Tanous             int retval = pamUpdatePassword(username, *password);
10926c51eab1SEd Tanous 
10936c51eab1SEd Tanous             if (retval == PAM_USER_UNKNOWN)
10946c51eab1SEd Tanous             {
1095d8a5d5d8SJiaqing Zhao                 messages::resourceNotFound(asyncResp->res, "ManagerAccount",
10966c51eab1SEd Tanous                                            username);
10976c51eab1SEd Tanous             }
10986c51eab1SEd Tanous             else if (retval == PAM_AUTHTOK_ERR)
10996c51eab1SEd Tanous             {
11006c51eab1SEd Tanous                 // If password is invalid
11019bd80831SJason M. Bills                 messages::propertyValueFormatError(asyncResp->res, nullptr,
11029bd80831SJason M. Bills                                                    "Password");
110362598e31SEd Tanous                 BMCWEB_LOG_ERROR("pamUpdatePassword Failed");
11046c51eab1SEd Tanous             }
11056c51eab1SEd Tanous             else if (retval != PAM_SUCCESS)
11066c51eab1SEd Tanous             {
11076c51eab1SEd Tanous                 messages::internalError(asyncResp->res);
11086c51eab1SEd Tanous                 return;
11096c51eab1SEd Tanous             }
1110e7b1b62bSEd Tanous             else
1111e7b1b62bSEd Tanous             {
1112e7b1b62bSEd Tanous                 messages::success(asyncResp->res);
1113e7b1b62bSEd Tanous             }
11146c51eab1SEd Tanous         }
11156c51eab1SEd Tanous 
11166c51eab1SEd Tanous         if (enabled)
11176c51eab1SEd Tanous         {
1118d02aad39SEd Tanous             setDbusProperty(asyncResp, "xyz.openbmc_project.User.Manager",
1119d02aad39SEd Tanous                             dbusObjectPath,
1120d02aad39SEd Tanous                             "xyz.openbmc_project.User.Attributes",
1121d02aad39SEd Tanous                             "UserEnabled", "Enabled", *enabled);
11226c51eab1SEd Tanous         }
11236c51eab1SEd Tanous 
11246c51eab1SEd Tanous         if (roleId)
11256c51eab1SEd Tanous         {
11266c51eab1SEd Tanous             std::string priv = getPrivilegeFromRoleId(*roleId);
11276c51eab1SEd Tanous             if (priv.empty())
11286c51eab1SEd Tanous             {
1129e2616cc5SEd Tanous                 messages::propertyValueNotInList(asyncResp->res, true,
1130e2616cc5SEd Tanous                                                  "Locked");
11316c51eab1SEd Tanous                 return;
11326c51eab1SEd Tanous             }
1133d02aad39SEd Tanous             setDbusProperty(asyncResp, "xyz.openbmc_project.User.Manager",
1134d02aad39SEd Tanous                             dbusObjectPath,
1135d02aad39SEd Tanous                             "xyz.openbmc_project.User.Attributes",
1136d02aad39SEd Tanous                             "UserPrivilege", "RoleId", priv);
11376c51eab1SEd Tanous         }
11386c51eab1SEd Tanous 
11396c51eab1SEd Tanous         if (locked)
11406c51eab1SEd Tanous         {
11416c51eab1SEd Tanous             // admin can unlock the account which is locked by
11426c51eab1SEd Tanous             // successive authentication failures but admin should
11436c51eab1SEd Tanous             // not be allowed to lock an account.
11446c51eab1SEd Tanous             if (*locked)
11456c51eab1SEd Tanous             {
11466c51eab1SEd Tanous                 messages::propertyValueNotInList(asyncResp->res, "true",
11476c51eab1SEd Tanous                                                  "Locked");
11486c51eab1SEd Tanous                 return;
11496c51eab1SEd Tanous             }
1150d02aad39SEd Tanous             setDbusProperty(asyncResp, "xyz.openbmc_project.User.Manager",
1151d02aad39SEd Tanous                             dbusObjectPath,
11529ae226faSGeorge Liu                             "xyz.openbmc_project.User.Attributes",
1153d02aad39SEd Tanous                             "UserLockedForFailedAttempt", "Locked", *locked);
11546c51eab1SEd Tanous         }
115558345856SAbhishek Patel 
115658345856SAbhishek Patel         if (accountTypes)
115758345856SAbhishek Patel         {
115858345856SAbhishek Patel             patchAccountTypes(*accountTypes, asyncResp, dbusObjectPath,
115958345856SAbhishek Patel                               userSelf);
116058345856SAbhishek Patel         }
11616c51eab1SEd Tanous     });
11626c51eab1SEd Tanous }
11636c51eab1SEd Tanous 
11644c7d4d33SEd Tanous inline void handleAccountServiceHead(
11654c7d4d33SEd Tanous     App& app, const crow::Request& req,
11661ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
11676c51eab1SEd Tanous {
11683ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
116945ca1b86SEd Tanous     {
117045ca1b86SEd Tanous         return;
117145ca1b86SEd Tanous     }
11724c7d4d33SEd Tanous     asyncResp->res.addHeader(
11734c7d4d33SEd Tanous         boost::beast::http::field::link,
11744c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/AccountService/AccountService.json>; rel=describedby");
11754c7d4d33SEd Tanous }
11764c7d4d33SEd Tanous 
11774c7d4d33SEd Tanous inline void
11784c7d4d33SEd Tanous     handleAccountServiceGet(App& app, const crow::Request& req,
11794c7d4d33SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
11804c7d4d33SEd Tanous {
1181afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1182afd369c6SJiaqing Zhao     {
1183afd369c6SJiaqing Zhao         return;
1184afd369c6SJiaqing Zhao     }
11853e72c202SNinad Palsule 
11863e72c202SNinad Palsule     if (req.session == nullptr)
11873e72c202SNinad Palsule     {
11883e72c202SNinad Palsule         messages::internalError(asyncResp->res);
11893e72c202SNinad Palsule         return;
11903e72c202SNinad Palsule     }
11913e72c202SNinad Palsule 
1192*c1019828SEd Tanous     const persistent_data::AuthConfigMethods& authMethodsConfig =
1193*c1019828SEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
1194*c1019828SEd Tanous 
1195afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1196afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1197afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/AccountService/AccountService.json>; rel=describedby");
1198afd369c6SJiaqing Zhao 
11991476687dSEd Tanous     nlohmann::json& json = asyncResp->res.jsonValue;
12001476687dSEd Tanous     json["@odata.id"] = "/redfish/v1/AccountService";
12011476687dSEd Tanous     json["@odata.type"] = "#AccountService."
12021476687dSEd Tanous                           "v1_10_0.AccountService";
12031476687dSEd Tanous     json["Id"] = "AccountService";
12041476687dSEd Tanous     json["Name"] = "Account Service";
12051476687dSEd Tanous     json["Description"] = "Account Service";
12061476687dSEd Tanous     json["ServiceEnabled"] = true;
12071476687dSEd Tanous     json["MaxPasswordLength"] = 20;
12081ef4c342SEd Tanous     json["Accounts"]["@odata.id"] = "/redfish/v1/AccountService/Accounts";
12091476687dSEd Tanous     json["Roles"]["@odata.id"] = "/redfish/v1/AccountService/Roles";
12101476687dSEd Tanous     json["Oem"]["OpenBMC"]["@odata.type"] =
12115b5574acSEd Tanous         "#OpenBMCAccountService.v1_0_0.AccountService";
12121476687dSEd Tanous     json["Oem"]["OpenBMC"]["@odata.id"] =
12131476687dSEd Tanous         "/redfish/v1/AccountService#/Oem/OpenBMC";
12141476687dSEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["BasicAuth"] =
12151476687dSEd Tanous         authMethodsConfig.basic;
12161476687dSEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["SessionToken"] =
12171476687dSEd Tanous         authMethodsConfig.sessionToken;
12181ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["XToken"] = authMethodsConfig.xtoken;
12191ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["Cookie"] = authMethodsConfig.cookie;
12201ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["TLS"] = authMethodsConfig.tls;
12211476687dSEd Tanous 
12221ef4c342SEd Tanous     // /redfish/v1/AccountService/LDAP/Certificates is something only
12231ef4c342SEd Tanous     // ConfigureManager can access then only display when the user has
12241ef4c342SEd Tanous     // permissions ConfigureManager
122572048780SAbhishek Patel     Privileges effectiveUserPrivileges =
12263e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
122772048780SAbhishek Patel 
122872048780SAbhishek Patel     if (isOperationAllowedWithPrivileges({{"ConfigureManager"}},
122972048780SAbhishek Patel                                          effectiveUserPrivileges))
123072048780SAbhishek Patel     {
12311ef4c342SEd Tanous         asyncResp->res.jsonValue["LDAP"]["Certificates"]["@odata.id"] =
12321476687dSEd Tanous             "/redfish/v1/AccountService/LDAP/Certificates";
123372048780SAbhishek Patel     }
1234d1bde9e5SKrzysztof Grobelny     sdbusplus::asio::getAllProperties(
1235d1bde9e5SKrzysztof Grobelny         *crow::connections::systemBus, "xyz.openbmc_project.User.Manager",
1236d1bde9e5SKrzysztof Grobelny         "/xyz/openbmc_project/user", "xyz.openbmc_project.User.AccountPolicy",
12375e7e2dc5SEd Tanous         [asyncResp](const boost::system::error_code& ec,
12381ef4c342SEd Tanous                     const dbus::utility::DBusPropertiesMap& propertiesList) {
12393d958bbcSAppaRao Puli         if (ec)
12403d958bbcSAppaRao Puli         {
12413d958bbcSAppaRao Puli             messages::internalError(asyncResp->res);
12423d958bbcSAppaRao Puli             return;
12433d958bbcSAppaRao Puli         }
1244d1bde9e5SKrzysztof Grobelny 
124562598e31SEd Tanous         BMCWEB_LOG_DEBUG("Got {}properties for AccountService",
124662598e31SEd Tanous                          propertiesList.size());
1247d1bde9e5SKrzysztof Grobelny 
1248d1bde9e5SKrzysztof Grobelny         const uint8_t* minPasswordLength = nullptr;
1249d1bde9e5SKrzysztof Grobelny         const uint32_t* accountUnlockTimeout = nullptr;
1250d1bde9e5SKrzysztof Grobelny         const uint16_t* maxLoginAttemptBeforeLockout = nullptr;
1251d1bde9e5SKrzysztof Grobelny 
1252d1bde9e5SKrzysztof Grobelny         const bool success = sdbusplus::unpackPropertiesNoThrow(
1253d1bde9e5SKrzysztof Grobelny             dbus_utils::UnpackErrorPrinter(), propertiesList,
1254d1bde9e5SKrzysztof Grobelny             "MinPasswordLength", minPasswordLength, "AccountUnlockTimeout",
1255d1bde9e5SKrzysztof Grobelny             accountUnlockTimeout, "MaxLoginAttemptBeforeLockout",
1256d1bde9e5SKrzysztof Grobelny             maxLoginAttemptBeforeLockout);
1257d1bde9e5SKrzysztof Grobelny 
1258d1bde9e5SKrzysztof Grobelny         if (!success)
12593d958bbcSAppaRao Puli         {
1260d1bde9e5SKrzysztof Grobelny             messages::internalError(asyncResp->res);
1261d1bde9e5SKrzysztof Grobelny             return;
12623d958bbcSAppaRao Puli         }
1263d1bde9e5SKrzysztof Grobelny 
1264d1bde9e5SKrzysztof Grobelny         if (minPasswordLength != nullptr)
12653d958bbcSAppaRao Puli         {
1266d1bde9e5SKrzysztof Grobelny             asyncResp->res.jsonValue["MinPasswordLength"] = *minPasswordLength;
12673d958bbcSAppaRao Puli         }
1268d1bde9e5SKrzysztof Grobelny 
1269d1bde9e5SKrzysztof Grobelny         if (accountUnlockTimeout != nullptr)
12703d958bbcSAppaRao Puli         {
1271d1bde9e5SKrzysztof Grobelny             asyncResp->res.jsonValue["AccountLockoutDuration"] =
1272d1bde9e5SKrzysztof Grobelny                 *accountUnlockTimeout;
1273d1bde9e5SKrzysztof Grobelny         }
1274d1bde9e5SKrzysztof Grobelny 
1275d1bde9e5SKrzysztof Grobelny         if (maxLoginAttemptBeforeLockout != nullptr)
12763d958bbcSAppaRao Puli         {
1277002d39b4SEd Tanous             asyncResp->res.jsonValue["AccountLockoutThreshold"] =
1278d1bde9e5SKrzysztof Grobelny                 *maxLoginAttemptBeforeLockout;
12793d958bbcSAppaRao Puli         }
1280d1bde9e5SKrzysztof Grobelny     });
12816973a582SRatan Gupta 
128202cad96eSEd Tanous     auto callback = [asyncResp](bool success, const LDAPConfigData& confData,
1283ab828d7cSRatan Gupta                                 const std::string& ldapType) {
1284cb13a392SEd Tanous         if (!success)
1285cb13a392SEd Tanous         {
1286cb13a392SEd Tanous             return;
1287cb13a392SEd Tanous         }
1288002d39b4SEd Tanous         parseLDAPConfigData(asyncResp->res.jsonValue, confData, ldapType);
1289ab828d7cSRatan Gupta     };
1290ab828d7cSRatan Gupta 
1291ab828d7cSRatan Gupta     getLDAPConfigData("LDAP", callback);
1292ab828d7cSRatan Gupta     getLDAPConfigData("ActiveDirectory", callback);
12931ef4c342SEd Tanous }
12946973a582SRatan Gupta 
12951ef4c342SEd Tanous inline void handleAccountServicePatch(
12961ef4c342SEd Tanous     App& app, const crow::Request& req,
12971ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
12981ef4c342SEd Tanous {
12993ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
130045ca1b86SEd Tanous     {
130145ca1b86SEd Tanous         return;
130245ca1b86SEd Tanous     }
1303f5ffd806SEd Tanous     std::optional<uint32_t> unlockTimeout;
1304f5ffd806SEd Tanous     std::optional<uint16_t> lockoutThreshold;
1305ef73ad0dSPaul Fertser     std::optional<uint8_t> minPasswordLength;
1306f5ffd806SEd Tanous     std::optional<uint16_t> maxPasswordLength;
1307*c1019828SEd Tanous     std::optional<nlohmann::json::object_t> ldapObject;
1308*c1019828SEd Tanous     std::optional<nlohmann::json::object_t> activeDirectoryObject;
1309*c1019828SEd Tanous     AuthMethods auth;
1310*c1019828SEd Tanous     // clang-format off
131115ed6780SWilly Tu     if (!json_util::readJsonPatch(
1312*c1019828SEd Tanous             req, asyncResp->res,
1313*c1019828SEd Tanous             "AccountLockoutDuration", unlockTimeout,
1314*c1019828SEd Tanous             "AccountLockoutThreshold", lockoutThreshold,
1315*c1019828SEd Tanous             "MaxPasswordLength", maxPasswordLength,
1316*c1019828SEd Tanous             "MinPasswordLength", minPasswordLength,
1317*c1019828SEd Tanous             "LDAP", ldapObject,
1318*c1019828SEd Tanous             "ActiveDirectory", activeDirectoryObject,
1319*c1019828SEd Tanous             "Oem/OpenBMC/AuthMethods/BasicAuth", auth.basicAuth,
1320*c1019828SEd Tanous             "Oem/OpenBMC/AuthMethods/Cookie", auth.cookie,
1321*c1019828SEd Tanous             "Oem/OpenBMC/AuthMethods/SessionToken", auth.sessionToken,
1322*c1019828SEd Tanous             "Oem/OpenBMC/AuthMethods/XToken", auth.xToken,
1323*c1019828SEd Tanous             "Oem/OpenBMC/AuthMethods/TLS", auth.tls))
1324f5ffd806SEd Tanous     {
1325f5ffd806SEd Tanous         return;
1326f5ffd806SEd Tanous     }
1327*c1019828SEd Tanous     // clang-format on
1328f5ffd806SEd Tanous 
1329f5ffd806SEd Tanous     if (minPasswordLength)
1330f5ffd806SEd Tanous     {
1331d02aad39SEd Tanous         setDbusProperty(
1332d02aad39SEd Tanous             asyncResp, "xyz.openbmc_project.User.Manager",
1333d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
13349ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy", "MinPasswordLength",
1335d02aad39SEd Tanous             "MinPasswordLength", *minPasswordLength);
1336f5ffd806SEd Tanous     }
1337f5ffd806SEd Tanous 
1338f5ffd806SEd Tanous     if (maxPasswordLength)
1339f5ffd806SEd Tanous     {
13401ef4c342SEd Tanous         messages::propertyNotWritable(asyncResp->res, "MaxPasswordLength");
1341f5ffd806SEd Tanous     }
1342f5ffd806SEd Tanous 
1343f5ffd806SEd Tanous     if (ldapObject)
1344f5ffd806SEd Tanous     {
1345f5ffd806SEd Tanous         handleLDAPPatch(*ldapObject, asyncResp, "LDAP");
1346f5ffd806SEd Tanous     }
1347f5ffd806SEd Tanous 
1348*c1019828SEd Tanous     handleAuthMethodsPatch(asyncResp, auth);
1349f5ffd806SEd Tanous 
1350f5ffd806SEd Tanous     if (activeDirectoryObject)
1351f5ffd806SEd Tanous     {
13521ef4c342SEd Tanous         handleLDAPPatch(*activeDirectoryObject, asyncResp, "ActiveDirectory");
1353f5ffd806SEd Tanous     }
1354f5ffd806SEd Tanous 
1355f5ffd806SEd Tanous     if (unlockTimeout)
1356f5ffd806SEd Tanous     {
1357d02aad39SEd Tanous         setDbusProperty(
1358d02aad39SEd Tanous             asyncResp, "xyz.openbmc_project.User.Manager",
1359d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
13609ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy", "AccountUnlockTimeout",
1361d02aad39SEd Tanous             "AccountLockoutDuration", *unlockTimeout);
1362f5ffd806SEd Tanous     }
1363f5ffd806SEd Tanous     if (lockoutThreshold)
1364f5ffd806SEd Tanous     {
1365d02aad39SEd Tanous         setDbusProperty(
1366d02aad39SEd Tanous             asyncResp, "xyz.openbmc_project.User.Manager",
1367d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
13689ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy",
1369d02aad39SEd Tanous             "MaxLoginAttemptBeforeLockout", "AccountLockoutThreshold",
1370d02aad39SEd Tanous             *lockoutThreshold);
1371f5ffd806SEd Tanous     }
13721ef4c342SEd Tanous }
1373f5ffd806SEd Tanous 
13744c7d4d33SEd Tanous inline void handleAccountCollectionHead(
13751ef4c342SEd Tanous     App& app, const crow::Request& req,
13761ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
13771ef4c342SEd Tanous {
13783ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
137945ca1b86SEd Tanous     {
138045ca1b86SEd Tanous         return;
138145ca1b86SEd Tanous     }
13824c7d4d33SEd Tanous     asyncResp->res.addHeader(
13834c7d4d33SEd Tanous         boost::beast::http::field::link,
13844c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/ManagerAccountCollection.json>; rel=describedby");
13854c7d4d33SEd Tanous }
13864c7d4d33SEd Tanous 
13874c7d4d33SEd Tanous inline void handleAccountCollectionGet(
13884c7d4d33SEd Tanous     App& app, const crow::Request& req,
13894c7d4d33SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
13904c7d4d33SEd Tanous {
1391afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1392afd369c6SJiaqing Zhao     {
1393afd369c6SJiaqing Zhao         return;
1394afd369c6SJiaqing Zhao     }
13953e72c202SNinad Palsule 
13963e72c202SNinad Palsule     if (req.session == nullptr)
13973e72c202SNinad Palsule     {
13983e72c202SNinad Palsule         messages::internalError(asyncResp->res);
13993e72c202SNinad Palsule         return;
14003e72c202SNinad Palsule     }
14013e72c202SNinad Palsule 
1402afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1403afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1404afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/ManagerAccountCollection.json>; rel=describedby");
14051476687dSEd Tanous 
14061476687dSEd Tanous     asyncResp->res.jsonValue["@odata.id"] =
14071476687dSEd Tanous         "/redfish/v1/AccountService/Accounts";
14081ef4c342SEd Tanous     asyncResp->res.jsonValue["@odata.type"] = "#ManagerAccountCollection."
14091476687dSEd Tanous                                               "ManagerAccountCollection";
14101476687dSEd Tanous     asyncResp->res.jsonValue["Name"] = "Accounts Collection";
14111476687dSEd Tanous     asyncResp->res.jsonValue["Description"] = "BMC User Accounts";
14120f74e643SEd Tanous 
14136c51eab1SEd Tanous     Privileges effectiveUserPrivileges =
14143e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
14156c51eab1SEd Tanous 
1416f5e29f33SJunLin Chen     std::string thisUser;
1417f5e29f33SJunLin Chen     if (req.session)
1418f5e29f33SJunLin Chen     {
1419f5e29f33SJunLin Chen         thisUser = req.session->username;
1420f5e29f33SJunLin Chen     }
14215eb468daSGeorge Liu     sdbusplus::message::object_path path("/xyz/openbmc_project/user");
14225eb468daSGeorge Liu     dbus::utility::getManagedObjects(
14235eb468daSGeorge Liu         "xyz.openbmc_project.User.Manager", path,
1424cef1ddfbSEd Tanous         [asyncResp, thisUser, effectiveUserPrivileges](
14255e7e2dc5SEd Tanous             const boost::system::error_code& ec,
1426711ac7a9SEd Tanous             const dbus::utility::ManagedObjectType& users) {
1427b9b2e0b2SEd Tanous         if (ec)
1428b9b2e0b2SEd Tanous         {
1429f12894f8SJason M. Bills             messages::internalError(asyncResp->res);
1430b9b2e0b2SEd Tanous             return;
1431b9b2e0b2SEd Tanous         }
1432b9b2e0b2SEd Tanous 
1433cef1ddfbSEd Tanous         bool userCanSeeAllAccounts =
1434002d39b4SEd Tanous             effectiveUserPrivileges.isSupersetOf({"ConfigureUsers"});
1435cef1ddfbSEd Tanous 
1436cef1ddfbSEd Tanous         bool userCanSeeSelf =
1437002d39b4SEd Tanous             effectiveUserPrivileges.isSupersetOf({"ConfigureSelf"});
1438cef1ddfbSEd Tanous 
1439002d39b4SEd Tanous         nlohmann::json& memberArray = asyncResp->res.jsonValue["Members"];
1440b9b2e0b2SEd Tanous         memberArray = nlohmann::json::array();
1441b9b2e0b2SEd Tanous 
14429eb808c1SEd Tanous         for (const auto& userpath : users)
1443b9b2e0b2SEd Tanous         {
14442dfd18efSEd Tanous             std::string user = userpath.first.filename();
14452dfd18efSEd Tanous             if (user.empty())
1446b9b2e0b2SEd Tanous             {
14472dfd18efSEd Tanous                 messages::internalError(asyncResp->res);
144862598e31SEd Tanous                 BMCWEB_LOG_ERROR("Invalid firmware ID");
14492dfd18efSEd Tanous 
14502dfd18efSEd Tanous                 return;
1451b9b2e0b2SEd Tanous             }
1452f365910cSGunnar Mills 
1453f365910cSGunnar Mills             // As clarified by Redfish here:
1454f365910cSGunnar Mills             // https://redfishforum.com/thread/281/manageraccountcollection-change-allows-account-enumeration
14556c51eab1SEd Tanous             // Users without ConfigureUsers, only see their own
14566c51eab1SEd Tanous             // account. Users with ConfigureUsers, see all
14576c51eab1SEd Tanous             // accounts.
14581ef4c342SEd Tanous             if (userCanSeeAllAccounts || (thisUser == user && userCanSeeSelf))
1459f365910cSGunnar Mills             {
14601476687dSEd Tanous                 nlohmann::json::object_t member;
14613b32780dSEd Tanous                 member["@odata.id"] = boost::urls::format(
14623b32780dSEd Tanous                     "/redfish/v1/AccountService/Accounts/{}", user);
1463b2ba3072SPatrick Williams                 memberArray.emplace_back(std::move(member));
1464b9b2e0b2SEd Tanous             }
1465f365910cSGunnar Mills         }
14661ef4c342SEd Tanous         asyncResp->res.jsonValue["Members@odata.count"] = memberArray.size();
14675eb468daSGeorge Liu     });
14681ef4c342SEd Tanous }
14696c51eab1SEd Tanous 
147097e90da3SNinad Palsule inline void processAfterCreateUser(
147197e90da3SNinad Palsule     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
147297e90da3SNinad Palsule     const std::string& username, const std::string& password,
147397e90da3SNinad Palsule     const boost::system::error_code& ec, sdbusplus::message_t& m)
147497e90da3SNinad Palsule {
147597e90da3SNinad Palsule     if (ec)
147697e90da3SNinad Palsule     {
147797e90da3SNinad Palsule         userErrorMessageHandler(m.get_error(), asyncResp, username, "");
147897e90da3SNinad Palsule         return;
147997e90da3SNinad Palsule     }
148097e90da3SNinad Palsule 
148197e90da3SNinad Palsule     if (pamUpdatePassword(username, password) != PAM_SUCCESS)
148297e90da3SNinad Palsule     {
148397e90da3SNinad Palsule         // At this point we have a user that's been
148497e90da3SNinad Palsule         // created, but the password set
148597e90da3SNinad Palsule         // failed.Something is wrong, so delete the user
148697e90da3SNinad Palsule         // that we've already created
148797e90da3SNinad Palsule         sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
148897e90da3SNinad Palsule         tempObjPath /= username;
148997e90da3SNinad Palsule         const std::string userPath(tempObjPath);
149097e90da3SNinad Palsule 
149197e90da3SNinad Palsule         crow::connections::systemBus->async_method_call(
149297e90da3SNinad Palsule             [asyncResp, password](const boost::system::error_code& ec3) {
149397e90da3SNinad Palsule             if (ec3)
149497e90da3SNinad Palsule             {
149597e90da3SNinad Palsule                 messages::internalError(asyncResp->res);
149697e90da3SNinad Palsule                 return;
149797e90da3SNinad Palsule             }
149897e90da3SNinad Palsule 
149997e90da3SNinad Palsule             // If password is invalid
15009bd80831SJason M. Bills             messages::propertyValueFormatError(asyncResp->res, nullptr,
150197e90da3SNinad Palsule                                                "Password");
150297e90da3SNinad Palsule         },
150397e90da3SNinad Palsule             "xyz.openbmc_project.User.Manager", userPath,
150497e90da3SNinad Palsule             "xyz.openbmc_project.Object.Delete", "Delete");
150597e90da3SNinad Palsule 
150662598e31SEd Tanous         BMCWEB_LOG_ERROR("pamUpdatePassword Failed");
150797e90da3SNinad Palsule         return;
150897e90da3SNinad Palsule     }
150997e90da3SNinad Palsule 
151097e90da3SNinad Palsule     messages::created(asyncResp->res);
151197e90da3SNinad Palsule     asyncResp->res.addHeader("Location",
151297e90da3SNinad Palsule                              "/redfish/v1/AccountService/Accounts/" + username);
151397e90da3SNinad Palsule }
151497e90da3SNinad Palsule 
151597e90da3SNinad Palsule inline void processAfterGetAllGroups(
151697e90da3SNinad Palsule     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
151797e90da3SNinad Palsule     const std::string& username, const std::string& password,
1518e01d0c36SEd Tanous     const std::string& roleId, bool enabled,
15199ba73934SNinad Palsule     std::optional<std::vector<std::string>> accountTypes,
152097e90da3SNinad Palsule     const std::vector<std::string>& allGroupsList)
152197e90da3SNinad Palsule {
15223e72c202SNinad Palsule     std::vector<std::string> userGroups;
15239ba73934SNinad Palsule     std::vector<std::string> accountTypeUserGroups;
15249ba73934SNinad Palsule 
15259ba73934SNinad Palsule     // If user specified account types then convert them to unix user groups
15269ba73934SNinad Palsule     if (accountTypes)
15279ba73934SNinad Palsule     {
15289ba73934SNinad Palsule         if (!getUserGroupFromAccountType(asyncResp->res, *accountTypes,
15299ba73934SNinad Palsule                                          accountTypeUserGroups))
15309ba73934SNinad Palsule         {
15319ba73934SNinad Palsule             // Problem in mapping Account Types to User Groups, Error already
15329ba73934SNinad Palsule             // logged.
15339ba73934SNinad Palsule             return;
15349ba73934SNinad Palsule         }
15359ba73934SNinad Palsule     }
15369ba73934SNinad Palsule 
15373e72c202SNinad Palsule     for (const auto& grp : allGroupsList)
15383e72c202SNinad Palsule     {
15399ba73934SNinad Palsule         // If user specified the account type then only accept groups which are
15409ba73934SNinad Palsule         // in the account types group list.
15419ba73934SNinad Palsule         if (!accountTypeUserGroups.empty())
15429ba73934SNinad Palsule         {
15439ba73934SNinad Palsule             bool found = false;
15449ba73934SNinad Palsule             for (const auto& grp1 : accountTypeUserGroups)
15459ba73934SNinad Palsule             {
15469ba73934SNinad Palsule                 if (grp == grp1)
15479ba73934SNinad Palsule                 {
15489ba73934SNinad Palsule                     found = true;
15499ba73934SNinad Palsule                     break;
15509ba73934SNinad Palsule                 }
15519ba73934SNinad Palsule             }
15529ba73934SNinad Palsule             if (!found)
15539ba73934SNinad Palsule             {
15549ba73934SNinad Palsule                 continue;
15559ba73934SNinad Palsule             }
15569ba73934SNinad Palsule         }
15579ba73934SNinad Palsule 
15583e72c202SNinad Palsule         // Console access is provided to the user who is a member of
15593e72c202SNinad Palsule         // hostconsole group and has a administrator role. So, set
15603e72c202SNinad Palsule         // hostconsole group only for the administrator.
15619ba73934SNinad Palsule         if ((grp == "hostconsole") && (roleId != "priv-admin"))
15623e72c202SNinad Palsule         {
15639ba73934SNinad Palsule             if (!accountTypeUserGroups.empty())
15649ba73934SNinad Palsule             {
156562598e31SEd Tanous                 BMCWEB_LOG_ERROR(
156662598e31SEd Tanous                     "Only administrator can get HostConsole access");
15679ba73934SNinad Palsule                 asyncResp->res.result(boost::beast::http::status::bad_request);
15689ba73934SNinad Palsule                 return;
15699ba73934SNinad Palsule             }
15709ba73934SNinad Palsule             continue;
15719ba73934SNinad Palsule         }
15723e72c202SNinad Palsule         userGroups.emplace_back(grp);
15733e72c202SNinad Palsule     }
15749ba73934SNinad Palsule 
15759ba73934SNinad Palsule     // Make sure user specified groups are valid. This is internal error because
15769ba73934SNinad Palsule     // it some inconsistencies between user manager and bmcweb.
15779ba73934SNinad Palsule     if (!accountTypeUserGroups.empty() &&
15789ba73934SNinad Palsule         accountTypeUserGroups.size() != userGroups.size())
15799ba73934SNinad Palsule     {
15809ba73934SNinad Palsule         messages::internalError(asyncResp->res);
15819ba73934SNinad Palsule         return;
15823e72c202SNinad Palsule     }
158397e90da3SNinad Palsule     crow::connections::systemBus->async_method_call(
158497e90da3SNinad Palsule         [asyncResp, username, password](const boost::system::error_code& ec2,
158597e90da3SNinad Palsule                                         sdbusplus::message_t& m) {
158697e90da3SNinad Palsule         processAfterCreateUser(asyncResp, username, password, ec2, m);
158797e90da3SNinad Palsule     },
158897e90da3SNinad Palsule         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
15893e72c202SNinad Palsule         "xyz.openbmc_project.User.Manager", "CreateUser", username, userGroups,
1590e01d0c36SEd Tanous         roleId, enabled);
159197e90da3SNinad Palsule }
159297e90da3SNinad Palsule 
15931ef4c342SEd Tanous inline void handleAccountCollectionPost(
15941ef4c342SEd Tanous     App& app, const crow::Request& req,
15951ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
15961ef4c342SEd Tanous {
15973ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
159845ca1b86SEd Tanous     {
159945ca1b86SEd Tanous         return;
160045ca1b86SEd Tanous     }
16019712f8acSEd Tanous     std::string username;
16029712f8acSEd Tanous     std::string password;
1603e01d0c36SEd Tanous     std::optional<std::string> roleIdJson;
1604e01d0c36SEd Tanous     std::optional<bool> enabledJson;
16059ba73934SNinad Palsule     std::optional<std::vector<std::string>> accountTypes;
1606e01d0c36SEd Tanous     if (!json_util::readJsonPatch(req, asyncResp->res, "UserName", username,
1607e01d0c36SEd Tanous                                   "Password", password, "RoleId", roleIdJson,
1608e01d0c36SEd Tanous                                   "Enabled", enabledJson, "AccountTypes",
1609e01d0c36SEd Tanous                                   accountTypes))
161004ae99ecSEd Tanous     {
161104ae99ecSEd Tanous         return;
161204ae99ecSEd Tanous     }
161304ae99ecSEd Tanous 
1614e01d0c36SEd Tanous     std::string roleId = roleIdJson.value_or("User");
1615e01d0c36SEd Tanous     std::string priv = getPrivilegeFromRoleId(roleId);
161684e12cb7SAppaRao Puli     if (priv.empty())
161704ae99ecSEd Tanous     {
1618e01d0c36SEd Tanous         messages::propertyValueNotInList(asyncResp->res, roleId, "RoleId");
161904ae99ecSEd Tanous         return;
162004ae99ecSEd Tanous     }
16219712f8acSEd Tanous     roleId = priv;
162204ae99ecSEd Tanous 
1623e01d0c36SEd Tanous     bool enabled = enabledJson.value_or(true);
1624e01d0c36SEd Tanous 
1625599c71d8SAyushi Smriti     // Reading AllGroups property
16261e1e598dSJonathan Doman     sdbusplus::asio::getProperty<std::vector<std::string>>(
16271ef4c342SEd Tanous         *crow::connections::systemBus, "xyz.openbmc_project.User.Manager",
16281ef4c342SEd Tanous         "/xyz/openbmc_project/user", "xyz.openbmc_project.User.Manager",
16291ef4c342SEd Tanous         "AllGroups",
16309ba73934SNinad Palsule         [asyncResp, username, password{std::move(password)}, roleId, enabled,
16319ba73934SNinad Palsule          accountTypes](const boost::system::error_code& ec,
16321e1e598dSJonathan Doman                        const std::vector<std::string>& allGroupsList) {
1633599c71d8SAyushi Smriti         if (ec)
1634599c71d8SAyushi Smriti         {
163562598e31SEd Tanous             BMCWEB_LOG_DEBUG("ERROR with async_method_call");
1636599c71d8SAyushi Smriti             messages::internalError(asyncResp->res);
1637599c71d8SAyushi Smriti             return;
1638599c71d8SAyushi Smriti         }
1639599c71d8SAyushi Smriti 
16401e1e598dSJonathan Doman         if (allGroupsList.empty())
1641599c71d8SAyushi Smriti         {
1642599c71d8SAyushi Smriti             messages::internalError(asyncResp->res);
1643599c71d8SAyushi Smriti             return;
1644599c71d8SAyushi Smriti         }
1645599c71d8SAyushi Smriti 
164697e90da3SNinad Palsule         processAfterGetAllGroups(asyncResp, username, password, roleId, enabled,
16479ba73934SNinad Palsule                                  accountTypes, allGroupsList);
16481e1e598dSJonathan Doman     });
16491ef4c342SEd Tanous }
1650b9b2e0b2SEd Tanous 
16511ef4c342SEd Tanous inline void
16524c7d4d33SEd Tanous     handleAccountHead(App& app, const crow::Request& req,
16536c51eab1SEd Tanous                       const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
16544c7d4d33SEd Tanous                       const std::string& /*accountName*/)
16551ef4c342SEd Tanous {
16563ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
165745ca1b86SEd Tanous     {
165845ca1b86SEd Tanous         return;
165945ca1b86SEd Tanous     }
16604c7d4d33SEd Tanous     asyncResp->res.addHeader(
16614c7d4d33SEd Tanous         boost::beast::http::field::link,
16624c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/ManagerAccount/ManagerAccount.json>; rel=describedby");
16634c7d4d33SEd Tanous }
1664afd369c6SJiaqing Zhao 
16654c7d4d33SEd Tanous inline void
16664c7d4d33SEd Tanous     handleAccountGet(App& app, const crow::Request& req,
16674c7d4d33SEd Tanous                      const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
16684c7d4d33SEd Tanous                      const std::string& accountName)
16694c7d4d33SEd Tanous {
1670afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1671afd369c6SJiaqing Zhao     {
1672afd369c6SJiaqing Zhao         return;
1673afd369c6SJiaqing Zhao     }
1674afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1675afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1676afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/ManagerAccount/ManagerAccount.json>; rel=describedby");
1677afd369c6SJiaqing Zhao 
16781ef4c342SEd Tanous #ifdef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
1679031514fbSJunLin Chen     // If authentication is disabled, there are no user accounts
1680d8a5d5d8SJiaqing Zhao     messages::resourceNotFound(asyncResp->res, "ManagerAccount", accountName);
1681031514fbSJunLin Chen     return;
16821ef4c342SEd Tanous #endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
1683afd369c6SJiaqing Zhao 
1684031514fbSJunLin Chen     if (req.session == nullptr)
1685031514fbSJunLin Chen     {
1686031514fbSJunLin Chen         messages::internalError(asyncResp->res);
1687031514fbSJunLin Chen         return;
1688031514fbSJunLin Chen     }
16896c51eab1SEd Tanous     if (req.session->username != accountName)
1690b9b2e0b2SEd Tanous     {
16916c51eab1SEd Tanous         // At this point we've determined that the user is trying to
16921ef4c342SEd Tanous         // modify a user that isn't them.  We need to verify that they
16931ef4c342SEd Tanous         // have permissions to modify other users, so re-run the auth
16941ef4c342SEd Tanous         // check with the same permissions, minus ConfigureSelf.
16956c51eab1SEd Tanous         Privileges effectiveUserPrivileges =
16963e72c202SNinad Palsule             redfish::getUserPrivileges(*req.session);
16971ef4c342SEd Tanous         Privileges requiredPermissionsToChangeNonSelf = {"ConfigureUsers",
16981ef4c342SEd Tanous                                                          "ConfigureManager"};
16996c51eab1SEd Tanous         if (!effectiveUserPrivileges.isSupersetOf(
17006c51eab1SEd Tanous                 requiredPermissionsToChangeNonSelf))
1701900f9497SJoseph Reynolds         {
170262598e31SEd Tanous             BMCWEB_LOG_DEBUG("GET Account denied access");
1703900f9497SJoseph Reynolds             messages::insufficientPrivilege(asyncResp->res);
1704900f9497SJoseph Reynolds             return;
1705900f9497SJoseph Reynolds         }
1706900f9497SJoseph Reynolds     }
1707900f9497SJoseph Reynolds 
17085eb468daSGeorge Liu     sdbusplus::message::object_path path("/xyz/openbmc_project/user");
17095eb468daSGeorge Liu     dbus::utility::getManagedObjects(
17105eb468daSGeorge Liu         "xyz.openbmc_project.User.Manager", path,
17111ef4c342SEd Tanous         [asyncResp,
17125e7e2dc5SEd Tanous          accountName](const boost::system::error_code& ec,
1713711ac7a9SEd Tanous                       const dbus::utility::ManagedObjectType& users) {
1714b9b2e0b2SEd Tanous         if (ec)
1715b9b2e0b2SEd Tanous         {
1716f12894f8SJason M. Bills             messages::internalError(asyncResp->res);
1717b9b2e0b2SEd Tanous             return;
1718b9b2e0b2SEd Tanous         }
17193544d2a7SEd Tanous         const auto userIt = std::ranges::find_if(
172080f79a40SMichael Shen             users,
172180f79a40SMichael Shen             [accountName](
1722b477fd44SP Dheeraj Srujan Kumar                 const std::pair<sdbusplus::message::object_path,
172380f79a40SMichael Shen                                 dbus::utility::DBusInterfacesMap>& user) {
172455f79e6fSEd Tanous             return accountName == user.first.filename();
1725b477fd44SP Dheeraj Srujan Kumar         });
1726b9b2e0b2SEd Tanous 
172784e12cb7SAppaRao Puli         if (userIt == users.end())
1728b9b2e0b2SEd Tanous         {
1729002d39b4SEd Tanous             messages::resourceNotFound(asyncResp->res, "ManagerAccount",
1730002d39b4SEd Tanous                                        accountName);
173184e12cb7SAppaRao Puli             return;
173284e12cb7SAppaRao Puli         }
17334e68c45bSAyushi Smriti 
17341476687dSEd Tanous         asyncResp->res.jsonValue["@odata.type"] =
173558345856SAbhishek Patel             "#ManagerAccount.v1_7_0.ManagerAccount";
17361476687dSEd Tanous         asyncResp->res.jsonValue["Name"] = "User Account";
17371476687dSEd Tanous         asyncResp->res.jsonValue["Description"] = "User Account";
17381476687dSEd Tanous         asyncResp->res.jsonValue["Password"] = nullptr;
173958345856SAbhishek Patel         asyncResp->res.jsonValue["StrictAccountTypes"] = true;
17404e68c45bSAyushi Smriti 
174184e12cb7SAppaRao Puli         for (const auto& interface : userIt->second)
174265b0dc32SEd Tanous         {
1743002d39b4SEd Tanous             if (interface.first == "xyz.openbmc_project.User.Attributes")
174465b0dc32SEd Tanous             {
174565b0dc32SEd Tanous                 for (const auto& property : interface.second)
174665b0dc32SEd Tanous                 {
174765b0dc32SEd Tanous                     if (property.first == "UserEnabled")
174865b0dc32SEd Tanous                     {
174965b0dc32SEd Tanous                         const bool* userEnabled =
1750abf2add6SEd Tanous                             std::get_if<bool>(&property.second);
175165b0dc32SEd Tanous                         if (userEnabled == nullptr)
175265b0dc32SEd Tanous                         {
175362598e31SEd Tanous                             BMCWEB_LOG_ERROR("UserEnabled wasn't a bool");
175484e12cb7SAppaRao Puli                             messages::internalError(asyncResp->res);
175584e12cb7SAppaRao Puli                             return;
175665b0dc32SEd Tanous                         }
1757002d39b4SEd Tanous                         asyncResp->res.jsonValue["Enabled"] = *userEnabled;
175865b0dc32SEd Tanous                     }
1759002d39b4SEd Tanous                     else if (property.first == "UserLockedForFailedAttempt")
176065b0dc32SEd Tanous                     {
176165b0dc32SEd Tanous                         const bool* userLocked =
1762abf2add6SEd Tanous                             std::get_if<bool>(&property.second);
176365b0dc32SEd Tanous                         if (userLocked == nullptr)
176465b0dc32SEd Tanous                         {
176562598e31SEd Tanous                             BMCWEB_LOG_ERROR("UserLockedForF"
176684e12cb7SAppaRao Puli                                              "ailedAttempt "
176762598e31SEd Tanous                                              "wasn't a bool");
176884e12cb7SAppaRao Puli                             messages::internalError(asyncResp->res);
176984e12cb7SAppaRao Puli                             return;
177065b0dc32SEd Tanous                         }
1771002d39b4SEd Tanous                         asyncResp->res.jsonValue["Locked"] = *userLocked;
1772002d39b4SEd Tanous                         asyncResp->res
1773002d39b4SEd Tanous                             .jsonValue["Locked@Redfish.AllowableValues"] = {
17743bf4e632SJoseph Reynolds                             "false"}; // can only unlock accounts
177565b0dc32SEd Tanous                     }
177684e12cb7SAppaRao Puli                     else if (property.first == "UserPrivilege")
177784e12cb7SAppaRao Puli                     {
177854fc587aSNagaraju Goruganti                         const std::string* userPrivPtr =
1779002d39b4SEd Tanous                             std::get_if<std::string>(&property.second);
178054fc587aSNagaraju Goruganti                         if (userPrivPtr == nullptr)
178184e12cb7SAppaRao Puli                         {
178262598e31SEd Tanous                             BMCWEB_LOG_ERROR("UserPrivilege wasn't a "
178362598e31SEd Tanous                                              "string");
178484e12cb7SAppaRao Puli                             messages::internalError(asyncResp->res);
178584e12cb7SAppaRao Puli                             return;
178684e12cb7SAppaRao Puli                         }
17871ef4c342SEd Tanous                         std::string role = getRoleIdFromPrivilege(*userPrivPtr);
178854fc587aSNagaraju Goruganti                         if (role.empty())
178984e12cb7SAppaRao Puli                         {
179062598e31SEd Tanous                             BMCWEB_LOG_ERROR("Invalid user role");
179184e12cb7SAppaRao Puli                             messages::internalError(asyncResp->res);
179284e12cb7SAppaRao Puli                             return;
179384e12cb7SAppaRao Puli                         }
179454fc587aSNagaraju Goruganti                         asyncResp->res.jsonValue["RoleId"] = role;
179584e12cb7SAppaRao Puli 
17961476687dSEd Tanous                         nlohmann::json& roleEntry =
1797002d39b4SEd Tanous                             asyncResp->res.jsonValue["Links"]["Role"];
17983b32780dSEd Tanous                         roleEntry["@odata.id"] = boost::urls::format(
17993b32780dSEd Tanous                             "/redfish/v1/AccountService/Roles/{}", role);
180084e12cb7SAppaRao Puli                     }
1801002d39b4SEd Tanous                     else if (property.first == "UserPasswordExpired")
18023bf4e632SJoseph Reynolds                     {
18033bf4e632SJoseph Reynolds                         const bool* userPasswordExpired =
18043bf4e632SJoseph Reynolds                             std::get_if<bool>(&property.second);
18053bf4e632SJoseph Reynolds                         if (userPasswordExpired == nullptr)
18063bf4e632SJoseph Reynolds                         {
180762598e31SEd Tanous                             BMCWEB_LOG_ERROR(
180862598e31SEd Tanous                                 "UserPasswordExpired wasn't a bool");
18093bf4e632SJoseph Reynolds                             messages::internalError(asyncResp->res);
18103bf4e632SJoseph Reynolds                             return;
18113bf4e632SJoseph Reynolds                         }
1812002d39b4SEd Tanous                         asyncResp->res.jsonValue["PasswordChangeRequired"] =
18133bf4e632SJoseph Reynolds                             *userPasswordExpired;
18143bf4e632SJoseph Reynolds                     }
1815c7229815SAbhishek Patel                     else if (property.first == "UserGroups")
1816c7229815SAbhishek Patel                     {
1817c7229815SAbhishek Patel                         const std::vector<std::string>* userGroups =
1818c7229815SAbhishek Patel                             std::get_if<std::vector<std::string>>(
1819c7229815SAbhishek Patel                                 &property.second);
1820c7229815SAbhishek Patel                         if (userGroups == nullptr)
1821c7229815SAbhishek Patel                         {
182262598e31SEd Tanous                             BMCWEB_LOG_ERROR(
182362598e31SEd Tanous                                 "userGroups wasn't a string vector");
1824c7229815SAbhishek Patel                             messages::internalError(asyncResp->res);
1825c7229815SAbhishek Patel                             return;
1826c7229815SAbhishek Patel                         }
1827c7229815SAbhishek Patel                         if (!translateUserGroup(*userGroups, asyncResp->res))
1828c7229815SAbhishek Patel                         {
182962598e31SEd Tanous                             BMCWEB_LOG_ERROR("userGroups mapping failed");
1830c7229815SAbhishek Patel                             messages::internalError(asyncResp->res);
1831c7229815SAbhishek Patel                             return;
1832c7229815SAbhishek Patel                         }
1833c7229815SAbhishek Patel                     }
183465b0dc32SEd Tanous                 }
183565b0dc32SEd Tanous             }
183665b0dc32SEd Tanous         }
183765b0dc32SEd Tanous 
18383b32780dSEd Tanous         asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
18393b32780dSEd Tanous             "/redfish/v1/AccountService/Accounts/{}", accountName);
1840b9b2e0b2SEd Tanous         asyncResp->res.jsonValue["Id"] = accountName;
1841b9b2e0b2SEd Tanous         asyncResp->res.jsonValue["UserName"] = accountName;
18425eb468daSGeorge Liu     });
18431ef4c342SEd Tanous }
1844a840879dSEd Tanous 
18451ef4c342SEd Tanous inline void
184620fc307fSGunnar Mills     handleAccountDelete(App& app, const crow::Request& req,
18476c51eab1SEd Tanous                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
18481ef4c342SEd Tanous                         const std::string& username)
18491ef4c342SEd Tanous {
18503ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
185145ca1b86SEd Tanous     {
185245ca1b86SEd Tanous         return;
185345ca1b86SEd Tanous     }
18541ef4c342SEd Tanous 
18551ef4c342SEd Tanous #ifdef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
1856031514fbSJunLin Chen     // If authentication is disabled, there are no user accounts
1857d8a5d5d8SJiaqing Zhao     messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
1858031514fbSJunLin Chen     return;
1859031514fbSJunLin Chen 
18601ef4c342SEd Tanous #endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
18611ef4c342SEd Tanous     sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
18621ef4c342SEd Tanous     tempObjPath /= username;
18631ef4c342SEd Tanous     const std::string userPath(tempObjPath);
18641ef4c342SEd Tanous 
18651ef4c342SEd Tanous     crow::connections::systemBus->async_method_call(
18665e7e2dc5SEd Tanous         [asyncResp, username](const boost::system::error_code& ec) {
18671ef4c342SEd Tanous         if (ec)
18681ef4c342SEd Tanous         {
1869d8a5d5d8SJiaqing Zhao             messages::resourceNotFound(asyncResp->res, "ManagerAccount",
18701ef4c342SEd Tanous                                        username);
18711ef4c342SEd Tanous             return;
18721ef4c342SEd Tanous         }
18731ef4c342SEd Tanous 
18741ef4c342SEd Tanous         messages::accountRemoved(asyncResp->res);
18751ef4c342SEd Tanous     },
18761ef4c342SEd Tanous         "xyz.openbmc_project.User.Manager", userPath,
18771ef4c342SEd Tanous         "xyz.openbmc_project.Object.Delete", "Delete");
18781ef4c342SEd Tanous }
18791ef4c342SEd Tanous 
18801ef4c342SEd Tanous inline void
18811ef4c342SEd Tanous     handleAccountPatch(App& app, const crow::Request& req,
18821ef4c342SEd Tanous                        const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
18831ef4c342SEd Tanous                        const std::string& username)
18841ef4c342SEd Tanous {
18851ef4c342SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
18861ef4c342SEd Tanous     {
18871ef4c342SEd Tanous         return;
18881ef4c342SEd Tanous     }
18891ef4c342SEd Tanous #ifdef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
18901ef4c342SEd Tanous     // If authentication is disabled, there are no user accounts
1891d8a5d5d8SJiaqing Zhao     messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
18921ef4c342SEd Tanous     return;
18931ef4c342SEd Tanous 
18941ef4c342SEd Tanous #endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
1895a24526dcSEd Tanous     std::optional<std::string> newUserName;
1896a24526dcSEd Tanous     std::optional<std::string> password;
1897a24526dcSEd Tanous     std::optional<bool> enabled;
1898a24526dcSEd Tanous     std::optional<std::string> roleId;
189924c8542dSRatan Gupta     std::optional<bool> locked;
190058345856SAbhishek Patel     std::optional<std::vector<std::string>> accountTypes;
190158345856SAbhishek Patel 
190258345856SAbhishek Patel     bool userSelf = (username == req.session->username);
1903e9cc5172SEd Tanous 
1904031514fbSJunLin Chen     if (req.session == nullptr)
1905031514fbSJunLin Chen     {
1906031514fbSJunLin Chen         messages::internalError(asyncResp->res);
1907031514fbSJunLin Chen         return;
1908031514fbSJunLin Chen     }
1909031514fbSJunLin Chen 
1910e9cc5172SEd Tanous     Privileges effectiveUserPrivileges =
19113e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
1912e9cc5172SEd Tanous     Privileges configureUsers = {"ConfigureUsers"};
1913e9cc5172SEd Tanous     bool userHasConfigureUsers =
1914e9cc5172SEd Tanous         effectiveUserPrivileges.isSupersetOf(configureUsers);
1915e9cc5172SEd Tanous     if (userHasConfigureUsers)
1916e9cc5172SEd Tanous     {
1917e9cc5172SEd Tanous         // Users with ConfigureUsers can modify for all users
191858345856SAbhishek Patel         if (!json_util::readJsonPatch(
191958345856SAbhishek Patel                 req, asyncResp->res, "UserName", newUserName, "Password",
192058345856SAbhishek Patel                 password, "RoleId", roleId, "Enabled", enabled, "Locked",
192158345856SAbhishek Patel                 locked, "AccountTypes", accountTypes))
1922a840879dSEd Tanous         {
1923a840879dSEd Tanous             return;
1924a840879dSEd Tanous         }
1925e9cc5172SEd Tanous     }
1926e9cc5172SEd Tanous     else
1927900f9497SJoseph Reynolds     {
1928e9cc5172SEd Tanous         // ConfigureSelf accounts can only modify their own account
192958345856SAbhishek Patel         if (!userSelf)
1930900f9497SJoseph Reynolds         {
1931900f9497SJoseph Reynolds             messages::insufficientPrivilege(asyncResp->res);
1932900f9497SJoseph Reynolds             return;
1933900f9497SJoseph Reynolds         }
1934031514fbSJunLin Chen 
1935e9cc5172SEd Tanous         // ConfigureSelf accounts can only modify their password
19361ef4c342SEd Tanous         if (!json_util::readJsonPatch(req, asyncResp->res, "Password",
19371ef4c342SEd Tanous                                       password))
1938e9cc5172SEd Tanous         {
1939e9cc5172SEd Tanous             return;
1940e9cc5172SEd Tanous         }
1941900f9497SJoseph Reynolds     }
1942900f9497SJoseph Reynolds 
194366b5ca76Sjayaprakash Mutyala     // if user name is not provided in the patch method or if it
19446c51eab1SEd Tanous     // matches the user name in the URI, then we are treating it as
19456c51eab1SEd Tanous     // updating user properties other then username. If username
19466c51eab1SEd Tanous     // provided doesn't match the URI, then we are treating this as
19476c51eab1SEd Tanous     // user rename request.
194866b5ca76Sjayaprakash Mutyala     if (!newUserName || (newUserName.value() == username))
1949a840879dSEd Tanous     {
19501ef4c342SEd Tanous         updateUserProperties(asyncResp, username, password, enabled, roleId,
195158345856SAbhishek Patel                              locked, accountTypes, userSelf);
195284e12cb7SAppaRao Puli         return;
195384e12cb7SAppaRao Puli     }
195484e12cb7SAppaRao Puli     crow::connections::systemBus->async_method_call(
19556c51eab1SEd Tanous         [asyncResp, username, password(std::move(password)),
19561ef4c342SEd Tanous          roleId(std::move(roleId)), enabled, newUser{std::string(*newUserName)},
195758345856SAbhishek Patel          locked, userSelf, accountTypes(std::move(accountTypes))](
1958e81de512SEd Tanous             const boost::system::error_code& ec, sdbusplus::message_t& m) {
195984e12cb7SAppaRao Puli         if (ec)
196084e12cb7SAppaRao Puli         {
1961002d39b4SEd Tanous             userErrorMessageHandler(m.get_error(), asyncResp, newUser,
1962002d39b4SEd Tanous                                     username);
1963a840879dSEd Tanous             return;
1964a840879dSEd Tanous         }
1965a840879dSEd Tanous 
1966002d39b4SEd Tanous         updateUserProperties(asyncResp, newUser, password, enabled, roleId,
196758345856SAbhishek Patel                              locked, accountTypes, userSelf);
196884e12cb7SAppaRao Puli     },
19691ef4c342SEd Tanous         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
197084e12cb7SAppaRao Puli         "xyz.openbmc_project.User.Manager", "RenameUser", username,
197184e12cb7SAppaRao Puli         *newUserName);
19721ef4c342SEd Tanous }
19731ef4c342SEd Tanous 
19741ef4c342SEd Tanous inline void requestAccountServiceRoutes(App& app)
19751ef4c342SEd Tanous {
19761ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
19774c7d4d33SEd Tanous         .privileges(redfish::privileges::headAccountService)
19784c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
19794c7d4d33SEd Tanous             std::bind_front(handleAccountServiceHead, std::ref(app)));
19804c7d4d33SEd Tanous 
19814c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
19821ef4c342SEd Tanous         .privileges(redfish::privileges::getAccountService)
19831ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
19841ef4c342SEd Tanous             std::bind_front(handleAccountServiceGet, std::ref(app)));
19851ef4c342SEd Tanous 
19861ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
19871ef4c342SEd Tanous         .privileges(redfish::privileges::patchAccountService)
19881ef4c342SEd Tanous         .methods(boost::beast::http::verb::patch)(
19891ef4c342SEd Tanous             std::bind_front(handleAccountServicePatch, std::ref(app)));
19901ef4c342SEd Tanous 
19911ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
19924c7d4d33SEd Tanous         .privileges(redfish::privileges::headManagerAccountCollection)
19934c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
19944c7d4d33SEd Tanous             std::bind_front(handleAccountCollectionHead, std::ref(app)));
19954c7d4d33SEd Tanous 
19964c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
19971ef4c342SEd Tanous         .privileges(redfish::privileges::getManagerAccountCollection)
19981ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
19991ef4c342SEd Tanous             std::bind_front(handleAccountCollectionGet, std::ref(app)));
20001ef4c342SEd Tanous 
20011ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
20021ef4c342SEd Tanous         .privileges(redfish::privileges::postManagerAccountCollection)
20031ef4c342SEd Tanous         .methods(boost::beast::http::verb::post)(
20041ef4c342SEd Tanous             std::bind_front(handleAccountCollectionPost, std::ref(app)));
20051ef4c342SEd Tanous 
20061ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
20074c7d4d33SEd Tanous         .privileges(redfish::privileges::headManagerAccount)
20084c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
20094c7d4d33SEd Tanous             std::bind_front(handleAccountHead, std::ref(app)));
20104c7d4d33SEd Tanous 
20114c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
20121ef4c342SEd Tanous         .privileges(redfish::privileges::getManagerAccount)
20131ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
20141ef4c342SEd Tanous             std::bind_front(handleAccountGet, std::ref(app)));
20151ef4c342SEd Tanous 
20161ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
20171ef4c342SEd Tanous         // TODO this privilege should be using the generated endpoints, but
20181ef4c342SEd Tanous         // because of the special handling of ConfigureSelf, it's not able to
20191ef4c342SEd Tanous         // yet
20201ef4c342SEd Tanous         .privileges({{"ConfigureUsers"}, {"ConfigureSelf"}})
20211ef4c342SEd Tanous         .methods(boost::beast::http::verb::patch)(
20221ef4c342SEd Tanous             std::bind_front(handleAccountPatch, std::ref(app)));
202384e12cb7SAppaRao Puli 
20246c51eab1SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
2025ed398213SEd Tanous         .privileges(redfish::privileges::deleteManagerAccount)
20266c51eab1SEd Tanous         .methods(boost::beast::http::verb::delete_)(
202720fc307fSGunnar Mills             std::bind_front(handleAccountDelete, std::ref(app)));
202806e086d9SEd Tanous }
202988d16c9aSLewanczyk, Dawid 
203088d16c9aSLewanczyk, Dawid } // namespace redfish
2031