xref: /openbmc/bmcweb/features/redfish/lib/account_service.hpp (revision bd79bce8c3f1deb1fb2773868b9ece25233cf27b)
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"
191aa375b8SEd Tanous #include "certificate_service.hpp"
203ccb3adbSEd Tanous #include "dbus_utility.hpp"
213ccb3adbSEd Tanous #include "error_messages.hpp"
220ec8b83dSEd Tanous #include "generated/enums/account_service.hpp"
233ccb3adbSEd Tanous #include "persistent_data.hpp"
243ccb3adbSEd Tanous #include "query.hpp"
250ec8b83dSEd Tanous #include "registries/privilege_registry.hpp"
263281bcf1SEd Tanous #include "sessions.hpp"
271aa375b8SEd Tanous #include "utils/collection.hpp"
283ccb3adbSEd Tanous #include "utils/dbus_utils.hpp"
293ccb3adbSEd Tanous #include "utils/json_utils.hpp"
300ec8b83dSEd Tanous 
311aa375b8SEd Tanous #include <boost/url/format.hpp>
321aa375b8SEd Tanous #include <boost/url/url.hpp>
331e1e598dSJonathan Doman #include <sdbusplus/asio/property.hpp>
34d1bde9e5SKrzysztof Grobelny #include <sdbusplus/unpack_properties.hpp>
351214b7e7SGunnar Mills 
362b73119cSGeorge Liu #include <array>
371aa375b8SEd Tanous #include <memory>
38c7229815SAbhishek Patel #include <optional>
393544d2a7SEd Tanous #include <ranges>
40c7229815SAbhishek Patel #include <string>
412b73119cSGeorge Liu #include <string_view>
4220fa6a2cSEd Tanous #include <utility>
43c7229815SAbhishek Patel #include <vector>
44c7229815SAbhishek Patel 
451abe55efSEd Tanous namespace redfish
461abe55efSEd Tanous {
4788d16c9aSLewanczyk, Dawid 
4823a21a1cSEd Tanous constexpr const char* ldapConfigObjectName =
496973a582SRatan Gupta     "/xyz/openbmc_project/user/ldap/openldap";
502c70f800SEd Tanous constexpr const char* adConfigObject =
51ab828d7cSRatan Gupta     "/xyz/openbmc_project/user/ldap/active_directory";
52ab828d7cSRatan Gupta 
53b477fd44SP Dheeraj Srujan Kumar constexpr const char* rootUserDbusPath = "/xyz/openbmc_project/user/";
546973a582SRatan Gupta constexpr const char* ldapRootObject = "/xyz/openbmc_project/user/ldap";
556973a582SRatan Gupta constexpr const char* ldapDbusService = "xyz.openbmc_project.Ldap.Config";
566973a582SRatan Gupta constexpr const char* ldapConfigInterface =
576973a582SRatan Gupta     "xyz.openbmc_project.User.Ldap.Config";
586973a582SRatan Gupta constexpr const char* ldapCreateInterface =
596973a582SRatan Gupta     "xyz.openbmc_project.User.Ldap.Create";
606973a582SRatan Gupta constexpr const char* ldapEnableInterface = "xyz.openbmc_project.Object.Enable";
6106785244SRatan Gupta constexpr const char* ldapPrivMapperInterface =
6206785244SRatan Gupta     "xyz.openbmc_project.User.PrivilegeMapper";
636973a582SRatan Gupta 
6454fc587aSNagaraju Goruganti struct LDAPRoleMapData
6554fc587aSNagaraju Goruganti {
6654fc587aSNagaraju Goruganti     std::string groupName;
6754fc587aSNagaraju Goruganti     std::string privilege;
6854fc587aSNagaraju Goruganti };
6954fc587aSNagaraju Goruganti 
706973a582SRatan Gupta struct LDAPConfigData
716973a582SRatan Gupta {
7247f2934cSEd Tanous     std::string uri;
7347f2934cSEd Tanous     std::string bindDN;
7447f2934cSEd Tanous     std::string baseDN;
7547f2934cSEd Tanous     std::string searchScope;
7647f2934cSEd Tanous     std::string serverType;
776973a582SRatan Gupta     bool serviceEnabled = false;
7847f2934cSEd Tanous     std::string userNameAttribute;
7947f2934cSEd Tanous     std::string groupAttribute;
8054fc587aSNagaraju Goruganti     std::vector<std::pair<std::string, LDAPRoleMapData>> groupRoleList;
816973a582SRatan Gupta };
826973a582SRatan Gupta 
8354fc587aSNagaraju Goruganti inline std::string getRoleIdFromPrivilege(std::string_view role)
8484e12cb7SAppaRao Puli {
8584e12cb7SAppaRao Puli     if (role == "priv-admin")
8684e12cb7SAppaRao Puli     {
8784e12cb7SAppaRao Puli         return "Administrator";
8884e12cb7SAppaRao Puli     }
893174e4dfSEd Tanous     if (role == "priv-user")
9084e12cb7SAppaRao Puli     {
91c80fee55SAppaRao Puli         return "ReadOnly";
9284e12cb7SAppaRao Puli     }
933174e4dfSEd Tanous     if (role == "priv-operator")
9484e12cb7SAppaRao Puli     {
9584e12cb7SAppaRao Puli         return "Operator";
9684e12cb7SAppaRao Puli     }
9784e12cb7SAppaRao Puli     return "";
9884e12cb7SAppaRao Puli }
9954fc587aSNagaraju Goruganti inline std::string getPrivilegeFromRoleId(std::string_view role)
10084e12cb7SAppaRao Puli {
10184e12cb7SAppaRao Puli     if (role == "Administrator")
10284e12cb7SAppaRao Puli     {
10384e12cb7SAppaRao Puli         return "priv-admin";
10484e12cb7SAppaRao Puli     }
1053174e4dfSEd Tanous     if (role == "ReadOnly")
10684e12cb7SAppaRao Puli     {
10784e12cb7SAppaRao Puli         return "priv-user";
10884e12cb7SAppaRao Puli     }
1093174e4dfSEd Tanous     if (role == "Operator")
11084e12cb7SAppaRao Puli     {
11184e12cb7SAppaRao Puli         return "priv-operator";
11284e12cb7SAppaRao Puli     }
11384e12cb7SAppaRao Puli     return "";
11484e12cb7SAppaRao Puli }
115b9b2e0b2SEd Tanous 
116c7229815SAbhishek Patel /**
117c7229815SAbhishek Patel  * @brief Maps user group names retrieved from D-Bus object to
118c7229815SAbhishek Patel  * Account Types.
119c7229815SAbhishek Patel  *
120c7229815SAbhishek Patel  * @param[in] userGroups List of User groups
121c7229815SAbhishek Patel  * @param[out] res AccountTypes populated
122c7229815SAbhishek Patel  *
123c7229815SAbhishek Patel  * @return true in case of success, false if UserGroups contains
124c7229815SAbhishek Patel  * invalid group name(s).
125c7229815SAbhishek Patel  */
126c7229815SAbhishek Patel inline bool translateUserGroup(const std::vector<std::string>& userGroups,
127c7229815SAbhishek Patel                                crow::Response& res)
128c7229815SAbhishek Patel {
129c7229815SAbhishek Patel     std::vector<std::string> accountTypes;
130c7229815SAbhishek Patel     for (const auto& userGroup : userGroups)
131c7229815SAbhishek Patel     {
132c7229815SAbhishek Patel         if (userGroup == "redfish")
133c7229815SAbhishek Patel         {
134c7229815SAbhishek Patel             accountTypes.emplace_back("Redfish");
135c7229815SAbhishek Patel             accountTypes.emplace_back("WebUI");
136c7229815SAbhishek Patel         }
137c7229815SAbhishek Patel         else if (userGroup == "ipmi")
138c7229815SAbhishek Patel         {
139c7229815SAbhishek Patel             accountTypes.emplace_back("IPMI");
140c7229815SAbhishek Patel         }
141c7229815SAbhishek Patel         else if (userGroup == "ssh")
142c7229815SAbhishek Patel         {
143c7229815SAbhishek Patel             accountTypes.emplace_back("ManagerConsole");
144c7229815SAbhishek Patel         }
1453e72c202SNinad Palsule         else if (userGroup == "hostconsole")
1463e72c202SNinad Palsule         {
1473e72c202SNinad Palsule             // The hostconsole group controls who can access the host console
1483e72c202SNinad Palsule             // port via ssh and websocket.
1493e72c202SNinad Palsule             accountTypes.emplace_back("HostConsole");
1503e72c202SNinad Palsule         }
151c7229815SAbhishek Patel         else if (userGroup == "web")
152c7229815SAbhishek Patel         {
153c7229815SAbhishek Patel             // 'web' is one of the valid groups in the UserGroups property of
154c7229815SAbhishek Patel             // the user account in the D-Bus object. This group is currently not
155c7229815SAbhishek Patel             // doing anything, and is considered to be equivalent to 'redfish'.
156c7229815SAbhishek Patel             // 'redfish' user group is mapped to 'Redfish'and 'WebUI'
157c7229815SAbhishek Patel             // AccountTypes, so do nothing here...
158c7229815SAbhishek Patel         }
159c7229815SAbhishek Patel         else
160c7229815SAbhishek Patel         {
1618ece0e45SEd Tanous             // Invalid user group name. Caller throws an exception.
162c7229815SAbhishek Patel             return false;
163c7229815SAbhishek Patel         }
164c7229815SAbhishek Patel     }
165c7229815SAbhishek Patel 
166c7229815SAbhishek Patel     res.jsonValue["AccountTypes"] = std::move(accountTypes);
167c7229815SAbhishek Patel     return true;
168c7229815SAbhishek Patel }
169c7229815SAbhishek Patel 
17058345856SAbhishek Patel /**
17158345856SAbhishek Patel  * @brief Builds User Groups from the Account Types
17258345856SAbhishek Patel  *
17358345856SAbhishek Patel  * @param[in] asyncResp Async Response
17458345856SAbhishek Patel  * @param[in] accountTypes List of Account Types
17558345856SAbhishek Patel  * @param[out] userGroups List of User Groups mapped from Account Types
17658345856SAbhishek Patel  *
17758345856SAbhishek Patel  * @return true if Account Types mapped to User Groups, false otherwise.
17858345856SAbhishek Patel  */
179*bd79bce8SPatrick Williams inline bool getUserGroupFromAccountType(
180*bd79bce8SPatrick Williams     crow::Response& res, const std::vector<std::string>& accountTypes,
18158345856SAbhishek Patel     std::vector<std::string>& userGroups)
18258345856SAbhishek Patel {
18358345856SAbhishek Patel     // Need both Redfish and WebUI Account Types to map to 'redfish' User Group
18458345856SAbhishek Patel     bool redfishType = false;
18558345856SAbhishek Patel     bool webUIType = false;
18658345856SAbhishek Patel 
18758345856SAbhishek Patel     for (const auto& accountType : accountTypes)
18858345856SAbhishek Patel     {
18958345856SAbhishek Patel         if (accountType == "Redfish")
19058345856SAbhishek Patel         {
19158345856SAbhishek Patel             redfishType = true;
19258345856SAbhishek Patel         }
19358345856SAbhishek Patel         else if (accountType == "WebUI")
19458345856SAbhishek Patel         {
19558345856SAbhishek Patel             webUIType = true;
19658345856SAbhishek Patel         }
19758345856SAbhishek Patel         else if (accountType == "IPMI")
19858345856SAbhishek Patel         {
19958345856SAbhishek Patel             userGroups.emplace_back("ipmi");
20058345856SAbhishek Patel         }
20158345856SAbhishek Patel         else if (accountType == "HostConsole")
20258345856SAbhishek Patel         {
20358345856SAbhishek Patel             userGroups.emplace_back("hostconsole");
20458345856SAbhishek Patel         }
20558345856SAbhishek Patel         else if (accountType == "ManagerConsole")
20658345856SAbhishek Patel         {
20758345856SAbhishek Patel             userGroups.emplace_back("ssh");
20858345856SAbhishek Patel         }
20958345856SAbhishek Patel         else
21058345856SAbhishek Patel         {
21158345856SAbhishek Patel             // Invalid Account Type
21258345856SAbhishek Patel             messages::propertyValueNotInList(res, "AccountTypes", accountType);
21358345856SAbhishek Patel             return false;
21458345856SAbhishek Patel         }
21558345856SAbhishek Patel     }
21658345856SAbhishek Patel 
21758345856SAbhishek Patel     // Both  Redfish and WebUI Account Types are needed to PATCH
21858345856SAbhishek Patel     if (redfishType ^ webUIType)
21958345856SAbhishek Patel     {
22062598e31SEd Tanous         BMCWEB_LOG_ERROR(
22162598e31SEd Tanous             "Missing Redfish or WebUI Account Type to set redfish User Group");
22258345856SAbhishek Patel         messages::strictAccountTypes(res, "AccountTypes");
22358345856SAbhishek Patel         return false;
22458345856SAbhishek Patel     }
22558345856SAbhishek Patel 
22658345856SAbhishek Patel     if (redfishType && webUIType)
22758345856SAbhishek Patel     {
22858345856SAbhishek Patel         userGroups.emplace_back("redfish");
22958345856SAbhishek Patel     }
23058345856SAbhishek Patel 
23158345856SAbhishek Patel     return true;
23258345856SAbhishek Patel }
23358345856SAbhishek Patel 
23458345856SAbhishek Patel /**
23558345856SAbhishek Patel  * @brief Sets UserGroups property of the user based on the Account Types
23658345856SAbhishek Patel  *
23758345856SAbhishek Patel  * @param[in] accountTypes List of User Account Types
23858345856SAbhishek Patel  * @param[in] asyncResp Async Response
23958345856SAbhishek Patel  * @param[in] dbusObjectPath D-Bus Object Path
24058345856SAbhishek Patel  * @param[in] userSelf true if User is updating OWN Account Types
24158345856SAbhishek Patel  */
24258345856SAbhishek Patel inline void
24358345856SAbhishek Patel     patchAccountTypes(const std::vector<std::string>& accountTypes,
24458345856SAbhishek Patel                       const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
24558345856SAbhishek Patel                       const std::string& dbusObjectPath, bool userSelf)
24658345856SAbhishek Patel {
24758345856SAbhishek Patel     // Check if User is disabling own Redfish Account Type
24858345856SAbhishek Patel     if (userSelf &&
24958345856SAbhishek Patel         (accountTypes.cend() ==
25058345856SAbhishek Patel          std::find(accountTypes.cbegin(), accountTypes.cend(), "Redfish")))
25158345856SAbhishek Patel     {
25262598e31SEd Tanous         BMCWEB_LOG_ERROR(
25362598e31SEd Tanous             "User disabling OWN Redfish Account Type is not allowed");
25458345856SAbhishek Patel         messages::strictAccountTypes(asyncResp->res, "AccountTypes");
25558345856SAbhishek Patel         return;
25658345856SAbhishek Patel     }
25758345856SAbhishek Patel 
25858345856SAbhishek Patel     std::vector<std::string> updatedUserGroups;
25958345856SAbhishek Patel     if (!getUserGroupFromAccountType(asyncResp->res, accountTypes,
26058345856SAbhishek Patel                                      updatedUserGroups))
26158345856SAbhishek Patel     {
26258345856SAbhishek Patel         // Problem in mapping Account Types to User Groups, Error already
26358345856SAbhishek Patel         // logged.
26458345856SAbhishek Patel         return;
26558345856SAbhishek Patel     }
266e93abac6SGinu George     setDbusProperty(asyncResp, "AccountTypes",
267e93abac6SGinu George                     "xyz.openbmc_project.User.Manager", dbusObjectPath,
268e93abac6SGinu George                     "xyz.openbmc_project.User.Attributes", "UserGroups",
269e93abac6SGinu George                     updatedUserGroups);
27058345856SAbhishek Patel }
27158345856SAbhishek Patel 
2728d1b46d7Szhanghch05 inline void userErrorMessageHandler(
2738d1b46d7Szhanghch05     const sd_bus_error* e, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2748d1b46d7Szhanghch05     const std::string& newUser, const std::string& username)
27566b5ca76Sjayaprakash Mutyala {
27666b5ca76Sjayaprakash Mutyala     if (e == nullptr)
27766b5ca76Sjayaprakash Mutyala     {
27866b5ca76Sjayaprakash Mutyala         messages::internalError(asyncResp->res);
27966b5ca76Sjayaprakash Mutyala         return;
28066b5ca76Sjayaprakash Mutyala     }
28166b5ca76Sjayaprakash Mutyala 
282055806b3SManojkiran Eda     const char* errorMessage = e->name;
28366b5ca76Sjayaprakash Mutyala     if (strcmp(errorMessage,
28466b5ca76Sjayaprakash Mutyala                "xyz.openbmc_project.User.Common.Error.UserNameExists") == 0)
28566b5ca76Sjayaprakash Mutyala     {
286d8a5d5d8SJiaqing Zhao         messages::resourceAlreadyExists(asyncResp->res, "ManagerAccount",
28766b5ca76Sjayaprakash Mutyala                                         "UserName", newUser);
28866b5ca76Sjayaprakash Mutyala     }
28966b5ca76Sjayaprakash Mutyala     else if (strcmp(errorMessage, "xyz.openbmc_project.User.Common.Error."
29066b5ca76Sjayaprakash Mutyala                                   "UserNameDoesNotExist") == 0)
29166b5ca76Sjayaprakash Mutyala     {
292d8a5d5d8SJiaqing Zhao         messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
29366b5ca76Sjayaprakash Mutyala     }
294d4d25793SEd Tanous     else if ((strcmp(errorMessage,
295d4d25793SEd Tanous                      "xyz.openbmc_project.Common.Error.InvalidArgument") ==
296d4d25793SEd Tanous               0) ||
2970fda0f12SGeorge Liu              (strcmp(
2980fda0f12SGeorge Liu                   errorMessage,
2990fda0f12SGeorge Liu                   "xyz.openbmc_project.User.Common.Error.UserNameGroupFail") ==
3000fda0f12SGeorge Liu               0))
30166b5ca76Sjayaprakash Mutyala     {
30266b5ca76Sjayaprakash Mutyala         messages::propertyValueFormatError(asyncResp->res, newUser, "UserName");
30366b5ca76Sjayaprakash Mutyala     }
30466b5ca76Sjayaprakash Mutyala     else if (strcmp(errorMessage,
30566b5ca76Sjayaprakash Mutyala                     "xyz.openbmc_project.User.Common.Error.NoResource") == 0)
30666b5ca76Sjayaprakash Mutyala     {
30766b5ca76Sjayaprakash Mutyala         messages::createLimitReachedForResource(asyncResp->res);
30866b5ca76Sjayaprakash Mutyala     }
30966b5ca76Sjayaprakash Mutyala     else
31066b5ca76Sjayaprakash Mutyala     {
311b8ad583fSGunnar Mills         BMCWEB_LOG_ERROR("DBUS response error {}", errorMessage);
31266b5ca76Sjayaprakash Mutyala         messages::internalError(asyncResp->res);
31366b5ca76Sjayaprakash Mutyala     }
31466b5ca76Sjayaprakash Mutyala }
31566b5ca76Sjayaprakash Mutyala 
31681ce609eSEd Tanous inline void parseLDAPConfigData(nlohmann::json& jsonResponse,
317ab828d7cSRatan Gupta                                 const LDAPConfigData& confData,
318ab828d7cSRatan Gupta                                 const std::string& ldapType)
3196973a582SRatan Gupta {
32049cc263fSEd Tanous     nlohmann::json::object_t ldap;
3211476687dSEd Tanous     ldap["ServiceEnabled"] = confData.serviceEnabled;
32249cc263fSEd Tanous     nlohmann::json::array_t serviceAddresses;
32349cc263fSEd Tanous     serviceAddresses.emplace_back(confData.uri);
32449cc263fSEd Tanous     ldap["ServiceAddresses"] = std::move(serviceAddresses);
32549cc263fSEd Tanous 
32649cc263fSEd Tanous     nlohmann::json::object_t authentication;
32749cc263fSEd Tanous     authentication["AuthenticationType"] =
3280ec8b83dSEd Tanous         account_service::AuthenticationTypes::UsernameAndPassword;
32949cc263fSEd Tanous     authentication["Username"] = confData.bindDN;
33049cc263fSEd Tanous     authentication["Password"] = nullptr;
33149cc263fSEd Tanous     ldap["Authentication"] = std::move(authentication);
3321476687dSEd Tanous 
33349cc263fSEd Tanous     nlohmann::json::object_t ldapService;
33449cc263fSEd Tanous     nlohmann::json::object_t searchSettings;
33549cc263fSEd Tanous     nlohmann::json::array_t baseDistinguishedNames;
33649cc263fSEd Tanous     baseDistinguishedNames.emplace_back(confData.baseDN);
3371476687dSEd Tanous 
33849cc263fSEd Tanous     searchSettings["BaseDistinguishedNames"] =
33949cc263fSEd Tanous         std::move(baseDistinguishedNames);
34049cc263fSEd Tanous     searchSettings["UsernameAttribute"] = confData.userNameAttribute;
34149cc263fSEd Tanous     searchSettings["GroupsAttribute"] = confData.groupAttribute;
34249cc263fSEd Tanous     ldapService["SearchSettings"] = std::move(searchSettings);
34349cc263fSEd Tanous     ldap["LDAPService"] = std::move(ldapService);
34449cc263fSEd Tanous 
34549cc263fSEd Tanous     nlohmann::json::array_t roleMapArray;
3469eb808c1SEd Tanous     for (const auto& obj : confData.groupRoleList)
34754fc587aSNagaraju Goruganti     {
34862598e31SEd Tanous         BMCWEB_LOG_DEBUG("Pushing the data groupName={}", obj.second.groupName);
349613dabeaSEd Tanous 
350613dabeaSEd Tanous         nlohmann::json::object_t remoteGroup;
351613dabeaSEd Tanous         remoteGroup["RemoteGroup"] = obj.second.groupName;
352329f0348SJorge Cisneros         remoteGroup["LocalRole"] = getRoleIdFromPrivilege(obj.second.privilege);
353329f0348SJorge Cisneros         roleMapArray.emplace_back(std::move(remoteGroup));
35454fc587aSNagaraju Goruganti     }
35549cc263fSEd Tanous 
35649cc263fSEd Tanous     ldap["RemoteRoleMapping"] = std::move(roleMapArray);
35749cc263fSEd Tanous 
35849cc263fSEd Tanous     jsonResponse[ldapType].update(ldap);
3596973a582SRatan Gupta }
3606973a582SRatan Gupta 
3616973a582SRatan Gupta /**
36206785244SRatan Gupta  *  @brief validates given JSON input and then calls appropriate method to
36306785244SRatan Gupta  * create, to delete or to set Rolemapping object based on the given input.
36406785244SRatan Gupta  *
36506785244SRatan Gupta  */
36623a21a1cSEd Tanous inline void handleRoleMapPatch(
3678d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
36806785244SRatan Gupta     const std::vector<std::pair<std::string, LDAPRoleMapData>>& roleMapObjData,
369c1019828SEd Tanous     const std::string& serverType,
370c1019828SEd Tanous     std::vector<std::variant<nlohmann::json::object_t, std::nullptr_t>>& input)
37106785244SRatan Gupta {
37206785244SRatan Gupta     for (size_t index = 0; index < input.size(); index++)
37306785244SRatan Gupta     {
374c1019828SEd Tanous         std::variant<nlohmann::json::object_t, std::nullptr_t>& thisJson =
375c1019828SEd Tanous             input[index];
376c1019828SEd Tanous         nlohmann::json::object_t* obj =
377c1019828SEd Tanous             std::get_if<nlohmann::json::object_t>(&thisJson);
378c1019828SEd Tanous         if (obj == nullptr)
37906785244SRatan Gupta         {
38006785244SRatan Gupta             // delete the existing object
38106785244SRatan Gupta             if (index < roleMapObjData.size())
38206785244SRatan Gupta             {
38306785244SRatan Gupta                 crow::connections::systemBus->async_method_call(
38406785244SRatan Gupta                     [asyncResp, roleMapObjData, serverType,
3855e7e2dc5SEd Tanous                      index](const boost::system::error_code& ec) {
38606785244SRatan Gupta                         if (ec)
38706785244SRatan Gupta                         {
38862598e31SEd Tanous                             BMCWEB_LOG_ERROR("DBUS response error: {}", ec);
38906785244SRatan Gupta                             messages::internalError(asyncResp->res);
39006785244SRatan Gupta                             return;
39106785244SRatan Gupta                         }
392*bd79bce8SPatrick Williams                         asyncResp->res
393*bd79bce8SPatrick Williams                             .jsonValue[serverType]["RemoteRoleMapping"][index] =
394*bd79bce8SPatrick Williams                             nullptr;
39506785244SRatan Gupta                     },
39606785244SRatan Gupta                     ldapDbusService, roleMapObjData[index].first,
39706785244SRatan Gupta                     "xyz.openbmc_project.Object.Delete", "Delete");
39806785244SRatan Gupta             }
39906785244SRatan Gupta             else
40006785244SRatan Gupta             {
40162598e31SEd Tanous                 BMCWEB_LOG_ERROR("Can't delete the object");
402*bd79bce8SPatrick Williams                 messages::propertyValueTypeError(
403*bd79bce8SPatrick Williams                     asyncResp->res, "null",
404*bd79bce8SPatrick Williams                     "RemoteRoleMapping/" + std::to_string(index));
40506785244SRatan Gupta                 return;
40606785244SRatan Gupta             }
40706785244SRatan Gupta         }
408c1019828SEd Tanous         else if (obj->empty())
40906785244SRatan Gupta         {
41006785244SRatan Gupta             // Don't do anything for the empty objects,parse next json
41106785244SRatan Gupta             // eg {"RemoteRoleMapping",[{}]}
41206785244SRatan Gupta         }
41306785244SRatan Gupta         else
41406785244SRatan Gupta         {
41506785244SRatan Gupta             // update/create the object
41606785244SRatan Gupta             std::optional<std::string> remoteGroup;
41706785244SRatan Gupta             std::optional<std::string> localRole;
41806785244SRatan Gupta 
419c1019828SEd Tanous             if (!json_util::readJsonObject(*obj, asyncResp->res, "RemoteGroup",
420c1019828SEd Tanous                                            remoteGroup, "LocalRole", localRole))
42106785244SRatan Gupta             {
42206785244SRatan Gupta                 continue;
42306785244SRatan Gupta             }
42406785244SRatan Gupta 
42506785244SRatan Gupta             // Update existing RoleMapping Object
42606785244SRatan Gupta             if (index < roleMapObjData.size())
42706785244SRatan Gupta             {
42862598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Update Role Map Object");
42906785244SRatan Gupta                 // If "RemoteGroup" info is provided
43006785244SRatan Gupta                 if (remoteGroup)
43106785244SRatan Gupta                 {
432d02aad39SEd Tanous                     setDbusProperty(
433e93abac6SGinu George                         asyncResp,
434d02aad39SEd Tanous                         std::format("RemoteRoleMapping/{}/RemoteGroup", index),
435e93abac6SGinu George                         ldapDbusService, roleMapObjData[index].first,
436e93abac6SGinu George                         "xyz.openbmc_project.User.PrivilegeMapperEntry",
437e93abac6SGinu George                         "GroupName", *remoteGroup);
43806785244SRatan Gupta                 }
43906785244SRatan Gupta 
44006785244SRatan Gupta                 // If "LocalRole" info is provided
44106785244SRatan Gupta                 if (localRole)
44206785244SRatan Gupta                 {
4436d0b80beSRavi Teja                     std::string priv = getPrivilegeFromRoleId(*localRole);
4446d0b80beSRavi Teja                     if (priv.empty())
4456d0b80beSRavi Teja                     {
4466d0b80beSRavi Teja                         messages::propertyValueNotInList(
4476d0b80beSRavi Teja                             asyncResp->res, *localRole,
4486d0b80beSRavi Teja                             std::format("RemoteRoleMapping/{}/LocalRole",
4496d0b80beSRavi Teja                                         index));
4506d0b80beSRavi Teja                         return;
4516d0b80beSRavi Teja                     }
452d02aad39SEd Tanous                     setDbusProperty(
453e93abac6SGinu George                         asyncResp,
454d02aad39SEd Tanous                         std::format("RemoteRoleMapping/{}/LocalRole", index),
455e93abac6SGinu George                         ldapDbusService, roleMapObjData[index].first,
456e93abac6SGinu George                         "xyz.openbmc_project.User.PrivilegeMapperEntry",
4576d0b80beSRavi Teja                         "Privilege", priv);
45806785244SRatan Gupta                 }
45906785244SRatan Gupta             }
46006785244SRatan Gupta             // Create a new RoleMapping Object.
46106785244SRatan Gupta             else
46206785244SRatan Gupta             {
46362598e31SEd Tanous                 BMCWEB_LOG_DEBUG(
46462598e31SEd Tanous                     "setRoleMappingProperties: Creating new Object");
465*bd79bce8SPatrick Williams                 std::string pathString =
466*bd79bce8SPatrick Williams                     "RemoteRoleMapping/" + std::to_string(index);
46706785244SRatan Gupta 
46806785244SRatan Gupta                 if (!localRole)
46906785244SRatan Gupta                 {
47006785244SRatan Gupta                     messages::propertyMissing(asyncResp->res,
47106785244SRatan Gupta                                               pathString + "/LocalRole");
47206785244SRatan Gupta                     continue;
47306785244SRatan Gupta                 }
47406785244SRatan Gupta                 if (!remoteGroup)
47506785244SRatan Gupta                 {
47606785244SRatan Gupta                     messages::propertyMissing(asyncResp->res,
47706785244SRatan Gupta                                               pathString + "/RemoteGroup");
47806785244SRatan Gupta                     continue;
47906785244SRatan Gupta                 }
48006785244SRatan Gupta 
48106785244SRatan Gupta                 std::string dbusObjectPath;
48206785244SRatan Gupta                 if (serverType == "ActiveDirectory")
48306785244SRatan Gupta                 {
4842c70f800SEd Tanous                     dbusObjectPath = adConfigObject;
48506785244SRatan Gupta                 }
48606785244SRatan Gupta                 else if (serverType == "LDAP")
48706785244SRatan Gupta                 {
48823a21a1cSEd Tanous                     dbusObjectPath = ldapConfigObjectName;
48906785244SRatan Gupta                 }
49006785244SRatan Gupta 
49162598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Remote Group={},LocalRole={}", *remoteGroup,
49262598e31SEd Tanous                                  *localRole);
49306785244SRatan Gupta 
49406785244SRatan Gupta                 crow::connections::systemBus->async_method_call(
495271584abSEd Tanous                     [asyncResp, serverType, localRole,
4965e7e2dc5SEd Tanous                      remoteGroup](const boost::system::error_code& ec) {
49706785244SRatan Gupta                         if (ec)
49806785244SRatan Gupta                         {
49962598e31SEd Tanous                             BMCWEB_LOG_ERROR("DBUS response error: {}", ec);
50006785244SRatan Gupta                             messages::internalError(asyncResp->res);
50106785244SRatan Gupta                             return;
50206785244SRatan Gupta                         }
50306785244SRatan Gupta                         nlohmann::json& remoteRoleJson =
50406785244SRatan Gupta                             asyncResp->res
50506785244SRatan Gupta                                 .jsonValue[serverType]["RemoteRoleMapping"];
5061476687dSEd Tanous                         nlohmann::json::object_t roleMapEntry;
5071476687dSEd Tanous                         roleMapEntry["LocalRole"] = *localRole;
5081476687dSEd Tanous                         roleMapEntry["RemoteGroup"] = *remoteGroup;
509b2ba3072SPatrick Williams                         remoteRoleJson.emplace_back(std::move(roleMapEntry));
51006785244SRatan Gupta                     },
51106785244SRatan Gupta                     ldapDbusService, dbusObjectPath, ldapPrivMapperInterface,
5123174e4dfSEd Tanous                     "Create", *remoteGroup,
51306785244SRatan Gupta                     getPrivilegeFromRoleId(std::move(*localRole)));
51406785244SRatan Gupta             }
51506785244SRatan Gupta         }
51606785244SRatan Gupta     }
51706785244SRatan Gupta }
51806785244SRatan Gupta 
51906785244SRatan Gupta /**
5206973a582SRatan Gupta  * Function that retrieves all properties for LDAP config object
5216973a582SRatan Gupta  * into JSON
5226973a582SRatan Gupta  */
5236973a582SRatan Gupta template <typename CallbackFunc>
524*bd79bce8SPatrick Williams inline void
525*bd79bce8SPatrick Williams     getLDAPConfigData(const std::string& ldapType, CallbackFunc&& callback)
5266973a582SRatan Gupta {
5272b73119cSGeorge Liu     constexpr std::array<std::string_view, 2> interfaces = {
5282b73119cSGeorge Liu         ldapEnableInterface, ldapConfigInterface};
52954fc587aSNagaraju Goruganti 
5302b73119cSGeorge Liu     dbus::utility::getDbusObject(
5312b73119cSGeorge Liu         ldapConfigObjectName, interfaces,
5328cb2c024SEd Tanous         [callback = std::forward<CallbackFunc>(callback),
533c1019828SEd Tanous          ldapType](const boost::system::error_code& ec,
534c1019828SEd Tanous                    const dbus::utility::MapperGetObject& resp) mutable {
53554fc587aSNagaraju Goruganti             if (ec || resp.empty())
53654fc587aSNagaraju Goruganti             {
537bf2ddedeSCarson Labrado                 BMCWEB_LOG_WARNING(
538*bd79bce8SPatrick Williams                     "DBUS response error during getting of service name: {}",
539*bd79bce8SPatrick Williams                     ec);
54023a21a1cSEd Tanous                 LDAPConfigData empty{};
54123a21a1cSEd Tanous                 callback(false, empty, ldapType);
54254fc587aSNagaraju Goruganti                 return;
54354fc587aSNagaraju Goruganti             }
54454fc587aSNagaraju Goruganti             std::string service = resp.begin()->first;
5455eb468daSGeorge Liu             sdbusplus::message::object_path path(ldapRootObject);
5465eb468daSGeorge Liu             dbus::utility::getManagedObjects(
5475eb468daSGeorge Liu                 service, path,
548*bd79bce8SPatrick Williams                 [callback, ldapType](const boost::system::error_code& ec2,
549*bd79bce8SPatrick Williams                                      const dbus::utility::ManagedObjectType&
550*bd79bce8SPatrick Williams                                          ldapObjects) mutable {
5516973a582SRatan Gupta                     LDAPConfigData confData{};
5528b24275dSEd Tanous                     if (ec2)
5536973a582SRatan Gupta                     {
554ab828d7cSRatan Gupta                         callback(false, confData, ldapType);
555bf2ddedeSCarson Labrado                         BMCWEB_LOG_WARNING("D-Bus responses error: {}", ec2);
5566973a582SRatan Gupta                         return;
5576973a582SRatan Gupta                     }
558ab828d7cSRatan Gupta 
559ab828d7cSRatan Gupta                     std::string ldapDbusType;
56054fc587aSNagaraju Goruganti                     std::string searchString;
56154fc587aSNagaraju Goruganti 
562ab828d7cSRatan Gupta                     if (ldapType == "LDAP")
563ab828d7cSRatan Gupta                     {
5640fda0f12SGeorge Liu                         ldapDbusType =
5650fda0f12SGeorge Liu                             "xyz.openbmc_project.User.Ldap.Config.Type.OpenLdap";
56654fc587aSNagaraju Goruganti                         searchString = "openldap";
567ab828d7cSRatan Gupta                     }
568ab828d7cSRatan Gupta                     else if (ldapType == "ActiveDirectory")
569ab828d7cSRatan Gupta                     {
57054fc587aSNagaraju Goruganti                         ldapDbusType =
5710fda0f12SGeorge Liu                             "xyz.openbmc_project.User.Ldap.Config.Type.ActiveDirectory";
57254fc587aSNagaraju Goruganti                         searchString = "active_directory";
573ab828d7cSRatan Gupta                     }
574ab828d7cSRatan Gupta                     else
575ab828d7cSRatan Gupta                     {
576*bd79bce8SPatrick Williams                         BMCWEB_LOG_ERROR(
577*bd79bce8SPatrick Williams                             "Can't get the DbusType for the given type={}",
57862598e31SEd Tanous                             ldapType);
579ab828d7cSRatan Gupta                         callback(false, confData, ldapType);
580ab828d7cSRatan Gupta                         return;
581ab828d7cSRatan Gupta                     }
582ab828d7cSRatan Gupta 
583ab828d7cSRatan Gupta                     std::string ldapEnableInterfaceStr = ldapEnableInterface;
584ab828d7cSRatan Gupta                     std::string ldapConfigInterfaceStr = ldapConfigInterface;
585ab828d7cSRatan Gupta 
5866973a582SRatan Gupta                     for (const auto& object : ldapObjects)
5876973a582SRatan Gupta                     {
58854fc587aSNagaraju Goruganti                         // let's find the object whose ldap type is equal to the
58954fc587aSNagaraju Goruganti                         // given type
590*bd79bce8SPatrick Williams                         if (object.first.str.find(searchString) ==
591*bd79bce8SPatrick Williams                             std::string::npos)
5926973a582SRatan Gupta                         {
593ab828d7cSRatan Gupta                             continue;
594ab828d7cSRatan Gupta                         }
595ab828d7cSRatan Gupta 
5966973a582SRatan Gupta                         for (const auto& interface : object.second)
5976973a582SRatan Gupta                         {
5986973a582SRatan Gupta                             if (interface.first == ldapEnableInterfaceStr)
5996973a582SRatan Gupta                             {
6006973a582SRatan Gupta                                 // rest of the properties are string.
6016973a582SRatan Gupta                                 for (const auto& property : interface.second)
6026973a582SRatan Gupta                                 {
6036973a582SRatan Gupta                                     if (property.first == "Enabled")
6046973a582SRatan Gupta                                     {
6056973a582SRatan Gupta                                         const bool* value =
6066973a582SRatan Gupta                                             std::get_if<bool>(&property.second);
6076973a582SRatan Gupta                                         if (value == nullptr)
6086973a582SRatan Gupta                                         {
6096973a582SRatan Gupta                                             continue;
6106973a582SRatan Gupta                                         }
6116973a582SRatan Gupta                                         confData.serviceEnabled = *value;
6126973a582SRatan Gupta                                         break;
6136973a582SRatan Gupta                                     }
6146973a582SRatan Gupta                                 }
6156973a582SRatan Gupta                             }
6166973a582SRatan Gupta                             else if (interface.first == ldapConfigInterfaceStr)
6176973a582SRatan Gupta                             {
6186973a582SRatan Gupta                                 for (const auto& property : interface.second)
6196973a582SRatan Gupta                                 {
620271584abSEd Tanous                                     const std::string* strValue =
621*bd79bce8SPatrick Williams                                         std::get_if<std::string>(
622*bd79bce8SPatrick Williams                                             &property.second);
623271584abSEd Tanous                                     if (strValue == nullptr)
6246973a582SRatan Gupta                                     {
6256973a582SRatan Gupta                                         continue;
6266973a582SRatan Gupta                                     }
6276973a582SRatan Gupta                                     if (property.first == "LDAPServerURI")
6286973a582SRatan Gupta                                     {
629271584abSEd Tanous                                         confData.uri = *strValue;
6306973a582SRatan Gupta                                     }
6316973a582SRatan Gupta                                     else if (property.first == "LDAPBindDN")
6326973a582SRatan Gupta                                     {
633271584abSEd Tanous                                         confData.bindDN = *strValue;
6346973a582SRatan Gupta                                     }
6356973a582SRatan Gupta                                     else if (property.first == "LDAPBaseDN")
6366973a582SRatan Gupta                                     {
637271584abSEd Tanous                                         confData.baseDN = *strValue;
6386973a582SRatan Gupta                                     }
639*bd79bce8SPatrick Williams                                     else if (property.first ==
640*bd79bce8SPatrick Williams                                              "LDAPSearchScope")
6416973a582SRatan Gupta                                     {
642271584abSEd Tanous                                         confData.searchScope = *strValue;
6436973a582SRatan Gupta                                     }
644*bd79bce8SPatrick Williams                                     else if (property.first ==
645*bd79bce8SPatrick Williams                                              "GroupNameAttribute")
6466973a582SRatan Gupta                                     {
647271584abSEd Tanous                                         confData.groupAttribute = *strValue;
6486973a582SRatan Gupta                                     }
649*bd79bce8SPatrick Williams                                     else if (property.first ==
650*bd79bce8SPatrick Williams                                              "UserNameAttribute")
6516973a582SRatan Gupta                                     {
652271584abSEd Tanous                                         confData.userNameAttribute = *strValue;
6536973a582SRatan Gupta                                     }
65454fc587aSNagaraju Goruganti                                     else if (property.first == "LDAPType")
655ab828d7cSRatan Gupta                                     {
656271584abSEd Tanous                                         confData.serverType = *strValue;
65754fc587aSNagaraju Goruganti                                     }
65854fc587aSNagaraju Goruganti                                 }
65954fc587aSNagaraju Goruganti                             }
660*bd79bce8SPatrick Williams                             else if (
661*bd79bce8SPatrick Williams                                 interface.first ==
6620fda0f12SGeorge Liu                                 "xyz.openbmc_project.User.PrivilegeMapperEntry")
66354fc587aSNagaraju Goruganti                             {
66454fc587aSNagaraju Goruganti                                 LDAPRoleMapData roleMapData{};
66554fc587aSNagaraju Goruganti                                 for (const auto& property : interface.second)
66654fc587aSNagaraju Goruganti                                 {
667271584abSEd Tanous                                     const std::string* strValue =
668*bd79bce8SPatrick Williams                                         std::get_if<std::string>(
669*bd79bce8SPatrick Williams                                             &property.second);
67054fc587aSNagaraju Goruganti 
671271584abSEd Tanous                                     if (strValue == nullptr)
67254fc587aSNagaraju Goruganti                                     {
67354fc587aSNagaraju Goruganti                                         continue;
67454fc587aSNagaraju Goruganti                                     }
67554fc587aSNagaraju Goruganti 
67654fc587aSNagaraju Goruganti                                     if (property.first == "GroupName")
67754fc587aSNagaraju Goruganti                                     {
678271584abSEd Tanous                                         roleMapData.groupName = *strValue;
67954fc587aSNagaraju Goruganti                                     }
68054fc587aSNagaraju Goruganti                                     else if (property.first == "Privilege")
68154fc587aSNagaraju Goruganti                                     {
682271584abSEd Tanous                                         roleMapData.privilege = *strValue;
68354fc587aSNagaraju Goruganti                                     }
68454fc587aSNagaraju Goruganti                                 }
68554fc587aSNagaraju Goruganti 
686*bd79bce8SPatrick Williams                                 confData.groupRoleList.emplace_back(
687*bd79bce8SPatrick Williams                                     object.first.str, roleMapData);
68854fc587aSNagaraju Goruganti                             }
68954fc587aSNagaraju Goruganti                         }
69054fc587aSNagaraju Goruganti                     }
691ab828d7cSRatan Gupta                     callback(true, confData, ldapType);
6925eb468daSGeorge Liu                 });
6932b73119cSGeorge Liu         });
6946973a582SRatan Gupta }
6956973a582SRatan Gupta 
6968a07d286SRatan Gupta /**
6978a07d286SRatan Gupta  * @brief updates the LDAP server address and updates the
6988a07d286SRatan Gupta           json response with the new value.
6998a07d286SRatan Gupta  * @param serviceAddressList address to be updated.
7008a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7018a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7028a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7038a07d286SRatan Gupta  */
7048a07d286SRatan Gupta 
7054f48d5f6SEd Tanous inline void handleServiceAddressPatch(
7068a07d286SRatan Gupta     const std::vector<std::string>& serviceAddressList,
7078d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7088a07d286SRatan Gupta     const std::string& ldapServerElementName,
7098a07d286SRatan Gupta     const std::string& ldapConfigObject)
7108a07d286SRatan Gupta {
711e93abac6SGinu George     setDbusProperty(asyncResp, ldapServerElementName + "/ServiceAddress",
712e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapConfigInterface,
713e93abac6SGinu George                     "LDAPServerURI", serviceAddressList.front());
7148a07d286SRatan Gupta }
7158a07d286SRatan Gupta /**
7168a07d286SRatan Gupta  * @brief updates the LDAP Bind DN and updates the
7178a07d286SRatan Gupta           json response with the new value.
7188a07d286SRatan Gupta  * @param username name of the user which needs to be updated.
7198a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7208a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7218a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7228a07d286SRatan Gupta  */
7238a07d286SRatan Gupta 
7244f48d5f6SEd Tanous inline void
7254f48d5f6SEd Tanous     handleUserNamePatch(const std::string& username,
7268d1b46d7Szhanghch05                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7278a07d286SRatan Gupta                         const std::string& ldapServerElementName,
7288a07d286SRatan Gupta                         const std::string& ldapConfigObject)
7298a07d286SRatan Gupta {
730e93abac6SGinu George     setDbusProperty(asyncResp,
731d02aad39SEd Tanous                     ldapServerElementName + "/Authentication/Username",
732e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapConfigInterface,
733e93abac6SGinu George                     "LDAPBindDN", username);
7348a07d286SRatan Gupta }
7358a07d286SRatan Gupta 
7368a07d286SRatan Gupta /**
7378a07d286SRatan Gupta  * @brief updates the LDAP password
7388a07d286SRatan Gupta  * @param password : ldap password which needs to be updated.
7398a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7408a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7418a07d286SRatan Gupta  *        server(openLDAP/ActiveDirectory)
7428a07d286SRatan Gupta  */
7438a07d286SRatan Gupta 
7444f48d5f6SEd Tanous inline void
7454f48d5f6SEd Tanous     handlePasswordPatch(const std::string& password,
7468d1b46d7Szhanghch05                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7478a07d286SRatan Gupta                         const std::string& ldapServerElementName,
7488a07d286SRatan Gupta                         const std::string& ldapConfigObject)
7498a07d286SRatan Gupta {
750e93abac6SGinu George     setDbusProperty(asyncResp,
751d02aad39SEd Tanous                     ldapServerElementName + "/Authentication/Password",
752e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapConfigInterface,
753e93abac6SGinu George                     "LDAPBindDNPassword", password);
7548a07d286SRatan Gupta }
7558a07d286SRatan Gupta 
7568a07d286SRatan Gupta /**
7578a07d286SRatan Gupta  * @brief updates the LDAP BaseDN and updates the
7588a07d286SRatan Gupta           json response with the new value.
7598a07d286SRatan Gupta  * @param baseDNList baseDN list which needs to be updated.
7608a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7618a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7628a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7638a07d286SRatan Gupta  */
7648a07d286SRatan Gupta 
7654f48d5f6SEd Tanous inline void
7664f48d5f6SEd Tanous     handleBaseDNPatch(const std::vector<std::string>& baseDNList,
7678d1b46d7Szhanghch05                       const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7688a07d286SRatan Gupta                       const std::string& ldapServerElementName,
7698a07d286SRatan Gupta                       const std::string& ldapConfigObject)
7708a07d286SRatan Gupta {
771e93abac6SGinu George     setDbusProperty(asyncResp,
772d02aad39SEd Tanous                     ldapServerElementName +
773d02aad39SEd Tanous                         "/LDAPService/SearchSettings/BaseDistinguishedNames",
774e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapConfigInterface,
775e93abac6SGinu George                     "LDAPBaseDN", baseDNList.front());
7768a07d286SRatan Gupta }
7778a07d286SRatan Gupta /**
7788a07d286SRatan Gupta  * @brief updates the LDAP user name attribute and updates the
7798a07d286SRatan Gupta           json response with the new value.
7808a07d286SRatan Gupta  * @param userNameAttribute attribute to be updated.
7818a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7828a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7838a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7848a07d286SRatan Gupta  */
7858a07d286SRatan Gupta 
786*bd79bce8SPatrick Williams inline void handleUserNameAttrPatch(
787*bd79bce8SPatrick Williams     const std::string& userNameAttribute,
7888d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7898a07d286SRatan Gupta     const std::string& ldapServerElementName,
7908a07d286SRatan Gupta     const std::string& ldapConfigObject)
7918a07d286SRatan Gupta {
792*bd79bce8SPatrick Williams     setDbusProperty(
793*bd79bce8SPatrick Williams         asyncResp,
794*bd79bce8SPatrick Williams         ldapServerElementName + "LDAPService/SearchSettings/UsernameAttribute",
795e93abac6SGinu George         ldapDbusService, ldapConfigObject, ldapConfigInterface,
796e93abac6SGinu George         "UserNameAttribute", userNameAttribute);
7978a07d286SRatan Gupta }
7988a07d286SRatan Gupta /**
7998a07d286SRatan Gupta  * @brief updates the LDAP group attribute and updates the
8008a07d286SRatan Gupta           json response with the new value.
8018a07d286SRatan Gupta  * @param groupsAttribute attribute to be updated.
8028a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
8038a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
8048a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
8058a07d286SRatan Gupta  */
8068a07d286SRatan Gupta 
8074f48d5f6SEd Tanous inline void handleGroupNameAttrPatch(
8088d1b46d7Szhanghch05     const std::string& groupsAttribute,
8098d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8108a07d286SRatan Gupta     const std::string& ldapServerElementName,
8118a07d286SRatan Gupta     const std::string& ldapConfigObject)
8128a07d286SRatan Gupta {
813*bd79bce8SPatrick Williams     setDbusProperty(
814*bd79bce8SPatrick Williams         asyncResp,
815*bd79bce8SPatrick Williams         ldapServerElementName + "/LDAPService/SearchSettings/GroupsAttribute",
816e93abac6SGinu George         ldapDbusService, ldapConfigObject, ldapConfigInterface,
817e93abac6SGinu George         "GroupNameAttribute", groupsAttribute);
8188a07d286SRatan Gupta }
8198a07d286SRatan Gupta /**
8208a07d286SRatan Gupta  * @brief updates the LDAP service enable and updates the
8218a07d286SRatan Gupta           json response with the new value.
8228a07d286SRatan Gupta  * @param input JSON data.
8238a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
8248a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
8258a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
8268a07d286SRatan Gupta  */
8278a07d286SRatan Gupta 
8284f48d5f6SEd Tanous inline void handleServiceEnablePatch(
8296c51eab1SEd Tanous     bool serviceEnabled, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8308a07d286SRatan Gupta     const std::string& ldapServerElementName,
8318a07d286SRatan Gupta     const std::string& ldapConfigObject)
8328a07d286SRatan Gupta {
833e93abac6SGinu George     setDbusProperty(asyncResp, ldapServerElementName + "/ServiceEnabled",
834e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapEnableInterface,
835e93abac6SGinu George                     "Enabled", serviceEnabled);
8368a07d286SRatan Gupta }
8378a07d286SRatan Gupta 
838c1019828SEd Tanous struct AuthMethods
83978158631SZbigniew Kurzynski {
84078158631SZbigniew Kurzynski     std::optional<bool> basicAuth;
84178158631SZbigniew Kurzynski     std::optional<bool> cookie;
84278158631SZbigniew Kurzynski     std::optional<bool> sessionToken;
84378158631SZbigniew Kurzynski     std::optional<bool> xToken;
844501f1e58SZbigniew Kurzynski     std::optional<bool> tls;
845c1019828SEd Tanous };
84678158631SZbigniew Kurzynski 
847c1019828SEd Tanous inline void
848c1019828SEd Tanous     handleAuthMethodsPatch(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
849c1019828SEd Tanous                            const AuthMethods& auth)
85078158631SZbigniew Kurzynski {
851c1019828SEd Tanous     persistent_data::AuthConfigMethods& authMethodsConfig =
85252cc112dSEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
85378158631SZbigniew Kurzynski 
854c1019828SEd Tanous     if (auth.basicAuth)
85578158631SZbigniew Kurzynski     {
85625b54dbaSEd Tanous         if constexpr (!BMCWEB_BASIC_AUTH)
85725b54dbaSEd Tanous         {
858f16f6263SAlan Kuo             messages::actionNotSupported(
8590fda0f12SGeorge Liu                 asyncResp->res,
8600fda0f12SGeorge Liu                 "Setting BasicAuth when basic-auth feature is disabled");
861f16f6263SAlan Kuo             return;
86225b54dbaSEd Tanous         }
86325b54dbaSEd Tanous 
864c1019828SEd Tanous         authMethodsConfig.basic = *auth.basicAuth;
86578158631SZbigniew Kurzynski     }
86678158631SZbigniew Kurzynski 
867c1019828SEd Tanous     if (auth.cookie)
86878158631SZbigniew Kurzynski     {
86925b54dbaSEd Tanous         if constexpr (!BMCWEB_COOKIE_AUTH)
87025b54dbaSEd Tanous         {
8710fda0f12SGeorge Liu             messages::actionNotSupported(
8720fda0f12SGeorge Liu                 asyncResp->res,
8730fda0f12SGeorge Liu                 "Setting Cookie when cookie-auth feature is disabled");
874f16f6263SAlan Kuo             return;
87525b54dbaSEd Tanous         }
876c1019828SEd Tanous         authMethodsConfig.cookie = *auth.cookie;
87778158631SZbigniew Kurzynski     }
87878158631SZbigniew Kurzynski 
879c1019828SEd Tanous     if (auth.sessionToken)
88078158631SZbigniew Kurzynski     {
88125b54dbaSEd Tanous         if constexpr (!BMCWEB_SESSION_AUTH)
88225b54dbaSEd Tanous         {
883f16f6263SAlan Kuo             messages::actionNotSupported(
8840fda0f12SGeorge Liu                 asyncResp->res,
8850fda0f12SGeorge Liu                 "Setting SessionToken when session-auth feature is disabled");
886f16f6263SAlan Kuo             return;
88725b54dbaSEd Tanous         }
888c1019828SEd Tanous         authMethodsConfig.sessionToken = *auth.sessionToken;
88978158631SZbigniew Kurzynski     }
89078158631SZbigniew Kurzynski 
891c1019828SEd Tanous     if (auth.xToken)
89278158631SZbigniew Kurzynski     {
89325b54dbaSEd Tanous         if constexpr (!BMCWEB_XTOKEN_AUTH)
89425b54dbaSEd Tanous         {
8950fda0f12SGeorge Liu             messages::actionNotSupported(
8960fda0f12SGeorge Liu                 asyncResp->res,
8970fda0f12SGeorge Liu                 "Setting XToken when xtoken-auth feature is disabled");
898f16f6263SAlan Kuo             return;
89925b54dbaSEd Tanous         }
900c1019828SEd Tanous         authMethodsConfig.xtoken = *auth.xToken;
90178158631SZbigniew Kurzynski     }
90278158631SZbigniew Kurzynski 
903c1019828SEd Tanous     if (auth.tls)
904501f1e58SZbigniew Kurzynski     {
90525b54dbaSEd Tanous         if constexpr (!BMCWEB_MUTUAL_TLS_AUTH)
90625b54dbaSEd Tanous         {
9070fda0f12SGeorge Liu             messages::actionNotSupported(
9080fda0f12SGeorge Liu                 asyncResp->res,
9090fda0f12SGeorge Liu                 "Setting TLS when mutual-tls-auth feature is disabled");
910f16f6263SAlan Kuo             return;
91125b54dbaSEd Tanous         }
912c1019828SEd Tanous         authMethodsConfig.tls = *auth.tls;
913501f1e58SZbigniew Kurzynski     }
914501f1e58SZbigniew Kurzynski 
91578158631SZbigniew Kurzynski     if (!authMethodsConfig.basic && !authMethodsConfig.cookie &&
916501f1e58SZbigniew Kurzynski         !authMethodsConfig.sessionToken && !authMethodsConfig.xtoken &&
917501f1e58SZbigniew Kurzynski         !authMethodsConfig.tls)
91878158631SZbigniew Kurzynski     {
91978158631SZbigniew Kurzynski         // Do not allow user to disable everything
92078158631SZbigniew Kurzynski         messages::actionNotSupported(asyncResp->res,
92178158631SZbigniew Kurzynski                                      "of disabling all available methods");
92278158631SZbigniew Kurzynski         return;
92378158631SZbigniew Kurzynski     }
92478158631SZbigniew Kurzynski 
92552cc112dSEd Tanous     persistent_data::SessionStore::getInstance().updateAuthMethodsConfig(
92652cc112dSEd Tanous         authMethodsConfig);
92778158631SZbigniew Kurzynski     // Save configuration immediately
92852cc112dSEd Tanous     persistent_data::getConfig().writeData();
92978158631SZbigniew Kurzynski 
93078158631SZbigniew Kurzynski     messages::success(asyncResp->res);
93178158631SZbigniew Kurzynski }
93278158631SZbigniew Kurzynski 
9338a07d286SRatan Gupta /**
9348a07d286SRatan Gupta  * @brief Get the required values from the given JSON, validates the
9358a07d286SRatan Gupta  *        value and create the LDAP config object.
9368a07d286SRatan Gupta  * @param input JSON data
9378a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
9388a07d286SRatan Gupta  * @param serverType Type of LDAP server(openLDAP/ActiveDirectory)
9398a07d286SRatan Gupta  */
9408a07d286SRatan Gupta 
94110cb44f3SEd Tanous struct LdapPatchParams
94210cb44f3SEd Tanous {
94310cb44f3SEd Tanous     std::optional<std::string> authType;
94410cb44f3SEd Tanous     std::optional<std::vector<std::string>> serviceAddressList;
94510cb44f3SEd Tanous     std::optional<bool> serviceEnabled;
94610cb44f3SEd Tanous     std::optional<std::vector<std::string>> baseDNList;
94710cb44f3SEd Tanous     std::optional<std::string> userNameAttribute;
94810cb44f3SEd Tanous     std::optional<std::string> groupsAttribute;
94910cb44f3SEd Tanous     std::optional<std::string> userName;
95010cb44f3SEd Tanous     std::optional<std::string> password;
95110cb44f3SEd Tanous     std::optional<
95210cb44f3SEd Tanous         std::vector<std::variant<nlohmann::json::object_t, std::nullptr_t>>>
95310cb44f3SEd Tanous         remoteRoleMapData;
95410cb44f3SEd Tanous };
95510cb44f3SEd Tanous 
95610cb44f3SEd Tanous inline void handleLDAPPatch(LdapPatchParams&& input,
9578d1b46d7Szhanghch05                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
9588a07d286SRatan Gupta                             const std::string& serverType)
9598a07d286SRatan Gupta {
960eb2bbe56SRatan Gupta     std::string dbusObjectPath;
961eb2bbe56SRatan Gupta     if (serverType == "ActiveDirectory")
962eb2bbe56SRatan Gupta     {
9632c70f800SEd Tanous         dbusObjectPath = adConfigObject;
964eb2bbe56SRatan Gupta     }
965eb2bbe56SRatan Gupta     else if (serverType == "LDAP")
966eb2bbe56SRatan Gupta     {
96723a21a1cSEd Tanous         dbusObjectPath = ldapConfigObjectName;
968eb2bbe56SRatan Gupta     }
969cb13a392SEd Tanous     else
970cb13a392SEd Tanous     {
97110cb44f3SEd Tanous         BMCWEB_LOG_ERROR("serverType wasn't AD or LDAP but was {}????",
97210cb44f3SEd Tanous                          serverType);
973cb13a392SEd Tanous         return;
974cb13a392SEd Tanous     }
975eb2bbe56SRatan Gupta 
97610cb44f3SEd Tanous     if (input.authType && *input.authType != "UsernameAndPassword")
9778a07d286SRatan Gupta     {
97810cb44f3SEd Tanous         messages::propertyValueNotInList(asyncResp->res, *input.authType,
979c1019828SEd Tanous                                          "AuthenticationType");
980c1019828SEd Tanous         return;
9818a07d286SRatan Gupta     }
982c1019828SEd Tanous 
98310cb44f3SEd Tanous     if (input.serviceAddressList)
9848a07d286SRatan Gupta     {
98510cb44f3SEd Tanous         if (input.serviceAddressList->empty())
9868a07d286SRatan Gupta         {
987e2616cc5SEd Tanous             messages::propertyValueNotInList(
98810cb44f3SEd Tanous                 asyncResp->res, *input.serviceAddressList, "ServiceAddress");
9898a07d286SRatan Gupta             return;
9908a07d286SRatan Gupta         }
9918a07d286SRatan Gupta     }
99210cb44f3SEd Tanous     if (input.baseDNList)
9938a07d286SRatan Gupta     {
99410cb44f3SEd Tanous         if (input.baseDNList->empty())
9958a07d286SRatan Gupta         {
99610cb44f3SEd Tanous             messages::propertyValueNotInList(asyncResp->res, *input.baseDNList,
9978a07d286SRatan Gupta                                              "BaseDistinguishedNames");
9988a07d286SRatan Gupta             return;
9998a07d286SRatan Gupta         }
10008a07d286SRatan Gupta     }
10018a07d286SRatan Gupta 
10028a07d286SRatan Gupta     // nothing to update, then return
100310cb44f3SEd Tanous     if (!input.userName && !input.password && !input.serviceAddressList &&
100410cb44f3SEd Tanous         !input.baseDNList && !input.userNameAttribute &&
100510cb44f3SEd Tanous         !input.groupsAttribute && !input.serviceEnabled &&
100610cb44f3SEd Tanous         !input.remoteRoleMapData)
10078a07d286SRatan Gupta     {
10088a07d286SRatan Gupta         return;
10098a07d286SRatan Gupta     }
10108a07d286SRatan Gupta 
10118a07d286SRatan Gupta     // Get the existing resource first then keep modifying
10128a07d286SRatan Gupta     // whenever any property gets updated.
1013*bd79bce8SPatrick Williams     getLDAPConfigData(serverType, [asyncResp, input = std::move(input),
101410cb44f3SEd Tanous                                    dbusObjectPath = std::move(dbusObjectPath)](
1015*bd79bce8SPatrick Williams                                       bool success,
1016*bd79bce8SPatrick Williams                                       const LDAPConfigData& confData,
1017c1019828SEd Tanous                                       const std::string& serverT) mutable {
10188a07d286SRatan Gupta         if (!success)
10198a07d286SRatan Gupta         {
10208a07d286SRatan Gupta             messages::internalError(asyncResp->res);
10218a07d286SRatan Gupta             return;
10228a07d286SRatan Gupta         }
10236c51eab1SEd Tanous         parseLDAPConfigData(asyncResp->res.jsonValue, confData, serverT);
10248a07d286SRatan Gupta         if (confData.serviceEnabled)
10258a07d286SRatan Gupta         {
10268a07d286SRatan Gupta             // Disable the service first and update the rest of
10278a07d286SRatan Gupta             // the properties.
10286c51eab1SEd Tanous             handleServiceEnablePatch(false, asyncResp, serverT, dbusObjectPath);
10298a07d286SRatan Gupta         }
10308a07d286SRatan Gupta 
103110cb44f3SEd Tanous         if (input.serviceAddressList)
10328a07d286SRatan Gupta         {
103310cb44f3SEd Tanous             handleServiceAddressPatch(*input.serviceAddressList, asyncResp,
103410cb44f3SEd Tanous                                       serverT, dbusObjectPath);
103510cb44f3SEd Tanous         }
103610cb44f3SEd Tanous         if (input.userName)
103710cb44f3SEd Tanous         {
103810cb44f3SEd Tanous             handleUserNamePatch(*input.userName, asyncResp, serverT,
10396c51eab1SEd Tanous                                 dbusObjectPath);
10408a07d286SRatan Gupta         }
104110cb44f3SEd Tanous         if (input.password)
10428a07d286SRatan Gupta         {
104310cb44f3SEd Tanous             handlePasswordPatch(*input.password, asyncResp, serverT,
104410cb44f3SEd Tanous                                 dbusObjectPath);
10458a07d286SRatan Gupta         }
10468a07d286SRatan Gupta 
104710cb44f3SEd Tanous         if (input.baseDNList)
10488a07d286SRatan Gupta         {
104910cb44f3SEd Tanous             handleBaseDNPatch(*input.baseDNList, asyncResp, serverT,
10506c51eab1SEd Tanous                               dbusObjectPath);
10518a07d286SRatan Gupta         }
105210cb44f3SEd Tanous         if (input.userNameAttribute)
10538a07d286SRatan Gupta         {
105410cb44f3SEd Tanous             handleUserNameAttrPatch(*input.userNameAttribute, asyncResp,
105510cb44f3SEd Tanous                                     serverT, dbusObjectPath);
105610cb44f3SEd Tanous         }
105710cb44f3SEd Tanous         if (input.groupsAttribute)
105810cb44f3SEd Tanous         {
105910cb44f3SEd Tanous             handleGroupNameAttrPatch(*input.groupsAttribute, asyncResp, serverT,
10606c51eab1SEd Tanous                                      dbusObjectPath);
10618a07d286SRatan Gupta         }
106210cb44f3SEd Tanous         if (input.serviceEnabled)
10638a07d286SRatan Gupta         {
10648a07d286SRatan Gupta             // if user has given the value as true then enable
10658a07d286SRatan Gupta             // the service. if user has given false then no-op
10668a07d286SRatan Gupta             // as service is already stopped.
106710cb44f3SEd Tanous             if (*input.serviceEnabled)
10688a07d286SRatan Gupta             {
106910cb44f3SEd Tanous                 handleServiceEnablePatch(*input.serviceEnabled, asyncResp,
107010cb44f3SEd Tanous                                          serverT, dbusObjectPath);
10718a07d286SRatan Gupta             }
10728a07d286SRatan Gupta         }
10738a07d286SRatan Gupta         else
10748a07d286SRatan Gupta         {
10758a07d286SRatan Gupta             // if user has not given the service enabled value
10768a07d286SRatan Gupta             // then revert it to the same state as it was
10778a07d286SRatan Gupta             // before.
10788a07d286SRatan Gupta             handleServiceEnablePatch(confData.serviceEnabled, asyncResp,
107923a21a1cSEd Tanous                                      serverT, dbusObjectPath);
10808a07d286SRatan Gupta         }
108106785244SRatan Gupta 
108210cb44f3SEd Tanous         if (input.remoteRoleMapData)
108306785244SRatan Gupta         {
10846c51eab1SEd Tanous             handleRoleMapPatch(asyncResp, confData.groupRoleList, serverT,
108510cb44f3SEd Tanous                                *input.remoteRoleMapData);
108606785244SRatan Gupta         }
10878a07d286SRatan Gupta     });
10888a07d286SRatan Gupta }
1089d4b5443fSEd Tanous 
109058345856SAbhishek Patel inline void updateUserProperties(
109158345856SAbhishek Patel     std::shared_ptr<bmcweb::AsyncResp> asyncResp, const std::string& username,
1092618c14b4SEd Tanous     const std::optional<std::string>& password,
1093618c14b4SEd Tanous     const std::optional<bool>& enabled,
109458345856SAbhishek Patel     const std::optional<std::string>& roleId, const std::optional<bool>& locked,
1095e518ef32SRavi Teja     std::optional<std::vector<std::string>> accountTypes, bool userSelf,
1096e518ef32SRavi Teja     const std::shared_ptr<persistent_data::UserSession>& session)
10971abe55efSEd Tanous {
1098b477fd44SP Dheeraj Srujan Kumar     sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
1099b477fd44SP Dheeraj Srujan Kumar     tempObjPath /= username;
1100b477fd44SP Dheeraj Srujan Kumar     std::string dbusObjectPath(tempObjPath);
11016c51eab1SEd Tanous 
11026c51eab1SEd Tanous     dbus::utility::checkDbusPathExists(
1103e518ef32SRavi Teja         dbusObjectPath,
1104e518ef32SRavi Teja         [dbusObjectPath, username, password, roleId, enabled, locked,
1105e518ef32SRavi Teja          accountTypes(std::move(accountTypes)), userSelf, session,
1106e518ef32SRavi Teja          asyncResp{std::move(asyncResp)}](int rc) {
1107e662eae8SEd Tanous             if (rc <= 0)
11086c51eab1SEd Tanous             {
1109d8a5d5d8SJiaqing Zhao                 messages::resourceNotFound(asyncResp->res, "ManagerAccount",
11106c51eab1SEd Tanous                                            username);
11116c51eab1SEd Tanous                 return;
11126c51eab1SEd Tanous             }
11136c51eab1SEd Tanous 
11146c51eab1SEd Tanous             if (password)
11156c51eab1SEd Tanous             {
11166c51eab1SEd Tanous                 int retval = pamUpdatePassword(username, *password);
11176c51eab1SEd Tanous 
11186c51eab1SEd Tanous                 if (retval == PAM_USER_UNKNOWN)
11196c51eab1SEd Tanous                 {
1120d8a5d5d8SJiaqing Zhao                     messages::resourceNotFound(asyncResp->res, "ManagerAccount",
11216c51eab1SEd Tanous                                                username);
11226c51eab1SEd Tanous                 }
11236c51eab1SEd Tanous                 else if (retval == PAM_AUTHTOK_ERR)
11246c51eab1SEd Tanous                 {
11256c51eab1SEd Tanous                     // If password is invalid
11269bd80831SJason M. Bills                     messages::propertyValueFormatError(asyncResp->res, nullptr,
11279bd80831SJason M. Bills                                                        "Password");
112862598e31SEd Tanous                     BMCWEB_LOG_ERROR("pamUpdatePassword Failed");
11296c51eab1SEd Tanous                 }
11306c51eab1SEd Tanous                 else if (retval != PAM_SUCCESS)
11316c51eab1SEd Tanous                 {
11326c51eab1SEd Tanous                     messages::internalError(asyncResp->res);
11336c51eab1SEd Tanous                     return;
11346c51eab1SEd Tanous                 }
1135e7b1b62bSEd Tanous                 else
1136e7b1b62bSEd Tanous                 {
1137*bd79bce8SPatrick Williams                     // Remove existing sessions of the user when password
1138*bd79bce8SPatrick Williams                     // changed
1139e518ef32SRavi Teja                     persistent_data::SessionStore::getInstance()
1140*bd79bce8SPatrick Williams                         .removeSessionsByUsernameExceptSession(username,
1141*bd79bce8SPatrick Williams                                                                session);
1142e7b1b62bSEd Tanous                     messages::success(asyncResp->res);
1143e7b1b62bSEd Tanous                 }
11446c51eab1SEd Tanous             }
11456c51eab1SEd Tanous 
11466c51eab1SEd Tanous             if (enabled)
11476c51eab1SEd Tanous             {
1148*bd79bce8SPatrick Williams                 setDbusProperty(
1149*bd79bce8SPatrick Williams                     asyncResp, "Enabled", "xyz.openbmc_project.User.Manager",
1150*bd79bce8SPatrick Williams                     dbusObjectPath, "xyz.openbmc_project.User.Attributes",
1151e93abac6SGinu George                     "UserEnabled", *enabled);
11526c51eab1SEd Tanous             }
11536c51eab1SEd Tanous 
11546c51eab1SEd Tanous             if (roleId)
11556c51eab1SEd Tanous             {
11566c51eab1SEd Tanous                 std::string priv = getPrivilegeFromRoleId(*roleId);
11576c51eab1SEd Tanous                 if (priv.empty())
11586c51eab1SEd Tanous                 {
1159e2616cc5SEd Tanous                     messages::propertyValueNotInList(asyncResp->res, true,
1160e2616cc5SEd Tanous                                                      "Locked");
11616c51eab1SEd Tanous                     return;
11626c51eab1SEd Tanous                 }
1163*bd79bce8SPatrick Williams                 setDbusProperty(
1164*bd79bce8SPatrick Williams                     asyncResp, "RoleId", "xyz.openbmc_project.User.Manager",
1165*bd79bce8SPatrick Williams                     dbusObjectPath, "xyz.openbmc_project.User.Attributes",
1166e93abac6SGinu George                     "UserPrivilege", priv);
11676c51eab1SEd Tanous             }
11686c51eab1SEd Tanous 
11696c51eab1SEd Tanous             if (locked)
11706c51eab1SEd Tanous             {
11716c51eab1SEd Tanous                 // admin can unlock the account which is locked by
11726c51eab1SEd Tanous                 // successive authentication failures but admin should
11736c51eab1SEd Tanous                 // not be allowed to lock an account.
11746c51eab1SEd Tanous                 if (*locked)
11756c51eab1SEd Tanous                 {
11766c51eab1SEd Tanous                     messages::propertyValueNotInList(asyncResp->res, "true",
11776c51eab1SEd Tanous                                                      "Locked");
11786c51eab1SEd Tanous                     return;
11796c51eab1SEd Tanous                 }
1180*bd79bce8SPatrick Williams                 setDbusProperty(
1181*bd79bce8SPatrick Williams                     asyncResp, "Locked", "xyz.openbmc_project.User.Manager",
1182*bd79bce8SPatrick Williams                     dbusObjectPath, "xyz.openbmc_project.User.Attributes",
1183e93abac6SGinu George                     "UserLockedForFailedAttempt", *locked);
11846c51eab1SEd Tanous             }
118558345856SAbhishek Patel 
118658345856SAbhishek Patel             if (accountTypes)
118758345856SAbhishek Patel             {
118858345856SAbhishek Patel                 patchAccountTypes(*accountTypes, asyncResp, dbusObjectPath,
118958345856SAbhishek Patel                                   userSelf);
119058345856SAbhishek Patel             }
11916c51eab1SEd Tanous         });
11926c51eab1SEd Tanous }
11936c51eab1SEd Tanous 
11944c7d4d33SEd Tanous inline void handleAccountServiceHead(
11954c7d4d33SEd Tanous     App& app, const crow::Request& req,
11961ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
11976c51eab1SEd Tanous {
11983ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
119945ca1b86SEd Tanous     {
120045ca1b86SEd Tanous         return;
120145ca1b86SEd Tanous     }
12024c7d4d33SEd Tanous     asyncResp->res.addHeader(
12034c7d4d33SEd Tanous         boost::beast::http::field::link,
12044c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/AccountService/AccountService.json>; rel=describedby");
12054c7d4d33SEd Tanous }
12064c7d4d33SEd Tanous 
12074c7d4d33SEd Tanous inline void
12081aa375b8SEd Tanous     getClientCertificates(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
12091aa375b8SEd Tanous                           const nlohmann::json::json_pointer& keyLocation)
12101aa375b8SEd Tanous {
12111aa375b8SEd Tanous     boost::urls::url url(
12121aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates");
12131aa375b8SEd Tanous     std::array<std::string_view, 1> interfaces = {
12141aa375b8SEd Tanous         "xyz.openbmc_project.Certs.Certificate"};
12151aa375b8SEd Tanous     std::string path = "/xyz/openbmc_project/certs/authority/truststore";
12161aa375b8SEd Tanous 
12171aa375b8SEd Tanous     collection_util::getCollectionToKey(asyncResp, url, interfaces, path,
12181aa375b8SEd Tanous                                         keyLocation);
12191aa375b8SEd Tanous }
12201aa375b8SEd Tanous 
12211aa375b8SEd Tanous inline void handleAccountServiceClientCertificatesInstanceHead(
12221aa375b8SEd Tanous     App& app, const crow::Request& req,
12231aa375b8SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
12241aa375b8SEd Tanous     const std::string& /*id*/)
12251aa375b8SEd Tanous {
12261aa375b8SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
12271aa375b8SEd Tanous     {
12281aa375b8SEd Tanous         return;
12291aa375b8SEd Tanous     }
12301aa375b8SEd Tanous 
12311aa375b8SEd Tanous     asyncResp->res.addHeader(
12321aa375b8SEd Tanous         boost::beast::http::field::link,
12331aa375b8SEd Tanous         "</redfish/v1/JsonSchemas/Certificate/Certificate.json>; rel=describedby");
12341aa375b8SEd Tanous }
12351aa375b8SEd Tanous 
12361aa375b8SEd Tanous inline void handleAccountServiceClientCertificatesInstanceGet(
12371aa375b8SEd Tanous     App& app, const crow::Request& req,
12381aa375b8SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, const std::string& id)
12391aa375b8SEd Tanous {
12401aa375b8SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
12411aa375b8SEd Tanous     {
12421aa375b8SEd Tanous         return;
12431aa375b8SEd Tanous     }
12441aa375b8SEd Tanous     BMCWEB_LOG_DEBUG("ClientCertificate Certificate ID={}", id);
12451aa375b8SEd Tanous     const boost::urls::url certURL = boost::urls::format(
12461aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/{}",
12471aa375b8SEd Tanous         id);
12481aa375b8SEd Tanous     std::string objPath =
12491aa375b8SEd Tanous         sdbusplus::message::object_path(certs::authorityObjectPath) / id;
12501aa375b8SEd Tanous     getCertificateProperties(
12511aa375b8SEd Tanous         asyncResp, objPath,
12521aa375b8SEd Tanous         "xyz.openbmc_project.Certs.Manager.Authority.Truststore", id, certURL,
12531aa375b8SEd Tanous         "Client Certificate");
12541aa375b8SEd Tanous }
12551aa375b8SEd Tanous 
12561aa375b8SEd Tanous inline void handleAccountServiceClientCertificatesHead(
12571aa375b8SEd Tanous     App& app, const crow::Request& req,
12581aa375b8SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
12591aa375b8SEd Tanous {
12601aa375b8SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
12611aa375b8SEd Tanous     {
12621aa375b8SEd Tanous         return;
12631aa375b8SEd Tanous     }
12641aa375b8SEd Tanous 
12651aa375b8SEd Tanous     asyncResp->res.addHeader(
12661aa375b8SEd Tanous         boost::beast::http::field::link,
12671aa375b8SEd Tanous         "</redfish/v1/JsonSchemas/CertificateCollection/CertificateCollection.json>; rel=describedby");
12681aa375b8SEd Tanous }
12691aa375b8SEd Tanous 
12701aa375b8SEd Tanous inline void handleAccountServiceClientCertificatesGet(
12711aa375b8SEd Tanous     App& app, const crow::Request& req,
12721aa375b8SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
12731aa375b8SEd Tanous {
12741aa375b8SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
12751aa375b8SEd Tanous     {
12761aa375b8SEd Tanous         return;
12771aa375b8SEd Tanous     }
12781aa375b8SEd Tanous     getClientCertificates(asyncResp, "/Members"_json_pointer);
12791aa375b8SEd Tanous }
12801aa375b8SEd Tanous 
12813ce3688aSEd Tanous using account_service::CertificateMappingAttribute;
12823ce3688aSEd Tanous using persistent_data::MTLSCommonNameParseMode;
12833ce3688aSEd Tanous inline CertificateMappingAttribute
12843ce3688aSEd Tanous     getCertificateMapping(MTLSCommonNameParseMode parse)
12853ce3688aSEd Tanous {
12863ce3688aSEd Tanous     switch (parse)
12873ce3688aSEd Tanous     {
12883ce3688aSEd Tanous         case MTLSCommonNameParseMode::CommonName:
12893ce3688aSEd Tanous         {
12903ce3688aSEd Tanous             return CertificateMappingAttribute::CommonName;
12913ce3688aSEd Tanous         }
12923ce3688aSEd Tanous         break;
12933ce3688aSEd Tanous         case MTLSCommonNameParseMode::Whole:
12943ce3688aSEd Tanous         {
12953ce3688aSEd Tanous             return CertificateMappingAttribute::Whole;
12963ce3688aSEd Tanous         }
12973ce3688aSEd Tanous         break;
12983ce3688aSEd Tanous         case MTLSCommonNameParseMode::UserPrincipalName:
12993ce3688aSEd Tanous         {
13003ce3688aSEd Tanous             return CertificateMappingAttribute::UserPrincipalName;
13013ce3688aSEd Tanous         }
13023ce3688aSEd Tanous         break;
13033ce3688aSEd Tanous 
13043ce3688aSEd Tanous         case MTLSCommonNameParseMode::Meta:
13053ce3688aSEd Tanous         {
13063ce3688aSEd Tanous             if constexpr (BMCWEB_META_TLS_COMMON_NAME_PARSING)
13073ce3688aSEd Tanous             {
13083ce3688aSEd Tanous                 return CertificateMappingAttribute::CommonName;
13093ce3688aSEd Tanous             }
13103ce3688aSEd Tanous         }
13113ce3688aSEd Tanous         break;
13123ce3688aSEd Tanous         default:
13133ce3688aSEd Tanous         {
13143ce3688aSEd Tanous             return CertificateMappingAttribute::Invalid;
13153ce3688aSEd Tanous         }
13163ce3688aSEd Tanous         break;
13173ce3688aSEd Tanous     }
13183ce3688aSEd Tanous }
13193ce3688aSEd Tanous 
13201aa375b8SEd Tanous inline void
13214c7d4d33SEd Tanous     handleAccountServiceGet(App& app, const crow::Request& req,
13224c7d4d33SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
13234c7d4d33SEd Tanous {
1324afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1325afd369c6SJiaqing Zhao     {
1326afd369c6SJiaqing Zhao         return;
1327afd369c6SJiaqing Zhao     }
13283e72c202SNinad Palsule 
13293e72c202SNinad Palsule     if (req.session == nullptr)
13303e72c202SNinad Palsule     {
13313e72c202SNinad Palsule         messages::internalError(asyncResp->res);
13323e72c202SNinad Palsule         return;
13333e72c202SNinad Palsule     }
13343e72c202SNinad Palsule 
1335c1019828SEd Tanous     const persistent_data::AuthConfigMethods& authMethodsConfig =
1336c1019828SEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
1337c1019828SEd Tanous 
1338afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1339afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1340afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/AccountService/AccountService.json>; rel=describedby");
1341afd369c6SJiaqing Zhao 
13421476687dSEd Tanous     nlohmann::json& json = asyncResp->res.jsonValue;
13431476687dSEd Tanous     json["@odata.id"] = "/redfish/v1/AccountService";
1344482a69e7SRavi Teja     json["@odata.type"] = "#AccountService.v1_15_0.AccountService";
13451476687dSEd Tanous     json["Id"] = "AccountService";
13461476687dSEd Tanous     json["Name"] = "Account Service";
13471476687dSEd Tanous     json["Description"] = "Account Service";
13481476687dSEd Tanous     json["ServiceEnabled"] = true;
13491476687dSEd Tanous     json["MaxPasswordLength"] = 20;
13501ef4c342SEd Tanous     json["Accounts"]["@odata.id"] = "/redfish/v1/AccountService/Accounts";
13511476687dSEd Tanous     json["Roles"]["@odata.id"] = "/redfish/v1/AccountService/Roles";
1352482a69e7SRavi Teja     json["HTTPBasicAuth"] = authMethodsConfig.basic
1353482a69e7SRavi Teja                                 ? account_service::BasicAuthState::Enabled
1354482a69e7SRavi Teja                                 : account_service::BasicAuthState::Disabled;
1355482a69e7SRavi Teja 
1356482a69e7SRavi Teja     nlohmann::json::array_t allowed;
1357482a69e7SRavi Teja     allowed.emplace_back(account_service::BasicAuthState::Enabled);
1358482a69e7SRavi Teja     allowed.emplace_back(account_service::BasicAuthState::Disabled);
1359482a69e7SRavi Teja     json["HTTPBasicAuth@AllowableValues"] = std::move(allowed);
1360482a69e7SRavi Teja 
13611aa375b8SEd Tanous     nlohmann::json::object_t clientCertificate;
13621aa375b8SEd Tanous     clientCertificate["Enabled"] = authMethodsConfig.tls;
13633281bcf1SEd Tanous     clientCertificate["RespondToUnauthenticatedClients"] =
13643281bcf1SEd Tanous         !authMethodsConfig.tlsStrict;
13653ce3688aSEd Tanous 
13663ce3688aSEd Tanous     using account_service::CertificateMappingAttribute;
13673ce3688aSEd Tanous 
13683ce3688aSEd Tanous     CertificateMappingAttribute mapping =
13693ce3688aSEd Tanous         getCertificateMapping(authMethodsConfig.mTLSCommonNameParsingMode);
13703ce3688aSEd Tanous     if (mapping == CertificateMappingAttribute::Invalid)
13713ce3688aSEd Tanous     {
13723ce3688aSEd Tanous         messages::internalError(asyncResp->res);
13733ce3688aSEd Tanous     }
13743ce3688aSEd Tanous     else
13753ce3688aSEd Tanous     {
13763ce3688aSEd Tanous         clientCertificate["CertificateMappingAttribute"] = mapping;
13773ce3688aSEd Tanous     }
13781aa375b8SEd Tanous     nlohmann::json::object_t certificates;
13791aa375b8SEd Tanous     certificates["@odata.id"] =
13801aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates";
13811aa375b8SEd Tanous     certificates["@odata.type"] =
13821aa375b8SEd Tanous         "#CertificateCollection.CertificateCollection";
13831aa375b8SEd Tanous     clientCertificate["Certificates"] = std::move(certificates);
13841aa375b8SEd Tanous     json["MultiFactorAuth"]["ClientCertificate"] = std::move(clientCertificate);
13851aa375b8SEd Tanous 
13861aa375b8SEd Tanous     getClientCertificates(
13871aa375b8SEd Tanous         asyncResp,
13881aa375b8SEd Tanous         "/MultiFactorAuth/ClientCertificate/Certificates/Members"_json_pointer);
13891aa375b8SEd Tanous 
13901476687dSEd Tanous     json["Oem"]["OpenBMC"]["@odata.type"] =
13915b5574acSEd Tanous         "#OpenBMCAccountService.v1_0_0.AccountService";
13921476687dSEd Tanous     json["Oem"]["OpenBMC"]["@odata.id"] =
13931476687dSEd Tanous         "/redfish/v1/AccountService#/Oem/OpenBMC";
13941476687dSEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["BasicAuth"] =
13951476687dSEd Tanous         authMethodsConfig.basic;
13961476687dSEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["SessionToken"] =
13971476687dSEd Tanous         authMethodsConfig.sessionToken;
13981ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["XToken"] = authMethodsConfig.xtoken;
13991ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["Cookie"] = authMethodsConfig.cookie;
14001ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["TLS"] = authMethodsConfig.tls;
14011476687dSEd Tanous 
14021ef4c342SEd Tanous     // /redfish/v1/AccountService/LDAP/Certificates is something only
14031ef4c342SEd Tanous     // ConfigureManager can access then only display when the user has
14041ef4c342SEd Tanous     // permissions ConfigureManager
140572048780SAbhishek Patel     Privileges effectiveUserPrivileges =
14063e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
140772048780SAbhishek Patel 
140872048780SAbhishek Patel     if (isOperationAllowedWithPrivileges({{"ConfigureManager"}},
140972048780SAbhishek Patel                                          effectiveUserPrivileges))
141072048780SAbhishek Patel     {
14111ef4c342SEd Tanous         asyncResp->res.jsonValue["LDAP"]["Certificates"]["@odata.id"] =
14121476687dSEd Tanous             "/redfish/v1/AccountService/LDAP/Certificates";
141372048780SAbhishek Patel     }
1414d1bde9e5SKrzysztof Grobelny     sdbusplus::asio::getAllProperties(
1415d1bde9e5SKrzysztof Grobelny         *crow::connections::systemBus, "xyz.openbmc_project.User.Manager",
1416d1bde9e5SKrzysztof Grobelny         "/xyz/openbmc_project/user", "xyz.openbmc_project.User.AccountPolicy",
14175e7e2dc5SEd Tanous         [asyncResp](const boost::system::error_code& ec,
14181ef4c342SEd Tanous                     const dbus::utility::DBusPropertiesMap& propertiesList) {
14193d958bbcSAppaRao Puli             if (ec)
14203d958bbcSAppaRao Puli             {
14213d958bbcSAppaRao Puli                 messages::internalError(asyncResp->res);
14223d958bbcSAppaRao Puli                 return;
14233d958bbcSAppaRao Puli             }
1424d1bde9e5SKrzysztof Grobelny 
142562598e31SEd Tanous             BMCWEB_LOG_DEBUG("Got {} properties for AccountService",
142662598e31SEd Tanous                              propertiesList.size());
1427d1bde9e5SKrzysztof Grobelny 
1428d1bde9e5SKrzysztof Grobelny             const uint8_t* minPasswordLength = nullptr;
1429d1bde9e5SKrzysztof Grobelny             const uint32_t* accountUnlockTimeout = nullptr;
1430d1bde9e5SKrzysztof Grobelny             const uint16_t* maxLoginAttemptBeforeLockout = nullptr;
1431d1bde9e5SKrzysztof Grobelny 
1432d1bde9e5SKrzysztof Grobelny             const bool success = sdbusplus::unpackPropertiesNoThrow(
1433d1bde9e5SKrzysztof Grobelny                 dbus_utils::UnpackErrorPrinter(), propertiesList,
1434d1bde9e5SKrzysztof Grobelny                 "MinPasswordLength", minPasswordLength, "AccountUnlockTimeout",
1435d1bde9e5SKrzysztof Grobelny                 accountUnlockTimeout, "MaxLoginAttemptBeforeLockout",
1436d1bde9e5SKrzysztof Grobelny                 maxLoginAttemptBeforeLockout);
1437d1bde9e5SKrzysztof Grobelny 
1438d1bde9e5SKrzysztof Grobelny             if (!success)
14393d958bbcSAppaRao Puli             {
1440d1bde9e5SKrzysztof Grobelny                 messages::internalError(asyncResp->res);
1441d1bde9e5SKrzysztof Grobelny                 return;
14423d958bbcSAppaRao Puli             }
1443d1bde9e5SKrzysztof Grobelny 
1444d1bde9e5SKrzysztof Grobelny             if (minPasswordLength != nullptr)
14453d958bbcSAppaRao Puli             {
1446*bd79bce8SPatrick Williams                 asyncResp->res.jsonValue["MinPasswordLength"] =
1447*bd79bce8SPatrick Williams                     *minPasswordLength;
14483d958bbcSAppaRao Puli             }
1449d1bde9e5SKrzysztof Grobelny 
1450d1bde9e5SKrzysztof Grobelny             if (accountUnlockTimeout != nullptr)
14513d958bbcSAppaRao Puli             {
1452d1bde9e5SKrzysztof Grobelny                 asyncResp->res.jsonValue["AccountLockoutDuration"] =
1453d1bde9e5SKrzysztof Grobelny                     *accountUnlockTimeout;
1454d1bde9e5SKrzysztof Grobelny             }
1455d1bde9e5SKrzysztof Grobelny 
1456d1bde9e5SKrzysztof Grobelny             if (maxLoginAttemptBeforeLockout != nullptr)
14573d958bbcSAppaRao Puli             {
1458002d39b4SEd Tanous                 asyncResp->res.jsonValue["AccountLockoutThreshold"] =
1459d1bde9e5SKrzysztof Grobelny                     *maxLoginAttemptBeforeLockout;
14603d958bbcSAppaRao Puli             }
1461d1bde9e5SKrzysztof Grobelny         });
14626973a582SRatan Gupta 
146302cad96eSEd Tanous     auto callback = [asyncResp](bool success, const LDAPConfigData& confData,
1464ab828d7cSRatan Gupta                                 const std::string& ldapType) {
1465cb13a392SEd Tanous         if (!success)
1466cb13a392SEd Tanous         {
1467cb13a392SEd Tanous             return;
1468cb13a392SEd Tanous         }
1469002d39b4SEd Tanous         parseLDAPConfigData(asyncResp->res.jsonValue, confData, ldapType);
1470ab828d7cSRatan Gupta     };
1471ab828d7cSRatan Gupta 
1472ab828d7cSRatan Gupta     getLDAPConfigData("LDAP", callback);
1473ab828d7cSRatan Gupta     getLDAPConfigData("ActiveDirectory", callback);
14741ef4c342SEd Tanous }
14756973a582SRatan Gupta 
1476*bd79bce8SPatrick Williams inline void handleCertificateMappingAttributePatch(
1477*bd79bce8SPatrick Williams     crow::Response& res, const std::string& certMapAttribute)
14783ce3688aSEd Tanous {
14793ce3688aSEd Tanous     MTLSCommonNameParseMode parseMode =
14803ce3688aSEd Tanous         persistent_data::getMTLSCommonNameParseMode(certMapAttribute);
14813ce3688aSEd Tanous     if (parseMode == MTLSCommonNameParseMode::Invalid)
14823ce3688aSEd Tanous     {
14833ce3688aSEd Tanous         messages::propertyValueNotInList(res, "CertificateMappingAttribute",
14843ce3688aSEd Tanous                                          certMapAttribute);
14853ce3688aSEd Tanous         return;
14863ce3688aSEd Tanous     }
14873ce3688aSEd Tanous 
14883ce3688aSEd Tanous     persistent_data::AuthConfigMethods& authMethodsConfig =
14893ce3688aSEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
14903ce3688aSEd Tanous     authMethodsConfig.mTLSCommonNameParsingMode = parseMode;
14913ce3688aSEd Tanous }
14923ce3688aSEd Tanous 
14933281bcf1SEd Tanous inline void handleRespondToUnauthenticatedClientsPatch(
14943281bcf1SEd Tanous     App& app, const crow::Request& req, crow::Response& res,
14953281bcf1SEd Tanous     bool respondToUnauthenticatedClients)
14963281bcf1SEd Tanous {
14973281bcf1SEd Tanous     if (req.session != nullptr)
14983281bcf1SEd Tanous     {
14993281bcf1SEd Tanous         // Sanity check.  If the user isn't currently authenticated with mutual
15003281bcf1SEd Tanous         // TLS, they very likely are about to permanently lock themselves out.
15013281bcf1SEd Tanous         // Make sure they're using mutual TLS before allowing locking.
15023281bcf1SEd Tanous         if (req.session->sessionType != persistent_data::SessionType::MutualTLS)
15033281bcf1SEd Tanous         {
15043281bcf1SEd Tanous             messages::propertyValueExternalConflict(
15053281bcf1SEd Tanous                 res,
15063281bcf1SEd Tanous                 "MultiFactorAuth/ClientCertificate/RespondToUnauthenticatedClients",
15073281bcf1SEd Tanous                 respondToUnauthenticatedClients);
15083281bcf1SEd Tanous             return;
15093281bcf1SEd Tanous         }
15103281bcf1SEd Tanous     }
15113281bcf1SEd Tanous 
15123281bcf1SEd Tanous     persistent_data::AuthConfigMethods& authMethodsConfig =
15133281bcf1SEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
15143281bcf1SEd Tanous 
15153281bcf1SEd Tanous     // Change the settings
15163281bcf1SEd Tanous     authMethodsConfig.tlsStrict = !respondToUnauthenticatedClients;
15173281bcf1SEd Tanous 
15183281bcf1SEd Tanous     // Write settings to disk
15193281bcf1SEd Tanous     persistent_data::getConfig().writeData();
15203281bcf1SEd Tanous 
15213281bcf1SEd Tanous     // Trigger a reload, to apply the new settings to new connections
15223281bcf1SEd Tanous     app.loadCertificate();
15233281bcf1SEd Tanous }
15243281bcf1SEd Tanous 
15251ef4c342SEd Tanous inline void handleAccountServicePatch(
15261ef4c342SEd Tanous     App& app, const crow::Request& req,
15271ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
15281ef4c342SEd Tanous {
15293ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
153045ca1b86SEd Tanous     {
153145ca1b86SEd Tanous         return;
153245ca1b86SEd Tanous     }
1533f5ffd806SEd Tanous     std::optional<uint32_t> unlockTimeout;
1534f5ffd806SEd Tanous     std::optional<uint16_t> lockoutThreshold;
1535ef73ad0dSPaul Fertser     std::optional<uint8_t> minPasswordLength;
1536f5ffd806SEd Tanous     std::optional<uint16_t> maxPasswordLength;
153710cb44f3SEd Tanous     LdapPatchParams ldapObject;
15383ce3688aSEd Tanous     std::optional<std::string> certificateMappingAttribute;
15393281bcf1SEd Tanous     std::optional<bool> respondToUnauthenticatedClients;
154010cb44f3SEd Tanous     LdapPatchParams activeDirectoryObject;
1541c1019828SEd Tanous     AuthMethods auth;
1542482a69e7SRavi Teja     std::optional<std::string> httpBasicAuth;
15433ce3688aSEd Tanous 
1544c1019828SEd Tanous     // clang-format off
154515ed6780SWilly Tu     if (!json_util::readJsonPatch(
1546c1019828SEd Tanous             req, asyncResp->res,
1547c1019828SEd Tanous             "AccountLockoutDuration", unlockTimeout,
1548c1019828SEd Tanous             "AccountLockoutThreshold", lockoutThreshold,
154910cb44f3SEd Tanous             "ActiveDirectory/Authentication/AuthenticationType", activeDirectoryObject.authType,
155010cb44f3SEd Tanous             "ActiveDirectory/Authentication/Password", activeDirectoryObject.password,
155110cb44f3SEd Tanous             "ActiveDirectory/Authentication/Username", activeDirectoryObject.userName,
155210cb44f3SEd Tanous             "ActiveDirectory/LDAPService/SearchSettings/BaseDistinguishedNames", activeDirectoryObject.baseDNList,
155310cb44f3SEd Tanous             "ActiveDirectory/LDAPService/SearchSettings/GroupsAttribute", activeDirectoryObject.groupsAttribute,
155410cb44f3SEd Tanous             "ActiveDirectory/LDAPService/SearchSettings/UsernameAttribute", activeDirectoryObject.userNameAttribute,
155510cb44f3SEd Tanous             "ActiveDirectory/RemoteRoleMapping", activeDirectoryObject.remoteRoleMapData,
155610cb44f3SEd Tanous             "ActiveDirectory/ServiceAddresses", activeDirectoryObject.serviceAddressList,
155710cb44f3SEd Tanous             "ActiveDirectory/ServiceEnabled", activeDirectoryObject.serviceEnabled,
15583ce3688aSEd Tanous             "MultiFactorAuth/ClientCertificate/CertificateMappingAttribute", certificateMappingAttribute,
15593281bcf1SEd Tanous             "MultiFactorAuth/ClientCertificate/RespondToUnauthenticatedClients", respondToUnauthenticatedClients,
156010cb44f3SEd Tanous             "LDAP/Authentication/AuthenticationType", ldapObject.authType,
156110cb44f3SEd Tanous             "LDAP/Authentication/Password", ldapObject.password,
156210cb44f3SEd Tanous             "LDAP/Authentication/Username", ldapObject.userName,
156310cb44f3SEd Tanous             "LDAP/LDAPService/SearchSettings/BaseDistinguishedNames", ldapObject.baseDNList,
156410cb44f3SEd Tanous             "LDAP/LDAPService/SearchSettings/GroupsAttribute", ldapObject.groupsAttribute,
156510cb44f3SEd Tanous             "LDAP/LDAPService/SearchSettings/UsernameAttribute", ldapObject.userNameAttribute,
156610cb44f3SEd Tanous             "LDAP/RemoteRoleMapping", ldapObject.remoteRoleMapData,
156710cb44f3SEd Tanous             "LDAP/ServiceAddresses", ldapObject.serviceAddressList,
156810cb44f3SEd Tanous             "LDAP/ServiceEnabled", ldapObject.serviceEnabled,
1569c1019828SEd Tanous             "MaxPasswordLength", maxPasswordLength,
1570c1019828SEd Tanous             "MinPasswordLength", minPasswordLength,
1571c1019828SEd Tanous             "Oem/OpenBMC/AuthMethods/BasicAuth", auth.basicAuth,
1572c1019828SEd Tanous             "Oem/OpenBMC/AuthMethods/Cookie", auth.cookie,
1573c1019828SEd Tanous             "Oem/OpenBMC/AuthMethods/SessionToken", auth.sessionToken,
157410cb44f3SEd Tanous             "Oem/OpenBMC/AuthMethods/TLS", auth.tls,
1575482a69e7SRavi Teja             "Oem/OpenBMC/AuthMethods/XToken", auth.xToken,
1576482a69e7SRavi Teja             "HTTPBasicAuth", httpBasicAuth))
1577f5ffd806SEd Tanous     {
1578f5ffd806SEd Tanous         return;
1579f5ffd806SEd Tanous     }
1580c1019828SEd Tanous     // clang-format on
1581f5ffd806SEd Tanous 
1582482a69e7SRavi Teja     if (httpBasicAuth)
1583482a69e7SRavi Teja     {
1584482a69e7SRavi Teja         if (*httpBasicAuth == "Enabled")
1585482a69e7SRavi Teja         {
1586482a69e7SRavi Teja             auth.basicAuth = true;
1587482a69e7SRavi Teja         }
1588482a69e7SRavi Teja         else if (*httpBasicAuth == "Disabled")
1589482a69e7SRavi Teja         {
1590482a69e7SRavi Teja             auth.basicAuth = false;
1591482a69e7SRavi Teja         }
1592482a69e7SRavi Teja         else
1593482a69e7SRavi Teja         {
1594482a69e7SRavi Teja             messages::propertyValueNotInList(asyncResp->res, "HttpBasicAuth",
1595482a69e7SRavi Teja                                              *httpBasicAuth);
1596482a69e7SRavi Teja         }
1597482a69e7SRavi Teja     }
1598482a69e7SRavi Teja 
15993281bcf1SEd Tanous     if (respondToUnauthenticatedClients)
16003281bcf1SEd Tanous     {
16013281bcf1SEd Tanous         handleRespondToUnauthenticatedClientsPatch(
16023281bcf1SEd Tanous             app, req, asyncResp->res, *respondToUnauthenticatedClients);
16033281bcf1SEd Tanous     }
16043281bcf1SEd Tanous 
16053ce3688aSEd Tanous     if (certificateMappingAttribute)
16063ce3688aSEd Tanous     {
16073ce3688aSEd Tanous         handleCertificateMappingAttributePatch(asyncResp->res,
16083ce3688aSEd Tanous                                                *certificateMappingAttribute);
16093ce3688aSEd Tanous     }
16103ce3688aSEd Tanous 
1611f5ffd806SEd Tanous     if (minPasswordLength)
1612f5ffd806SEd Tanous     {
1613d02aad39SEd Tanous         setDbusProperty(
1614e93abac6SGinu George             asyncResp, "MinPasswordLength", "xyz.openbmc_project.User.Manager",
1615d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
16169ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy", "MinPasswordLength",
1617e93abac6SGinu George             *minPasswordLength);
1618f5ffd806SEd Tanous     }
1619f5ffd806SEd Tanous 
1620f5ffd806SEd Tanous     if (maxPasswordLength)
1621f5ffd806SEd Tanous     {
16221ef4c342SEd Tanous         messages::propertyNotWritable(asyncResp->res, "MaxPasswordLength");
1623f5ffd806SEd Tanous     }
1624f5ffd806SEd Tanous 
162510cb44f3SEd Tanous     handleLDAPPatch(std::move(activeDirectoryObject), asyncResp,
162610cb44f3SEd Tanous                     "ActiveDirectory");
162710cb44f3SEd Tanous     handleLDAPPatch(std::move(ldapObject), asyncResp, "LDAP");
1628f5ffd806SEd Tanous 
1629c1019828SEd Tanous     handleAuthMethodsPatch(asyncResp, auth);
1630f5ffd806SEd Tanous 
1631f5ffd806SEd Tanous     if (unlockTimeout)
1632f5ffd806SEd Tanous     {
1633d02aad39SEd Tanous         setDbusProperty(
1634e93abac6SGinu George             asyncResp, "AccountLockoutDuration",
1635e93abac6SGinu George             "xyz.openbmc_project.User.Manager",
1636d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
16379ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy", "AccountUnlockTimeout",
1638e93abac6SGinu George             *unlockTimeout);
1639f5ffd806SEd Tanous     }
1640f5ffd806SEd Tanous     if (lockoutThreshold)
1641f5ffd806SEd Tanous     {
1642d02aad39SEd Tanous         setDbusProperty(
1643e93abac6SGinu George             asyncResp, "AccountLockoutThreshold",
1644e93abac6SGinu George             "xyz.openbmc_project.User.Manager",
1645d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
16469ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy",
1647e93abac6SGinu George             "MaxLoginAttemptBeforeLockout", *lockoutThreshold);
1648f5ffd806SEd Tanous     }
16491ef4c342SEd Tanous }
1650f5ffd806SEd Tanous 
16514c7d4d33SEd Tanous inline void handleAccountCollectionHead(
16521ef4c342SEd Tanous     App& app, const crow::Request& req,
16531ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
16541ef4c342SEd Tanous {
16553ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
165645ca1b86SEd Tanous     {
165745ca1b86SEd Tanous         return;
165845ca1b86SEd Tanous     }
16594c7d4d33SEd Tanous     asyncResp->res.addHeader(
16604c7d4d33SEd Tanous         boost::beast::http::field::link,
16614c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/ManagerAccountCollection.json>; rel=describedby");
16624c7d4d33SEd Tanous }
16634c7d4d33SEd Tanous 
16644c7d4d33SEd Tanous inline void handleAccountCollectionGet(
16654c7d4d33SEd Tanous     App& app, const crow::Request& req,
16664c7d4d33SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
16674c7d4d33SEd Tanous {
1668afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1669afd369c6SJiaqing Zhao     {
1670afd369c6SJiaqing Zhao         return;
1671afd369c6SJiaqing Zhao     }
16723e72c202SNinad Palsule 
16733e72c202SNinad Palsule     if (req.session == nullptr)
16743e72c202SNinad Palsule     {
16753e72c202SNinad Palsule         messages::internalError(asyncResp->res);
16763e72c202SNinad Palsule         return;
16773e72c202SNinad Palsule     }
16783e72c202SNinad Palsule 
1679afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1680afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1681afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/ManagerAccountCollection.json>; rel=describedby");
16821476687dSEd Tanous 
16831476687dSEd Tanous     asyncResp->res.jsonValue["@odata.id"] =
16841476687dSEd Tanous         "/redfish/v1/AccountService/Accounts";
16851ef4c342SEd Tanous     asyncResp->res.jsonValue["@odata.type"] = "#ManagerAccountCollection."
16861476687dSEd Tanous                                               "ManagerAccountCollection";
16871476687dSEd Tanous     asyncResp->res.jsonValue["Name"] = "Accounts Collection";
16881476687dSEd Tanous     asyncResp->res.jsonValue["Description"] = "BMC User Accounts";
16890f74e643SEd Tanous 
16906c51eab1SEd Tanous     Privileges effectiveUserPrivileges =
16913e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
16926c51eab1SEd Tanous 
1693f5e29f33SJunLin Chen     std::string thisUser;
1694f5e29f33SJunLin Chen     if (req.session)
1695f5e29f33SJunLin Chen     {
1696f5e29f33SJunLin Chen         thisUser = req.session->username;
1697f5e29f33SJunLin Chen     }
16985eb468daSGeorge Liu     sdbusplus::message::object_path path("/xyz/openbmc_project/user");
16995eb468daSGeorge Liu     dbus::utility::getManagedObjects(
17005eb468daSGeorge Liu         "xyz.openbmc_project.User.Manager", path,
1701cef1ddfbSEd Tanous         [asyncResp, thisUser, effectiveUserPrivileges](
17025e7e2dc5SEd Tanous             const boost::system::error_code& ec,
1703711ac7a9SEd Tanous             const dbus::utility::ManagedObjectType& users) {
1704b9b2e0b2SEd Tanous             if (ec)
1705b9b2e0b2SEd Tanous             {
1706f12894f8SJason M. Bills                 messages::internalError(asyncResp->res);
1707b9b2e0b2SEd Tanous                 return;
1708b9b2e0b2SEd Tanous             }
1709b9b2e0b2SEd Tanous 
1710cef1ddfbSEd Tanous             bool userCanSeeAllAccounts =
1711002d39b4SEd Tanous                 effectiveUserPrivileges.isSupersetOf({"ConfigureUsers"});
1712cef1ddfbSEd Tanous 
1713cef1ddfbSEd Tanous             bool userCanSeeSelf =
1714002d39b4SEd Tanous                 effectiveUserPrivileges.isSupersetOf({"ConfigureSelf"});
1715cef1ddfbSEd Tanous 
1716002d39b4SEd Tanous             nlohmann::json& memberArray = asyncResp->res.jsonValue["Members"];
1717b9b2e0b2SEd Tanous             memberArray = nlohmann::json::array();
1718b9b2e0b2SEd Tanous 
17199eb808c1SEd Tanous             for (const auto& userpath : users)
1720b9b2e0b2SEd Tanous             {
17212dfd18efSEd Tanous                 std::string user = userpath.first.filename();
17222dfd18efSEd Tanous                 if (user.empty())
1723b9b2e0b2SEd Tanous                 {
17242dfd18efSEd Tanous                     messages::internalError(asyncResp->res);
172562598e31SEd Tanous                     BMCWEB_LOG_ERROR("Invalid firmware ID");
17262dfd18efSEd Tanous 
17272dfd18efSEd Tanous                     return;
1728b9b2e0b2SEd Tanous                 }
1729f365910cSGunnar Mills 
1730f365910cSGunnar Mills                 // As clarified by Redfish here:
1731f365910cSGunnar Mills                 // https://redfishforum.com/thread/281/manageraccountcollection-change-allows-account-enumeration
17326c51eab1SEd Tanous                 // Users without ConfigureUsers, only see their own
17336c51eab1SEd Tanous                 // account. Users with ConfigureUsers, see all
17346c51eab1SEd Tanous                 // accounts.
1735*bd79bce8SPatrick Williams                 if (userCanSeeAllAccounts ||
1736*bd79bce8SPatrick Williams                     (thisUser == user && userCanSeeSelf))
1737f365910cSGunnar Mills                 {
17381476687dSEd Tanous                     nlohmann::json::object_t member;
17393b32780dSEd Tanous                     member["@odata.id"] = boost::urls::format(
17403b32780dSEd Tanous                         "/redfish/v1/AccountService/Accounts/{}", user);
1741b2ba3072SPatrick Williams                     memberArray.emplace_back(std::move(member));
1742b9b2e0b2SEd Tanous                 }
1743f365910cSGunnar Mills             }
1744*bd79bce8SPatrick Williams             asyncResp->res.jsonValue["Members@odata.count"] =
1745*bd79bce8SPatrick Williams                 memberArray.size();
17465eb468daSGeorge Liu         });
17471ef4c342SEd Tanous }
17486c51eab1SEd Tanous 
174997e90da3SNinad Palsule inline void processAfterCreateUser(
175097e90da3SNinad Palsule     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
175197e90da3SNinad Palsule     const std::string& username, const std::string& password,
175297e90da3SNinad Palsule     const boost::system::error_code& ec, sdbusplus::message_t& m)
175397e90da3SNinad Palsule {
175497e90da3SNinad Palsule     if (ec)
175597e90da3SNinad Palsule     {
175697e90da3SNinad Palsule         userErrorMessageHandler(m.get_error(), asyncResp, username, "");
175797e90da3SNinad Palsule         return;
175897e90da3SNinad Palsule     }
175997e90da3SNinad Palsule 
176097e90da3SNinad Palsule     if (pamUpdatePassword(username, password) != PAM_SUCCESS)
176197e90da3SNinad Palsule     {
176297e90da3SNinad Palsule         // At this point we have a user that's been
176397e90da3SNinad Palsule         // created, but the password set
176497e90da3SNinad Palsule         // failed.Something is wrong, so delete the user
176597e90da3SNinad Palsule         // that we've already created
176697e90da3SNinad Palsule         sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
176797e90da3SNinad Palsule         tempObjPath /= username;
176897e90da3SNinad Palsule         const std::string userPath(tempObjPath);
176997e90da3SNinad Palsule 
177097e90da3SNinad Palsule         crow::connections::systemBus->async_method_call(
177197e90da3SNinad Palsule             [asyncResp, password](const boost::system::error_code& ec3) {
177297e90da3SNinad Palsule                 if (ec3)
177397e90da3SNinad Palsule                 {
177497e90da3SNinad Palsule                     messages::internalError(asyncResp->res);
177597e90da3SNinad Palsule                     return;
177697e90da3SNinad Palsule                 }
177797e90da3SNinad Palsule 
177897e90da3SNinad Palsule                 // If password is invalid
17799bd80831SJason M. Bills                 messages::propertyValueFormatError(asyncResp->res, nullptr,
178097e90da3SNinad Palsule                                                    "Password");
178197e90da3SNinad Palsule             },
178297e90da3SNinad Palsule             "xyz.openbmc_project.User.Manager", userPath,
178397e90da3SNinad Palsule             "xyz.openbmc_project.Object.Delete", "Delete");
178497e90da3SNinad Palsule 
178562598e31SEd Tanous         BMCWEB_LOG_ERROR("pamUpdatePassword Failed");
178697e90da3SNinad Palsule         return;
178797e90da3SNinad Palsule     }
178897e90da3SNinad Palsule 
178997e90da3SNinad Palsule     messages::created(asyncResp->res);
179097e90da3SNinad Palsule     asyncResp->res.addHeader("Location",
179197e90da3SNinad Palsule                              "/redfish/v1/AccountService/Accounts/" + username);
179297e90da3SNinad Palsule }
179397e90da3SNinad Palsule 
179497e90da3SNinad Palsule inline void processAfterGetAllGroups(
179597e90da3SNinad Palsule     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
179697e90da3SNinad Palsule     const std::string& username, const std::string& password,
1797e01d0c36SEd Tanous     const std::string& roleId, bool enabled,
17989ba73934SNinad Palsule     std::optional<std::vector<std::string>> accountTypes,
179997e90da3SNinad Palsule     const std::vector<std::string>& allGroupsList)
180097e90da3SNinad Palsule {
18013e72c202SNinad Palsule     std::vector<std::string> userGroups;
18029ba73934SNinad Palsule     std::vector<std::string> accountTypeUserGroups;
18039ba73934SNinad Palsule 
18049ba73934SNinad Palsule     // If user specified account types then convert them to unix user groups
18059ba73934SNinad Palsule     if (accountTypes)
18069ba73934SNinad Palsule     {
18079ba73934SNinad Palsule         if (!getUserGroupFromAccountType(asyncResp->res, *accountTypes,
18089ba73934SNinad Palsule                                          accountTypeUserGroups))
18099ba73934SNinad Palsule         {
18109ba73934SNinad Palsule             // Problem in mapping Account Types to User Groups, Error already
18119ba73934SNinad Palsule             // logged.
18129ba73934SNinad Palsule             return;
18139ba73934SNinad Palsule         }
18149ba73934SNinad Palsule     }
18159ba73934SNinad Palsule 
18163e72c202SNinad Palsule     for (const auto& grp : allGroupsList)
18173e72c202SNinad Palsule     {
18189ba73934SNinad Palsule         // If user specified the account type then only accept groups which are
18199ba73934SNinad Palsule         // in the account types group list.
18209ba73934SNinad Palsule         if (!accountTypeUserGroups.empty())
18219ba73934SNinad Palsule         {
18229ba73934SNinad Palsule             bool found = false;
18239ba73934SNinad Palsule             for (const auto& grp1 : accountTypeUserGroups)
18249ba73934SNinad Palsule             {
18259ba73934SNinad Palsule                 if (grp == grp1)
18269ba73934SNinad Palsule                 {
18279ba73934SNinad Palsule                     found = true;
18289ba73934SNinad Palsule                     break;
18299ba73934SNinad Palsule                 }
18309ba73934SNinad Palsule             }
18319ba73934SNinad Palsule             if (!found)
18329ba73934SNinad Palsule             {
18339ba73934SNinad Palsule                 continue;
18349ba73934SNinad Palsule             }
18359ba73934SNinad Palsule         }
18369ba73934SNinad Palsule 
18373e72c202SNinad Palsule         // Console access is provided to the user who is a member of
18383e72c202SNinad Palsule         // hostconsole group and has a administrator role. So, set
18393e72c202SNinad Palsule         // hostconsole group only for the administrator.
18409ba73934SNinad Palsule         if ((grp == "hostconsole") && (roleId != "priv-admin"))
18413e72c202SNinad Palsule         {
18429ba73934SNinad Palsule             if (!accountTypeUserGroups.empty())
18439ba73934SNinad Palsule             {
184462598e31SEd Tanous                 BMCWEB_LOG_ERROR(
184562598e31SEd Tanous                     "Only administrator can get HostConsole access");
18469ba73934SNinad Palsule                 asyncResp->res.result(boost::beast::http::status::bad_request);
18479ba73934SNinad Palsule                 return;
18489ba73934SNinad Palsule             }
18499ba73934SNinad Palsule             continue;
18509ba73934SNinad Palsule         }
18513e72c202SNinad Palsule         userGroups.emplace_back(grp);
18523e72c202SNinad Palsule     }
18539ba73934SNinad Palsule 
18549ba73934SNinad Palsule     // Make sure user specified groups are valid. This is internal error because
18559ba73934SNinad Palsule     // it some inconsistencies between user manager and bmcweb.
18569ba73934SNinad Palsule     if (!accountTypeUserGroups.empty() &&
18579ba73934SNinad Palsule         accountTypeUserGroups.size() != userGroups.size())
18589ba73934SNinad Palsule     {
18599ba73934SNinad Palsule         messages::internalError(asyncResp->res);
18609ba73934SNinad Palsule         return;
18613e72c202SNinad Palsule     }
186297e90da3SNinad Palsule     crow::connections::systemBus->async_method_call(
186397e90da3SNinad Palsule         [asyncResp, username, password](const boost::system::error_code& ec2,
186497e90da3SNinad Palsule                                         sdbusplus::message_t& m) {
186597e90da3SNinad Palsule             processAfterCreateUser(asyncResp, username, password, ec2, m);
186697e90da3SNinad Palsule         },
186797e90da3SNinad Palsule         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
18683e72c202SNinad Palsule         "xyz.openbmc_project.User.Manager", "CreateUser", username, userGroups,
1869e01d0c36SEd Tanous         roleId, enabled);
187097e90da3SNinad Palsule }
187197e90da3SNinad Palsule 
18721ef4c342SEd Tanous inline void handleAccountCollectionPost(
18731ef4c342SEd Tanous     App& app, const crow::Request& req,
18741ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
18751ef4c342SEd Tanous {
18763ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
187745ca1b86SEd Tanous     {
187845ca1b86SEd Tanous         return;
187945ca1b86SEd Tanous     }
18809712f8acSEd Tanous     std::string username;
18819712f8acSEd Tanous     std::string password;
1882e01d0c36SEd Tanous     std::optional<std::string> roleIdJson;
1883e01d0c36SEd Tanous     std::optional<bool> enabledJson;
18849ba73934SNinad Palsule     std::optional<std::vector<std::string>> accountTypes;
1885*bd79bce8SPatrick Williams     if (!json_util::readJsonPatch(
1886*bd79bce8SPatrick Williams             req, asyncResp->res, "UserName", username, "Password", password,
1887*bd79bce8SPatrick Williams             "RoleId", roleIdJson, "Enabled", enabledJson, "AccountTypes",
1888e01d0c36SEd Tanous             accountTypes))
188904ae99ecSEd Tanous     {
189004ae99ecSEd Tanous         return;
189104ae99ecSEd Tanous     }
189204ae99ecSEd Tanous 
1893e01d0c36SEd Tanous     std::string roleId = roleIdJson.value_or("User");
1894e01d0c36SEd Tanous     std::string priv = getPrivilegeFromRoleId(roleId);
189584e12cb7SAppaRao Puli     if (priv.empty())
189604ae99ecSEd Tanous     {
1897e01d0c36SEd Tanous         messages::propertyValueNotInList(asyncResp->res, roleId, "RoleId");
189804ae99ecSEd Tanous         return;
189904ae99ecSEd Tanous     }
19009712f8acSEd Tanous     roleId = priv;
190104ae99ecSEd Tanous 
1902e01d0c36SEd Tanous     bool enabled = enabledJson.value_or(true);
1903e01d0c36SEd Tanous 
1904599c71d8SAyushi Smriti     // Reading AllGroups property
19051e1e598dSJonathan Doman     sdbusplus::asio::getProperty<std::vector<std::string>>(
19061ef4c342SEd Tanous         *crow::connections::systemBus, "xyz.openbmc_project.User.Manager",
19071ef4c342SEd Tanous         "/xyz/openbmc_project/user", "xyz.openbmc_project.User.Manager",
19081ef4c342SEd Tanous         "AllGroups",
19099ba73934SNinad Palsule         [asyncResp, username, password{std::move(password)}, roleId, enabled,
19109ba73934SNinad Palsule          accountTypes](const boost::system::error_code& ec,
19111e1e598dSJonathan Doman                        const std::vector<std::string>& allGroupsList) {
1912599c71d8SAyushi Smriti             if (ec)
1913599c71d8SAyushi Smriti             {
191462598e31SEd Tanous                 BMCWEB_LOG_DEBUG("ERROR with async_method_call");
1915599c71d8SAyushi Smriti                 messages::internalError(asyncResp->res);
1916599c71d8SAyushi Smriti                 return;
1917599c71d8SAyushi Smriti             }
1918599c71d8SAyushi Smriti 
19191e1e598dSJonathan Doman             if (allGroupsList.empty())
1920599c71d8SAyushi Smriti             {
1921599c71d8SAyushi Smriti                 messages::internalError(asyncResp->res);
1922599c71d8SAyushi Smriti                 return;
1923599c71d8SAyushi Smriti             }
1924599c71d8SAyushi Smriti 
1925*bd79bce8SPatrick Williams             processAfterGetAllGroups(asyncResp, username, password, roleId,
1926*bd79bce8SPatrick Williams                                      enabled, accountTypes, allGroupsList);
19271e1e598dSJonathan Doman         });
19281ef4c342SEd Tanous }
1929b9b2e0b2SEd Tanous 
19301ef4c342SEd Tanous inline void
19314c7d4d33SEd Tanous     handleAccountHead(App& app, const crow::Request& req,
19326c51eab1SEd Tanous                       const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
19334c7d4d33SEd Tanous                       const std::string& /*accountName*/)
19341ef4c342SEd Tanous {
19353ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
193645ca1b86SEd Tanous     {
193745ca1b86SEd Tanous         return;
193845ca1b86SEd Tanous     }
19394c7d4d33SEd Tanous     asyncResp->res.addHeader(
19404c7d4d33SEd Tanous         boost::beast::http::field::link,
19414c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/ManagerAccount/ManagerAccount.json>; rel=describedby");
19424c7d4d33SEd Tanous }
1943afd369c6SJiaqing Zhao 
19444c7d4d33SEd Tanous inline void
19454c7d4d33SEd Tanous     handleAccountGet(App& app, const crow::Request& req,
19464c7d4d33SEd Tanous                      const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
19474c7d4d33SEd Tanous                      const std::string& accountName)
19484c7d4d33SEd Tanous {
1949afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1950afd369c6SJiaqing Zhao     {
1951afd369c6SJiaqing Zhao         return;
1952afd369c6SJiaqing Zhao     }
1953afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1954afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1955afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/ManagerAccount/ManagerAccount.json>; rel=describedby");
1956afd369c6SJiaqing Zhao 
195725b54dbaSEd Tanous     if constexpr (BMCWEB_INSECURE_DISABLE_AUTH)
195825b54dbaSEd Tanous     {
1959031514fbSJunLin Chen         // If authentication is disabled, there are no user accounts
196025b54dbaSEd Tanous         messages::resourceNotFound(asyncResp->res, "ManagerAccount",
196125b54dbaSEd Tanous                                    accountName);
1962031514fbSJunLin Chen         return;
196325b54dbaSEd Tanous     }
1964afd369c6SJiaqing Zhao 
1965031514fbSJunLin Chen     if (req.session == nullptr)
1966031514fbSJunLin Chen     {
1967031514fbSJunLin Chen         messages::internalError(asyncResp->res);
1968031514fbSJunLin Chen         return;
1969031514fbSJunLin Chen     }
19706c51eab1SEd Tanous     if (req.session->username != accountName)
1971b9b2e0b2SEd Tanous     {
19726c51eab1SEd Tanous         // At this point we've determined that the user is trying to
19731ef4c342SEd Tanous         // modify a user that isn't them.  We need to verify that they
19741ef4c342SEd Tanous         // have permissions to modify other users, so re-run the auth
19751ef4c342SEd Tanous         // check with the same permissions, minus ConfigureSelf.
19766c51eab1SEd Tanous         Privileges effectiveUserPrivileges =
19773e72c202SNinad Palsule             redfish::getUserPrivileges(*req.session);
19781ef4c342SEd Tanous         Privileges requiredPermissionsToChangeNonSelf = {"ConfigureUsers",
19791ef4c342SEd Tanous                                                          "ConfigureManager"};
19806c51eab1SEd Tanous         if (!effectiveUserPrivileges.isSupersetOf(
19816c51eab1SEd Tanous                 requiredPermissionsToChangeNonSelf))
1982900f9497SJoseph Reynolds         {
198362598e31SEd Tanous             BMCWEB_LOG_DEBUG("GET Account denied access");
1984900f9497SJoseph Reynolds             messages::insufficientPrivilege(asyncResp->res);
1985900f9497SJoseph Reynolds             return;
1986900f9497SJoseph Reynolds         }
1987900f9497SJoseph Reynolds     }
1988900f9497SJoseph Reynolds 
19895eb468daSGeorge Liu     sdbusplus::message::object_path path("/xyz/openbmc_project/user");
19905eb468daSGeorge Liu     dbus::utility::getManagedObjects(
19915eb468daSGeorge Liu         "xyz.openbmc_project.User.Manager", path,
19921ef4c342SEd Tanous         [asyncResp,
19935e7e2dc5SEd Tanous          accountName](const boost::system::error_code& ec,
1994711ac7a9SEd Tanous                       const dbus::utility::ManagedObjectType& users) {
1995b9b2e0b2SEd Tanous             if (ec)
1996b9b2e0b2SEd Tanous             {
1997f12894f8SJason M. Bills                 messages::internalError(asyncResp->res);
1998b9b2e0b2SEd Tanous                 return;
1999b9b2e0b2SEd Tanous             }
20003544d2a7SEd Tanous             const auto userIt = std::ranges::find_if(
200180f79a40SMichael Shen                 users,
200280f79a40SMichael Shen                 [accountName](
2003b477fd44SP Dheeraj Srujan Kumar                     const std::pair<sdbusplus::message::object_path,
200480f79a40SMichael Shen                                     dbus::utility::DBusInterfacesMap>& user) {
200555f79e6fSEd Tanous                     return accountName == user.first.filename();
2006b477fd44SP Dheeraj Srujan Kumar                 });
2007b9b2e0b2SEd Tanous 
200884e12cb7SAppaRao Puli             if (userIt == users.end())
2009b9b2e0b2SEd Tanous             {
2010002d39b4SEd Tanous                 messages::resourceNotFound(asyncResp->res, "ManagerAccount",
2011002d39b4SEd Tanous                                            accountName);
201284e12cb7SAppaRao Puli                 return;
201384e12cb7SAppaRao Puli             }
20144e68c45bSAyushi Smriti 
20151476687dSEd Tanous             asyncResp->res.jsonValue["@odata.type"] =
201658345856SAbhishek Patel                 "#ManagerAccount.v1_7_0.ManagerAccount";
20171476687dSEd Tanous             asyncResp->res.jsonValue["Name"] = "User Account";
20181476687dSEd Tanous             asyncResp->res.jsonValue["Description"] = "User Account";
20191476687dSEd Tanous             asyncResp->res.jsonValue["Password"] = nullptr;
202058345856SAbhishek Patel             asyncResp->res.jsonValue["StrictAccountTypes"] = true;
20214e68c45bSAyushi Smriti 
202284e12cb7SAppaRao Puli             for (const auto& interface : userIt->second)
202365b0dc32SEd Tanous             {
2024002d39b4SEd Tanous                 if (interface.first == "xyz.openbmc_project.User.Attributes")
202565b0dc32SEd Tanous                 {
202665b0dc32SEd Tanous                     for (const auto& property : interface.second)
202765b0dc32SEd Tanous                     {
202865b0dc32SEd Tanous                         if (property.first == "UserEnabled")
202965b0dc32SEd Tanous                         {
203065b0dc32SEd Tanous                             const bool* userEnabled =
2031abf2add6SEd Tanous                                 std::get_if<bool>(&property.second);
203265b0dc32SEd Tanous                             if (userEnabled == nullptr)
203365b0dc32SEd Tanous                             {
203462598e31SEd Tanous                                 BMCWEB_LOG_ERROR("UserEnabled wasn't a bool");
203584e12cb7SAppaRao Puli                                 messages::internalError(asyncResp->res);
203684e12cb7SAppaRao Puli                                 return;
203765b0dc32SEd Tanous                             }
2038002d39b4SEd Tanous                             asyncResp->res.jsonValue["Enabled"] = *userEnabled;
203965b0dc32SEd Tanous                         }
2040002d39b4SEd Tanous                         else if (property.first == "UserLockedForFailedAttempt")
204165b0dc32SEd Tanous                         {
204265b0dc32SEd Tanous                             const bool* userLocked =
2043abf2add6SEd Tanous                                 std::get_if<bool>(&property.second);
204465b0dc32SEd Tanous                             if (userLocked == nullptr)
204565b0dc32SEd Tanous                             {
204662598e31SEd Tanous                                 BMCWEB_LOG_ERROR("UserLockedForF"
204784e12cb7SAppaRao Puli                                                  "ailedAttempt "
204862598e31SEd Tanous                                                  "wasn't a bool");
204984e12cb7SAppaRao Puli                                 messages::internalError(asyncResp->res);
205084e12cb7SAppaRao Puli                                 return;
205165b0dc32SEd Tanous                             }
2052002d39b4SEd Tanous                             asyncResp->res.jsonValue["Locked"] = *userLocked;
205320fa6a2cSEd Tanous                             nlohmann::json::array_t allowed;
205420fa6a2cSEd Tanous                             // can only unlock accounts
205520fa6a2cSEd Tanous                             allowed.emplace_back("false");
2056002d39b4SEd Tanous                             asyncResp->res
205720fa6a2cSEd Tanous                                 .jsonValue["Locked@Redfish.AllowableValues"] =
205820fa6a2cSEd Tanous                                 std::move(allowed);
205965b0dc32SEd Tanous                         }
206084e12cb7SAppaRao Puli                         else if (property.first == "UserPrivilege")
206184e12cb7SAppaRao Puli                         {
206254fc587aSNagaraju Goruganti                             const std::string* userPrivPtr =
2063002d39b4SEd Tanous                                 std::get_if<std::string>(&property.second);
206454fc587aSNagaraju Goruganti                             if (userPrivPtr == nullptr)
206584e12cb7SAppaRao Puli                             {
206662598e31SEd Tanous                                 BMCWEB_LOG_ERROR("UserPrivilege wasn't a "
206762598e31SEd Tanous                                                  "string");
206884e12cb7SAppaRao Puli                                 messages::internalError(asyncResp->res);
206984e12cb7SAppaRao Puli                                 return;
207084e12cb7SAppaRao Puli                             }
2071*bd79bce8SPatrick Williams                             std::string role =
2072*bd79bce8SPatrick Williams                                 getRoleIdFromPrivilege(*userPrivPtr);
207354fc587aSNagaraju Goruganti                             if (role.empty())
207484e12cb7SAppaRao Puli                             {
207562598e31SEd Tanous                                 BMCWEB_LOG_ERROR("Invalid user role");
207684e12cb7SAppaRao Puli                                 messages::internalError(asyncResp->res);
207784e12cb7SAppaRao Puli                                 return;
207884e12cb7SAppaRao Puli                             }
207954fc587aSNagaraju Goruganti                             asyncResp->res.jsonValue["RoleId"] = role;
208084e12cb7SAppaRao Puli 
20811476687dSEd Tanous                             nlohmann::json& roleEntry =
2082002d39b4SEd Tanous                                 asyncResp->res.jsonValue["Links"]["Role"];
20833b32780dSEd Tanous                             roleEntry["@odata.id"] = boost::urls::format(
20843b32780dSEd Tanous                                 "/redfish/v1/AccountService/Roles/{}", role);
208584e12cb7SAppaRao Puli                         }
2086002d39b4SEd Tanous                         else if (property.first == "UserPasswordExpired")
20873bf4e632SJoseph Reynolds                         {
20883bf4e632SJoseph Reynolds                             const bool* userPasswordExpired =
20893bf4e632SJoseph Reynolds                                 std::get_if<bool>(&property.second);
20903bf4e632SJoseph Reynolds                             if (userPasswordExpired == nullptr)
20913bf4e632SJoseph Reynolds                             {
209262598e31SEd Tanous                                 BMCWEB_LOG_ERROR(
209362598e31SEd Tanous                                     "UserPasswordExpired wasn't a bool");
20943bf4e632SJoseph Reynolds                                 messages::internalError(asyncResp->res);
20953bf4e632SJoseph Reynolds                                 return;
20963bf4e632SJoseph Reynolds                             }
2097002d39b4SEd Tanous                             asyncResp->res.jsonValue["PasswordChangeRequired"] =
20983bf4e632SJoseph Reynolds                                 *userPasswordExpired;
20993bf4e632SJoseph Reynolds                         }
2100c7229815SAbhishek Patel                         else if (property.first == "UserGroups")
2101c7229815SAbhishek Patel                         {
2102c7229815SAbhishek Patel                             const std::vector<std::string>* userGroups =
2103c7229815SAbhishek Patel                                 std::get_if<std::vector<std::string>>(
2104c7229815SAbhishek Patel                                     &property.second);
2105c7229815SAbhishek Patel                             if (userGroups == nullptr)
2106c7229815SAbhishek Patel                             {
210762598e31SEd Tanous                                 BMCWEB_LOG_ERROR(
210862598e31SEd Tanous                                     "userGroups wasn't a string vector");
2109c7229815SAbhishek Patel                                 messages::internalError(asyncResp->res);
2110c7229815SAbhishek Patel                                 return;
2111c7229815SAbhishek Patel                             }
2112*bd79bce8SPatrick Williams                             if (!translateUserGroup(*userGroups,
2113*bd79bce8SPatrick Williams                                                     asyncResp->res))
2114c7229815SAbhishek Patel                             {
211562598e31SEd Tanous                                 BMCWEB_LOG_ERROR("userGroups mapping failed");
2116c7229815SAbhishek Patel                                 messages::internalError(asyncResp->res);
2117c7229815SAbhishek Patel                                 return;
2118c7229815SAbhishek Patel                             }
2119c7229815SAbhishek Patel                         }
212065b0dc32SEd Tanous                     }
212165b0dc32SEd Tanous                 }
212265b0dc32SEd Tanous             }
212365b0dc32SEd Tanous 
21243b32780dSEd Tanous             asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
21253b32780dSEd Tanous                 "/redfish/v1/AccountService/Accounts/{}", accountName);
2126b9b2e0b2SEd Tanous             asyncResp->res.jsonValue["Id"] = accountName;
2127b9b2e0b2SEd Tanous             asyncResp->res.jsonValue["UserName"] = accountName;
21285eb468daSGeorge Liu         });
21291ef4c342SEd Tanous }
2130a840879dSEd Tanous 
21311ef4c342SEd Tanous inline void
213220fc307fSGunnar Mills     handleAccountDelete(App& app, const crow::Request& req,
21336c51eab1SEd Tanous                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
21341ef4c342SEd Tanous                         const std::string& username)
21351ef4c342SEd Tanous {
21363ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
213745ca1b86SEd Tanous     {
213845ca1b86SEd Tanous         return;
213945ca1b86SEd Tanous     }
21401ef4c342SEd Tanous 
214125b54dbaSEd Tanous     if constexpr (BMCWEB_INSECURE_DISABLE_AUTH)
214225b54dbaSEd Tanous     {
2143031514fbSJunLin Chen         // If authentication is disabled, there are no user accounts
2144d8a5d5d8SJiaqing Zhao         messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
2145031514fbSJunLin Chen         return;
214625b54dbaSEd Tanous     }
21471ef4c342SEd Tanous     sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
21481ef4c342SEd Tanous     tempObjPath /= username;
21491ef4c342SEd Tanous     const std::string userPath(tempObjPath);
21501ef4c342SEd Tanous 
21511ef4c342SEd Tanous     crow::connections::systemBus->async_method_call(
21525e7e2dc5SEd Tanous         [asyncResp, username](const boost::system::error_code& ec) {
21531ef4c342SEd Tanous             if (ec)
21541ef4c342SEd Tanous             {
2155d8a5d5d8SJiaqing Zhao                 messages::resourceNotFound(asyncResp->res, "ManagerAccount",
21561ef4c342SEd Tanous                                            username);
21571ef4c342SEd Tanous                 return;
21581ef4c342SEd Tanous             }
21591ef4c342SEd Tanous 
21601ef4c342SEd Tanous             messages::accountRemoved(asyncResp->res);
21611ef4c342SEd Tanous         },
21621ef4c342SEd Tanous         "xyz.openbmc_project.User.Manager", userPath,
21631ef4c342SEd Tanous         "xyz.openbmc_project.Object.Delete", "Delete");
21641ef4c342SEd Tanous }
21651ef4c342SEd Tanous 
21661ef4c342SEd Tanous inline void
21671ef4c342SEd Tanous     handleAccountPatch(App& app, const crow::Request& req,
21681ef4c342SEd Tanous                        const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
21691ef4c342SEd Tanous                        const std::string& username)
21701ef4c342SEd Tanous {
21711ef4c342SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
21721ef4c342SEd Tanous     {
21731ef4c342SEd Tanous         return;
21741ef4c342SEd Tanous     }
217525b54dbaSEd Tanous     if constexpr (BMCWEB_INSECURE_DISABLE_AUTH)
217625b54dbaSEd Tanous     {
21771ef4c342SEd Tanous         // If authentication is disabled, there are no user accounts
2178d8a5d5d8SJiaqing Zhao         messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
21791ef4c342SEd Tanous         return;
218025b54dbaSEd Tanous     }
2181a24526dcSEd Tanous     std::optional<std::string> newUserName;
2182a24526dcSEd Tanous     std::optional<std::string> password;
2183a24526dcSEd Tanous     std::optional<bool> enabled;
2184a24526dcSEd Tanous     std::optional<std::string> roleId;
218524c8542dSRatan Gupta     std::optional<bool> locked;
218658345856SAbhishek Patel     std::optional<std::vector<std::string>> accountTypes;
218758345856SAbhishek Patel 
2188031514fbSJunLin Chen     if (req.session == nullptr)
2189031514fbSJunLin Chen     {
2190031514fbSJunLin Chen         messages::internalError(asyncResp->res);
2191031514fbSJunLin Chen         return;
2192031514fbSJunLin Chen     }
2193031514fbSJunLin Chen 
21942b9c1dfeSEd Tanous     bool userSelf = (username == req.session->username);
21952b9c1dfeSEd Tanous 
2196e9cc5172SEd Tanous     Privileges effectiveUserPrivileges =
21973e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
2198e9cc5172SEd Tanous     Privileges configureUsers = {"ConfigureUsers"};
2199e9cc5172SEd Tanous     bool userHasConfigureUsers =
2200e9cc5172SEd Tanous         effectiveUserPrivileges.isSupersetOf(configureUsers);
2201e9cc5172SEd Tanous     if (userHasConfigureUsers)
2202e9cc5172SEd Tanous     {
2203e9cc5172SEd Tanous         // Users with ConfigureUsers can modify for all users
220458345856SAbhishek Patel         if (!json_util::readJsonPatch(
220558345856SAbhishek Patel                 req, asyncResp->res, "UserName", newUserName, "Password",
220658345856SAbhishek Patel                 password, "RoleId", roleId, "Enabled", enabled, "Locked",
220758345856SAbhishek Patel                 locked, "AccountTypes", accountTypes))
2208a840879dSEd Tanous         {
2209a840879dSEd Tanous             return;
2210a840879dSEd Tanous         }
2211e9cc5172SEd Tanous     }
2212e9cc5172SEd Tanous     else
2213900f9497SJoseph Reynolds     {
2214e9cc5172SEd Tanous         // ConfigureSelf accounts can only modify their own account
221558345856SAbhishek Patel         if (!userSelf)
2216900f9497SJoseph Reynolds         {
2217900f9497SJoseph Reynolds             messages::insufficientPrivilege(asyncResp->res);
2218900f9497SJoseph Reynolds             return;
2219900f9497SJoseph Reynolds         }
2220031514fbSJunLin Chen 
2221e9cc5172SEd Tanous         // ConfigureSelf accounts can only modify their password
22221ef4c342SEd Tanous         if (!json_util::readJsonPatch(req, asyncResp->res, "Password",
22231ef4c342SEd Tanous                                       password))
2224e9cc5172SEd Tanous         {
2225e9cc5172SEd Tanous             return;
2226e9cc5172SEd Tanous         }
2227900f9497SJoseph Reynolds     }
2228900f9497SJoseph Reynolds 
222966b5ca76Sjayaprakash Mutyala     // if user name is not provided in the patch method or if it
22306c51eab1SEd Tanous     // matches the user name in the URI, then we are treating it as
22316c51eab1SEd Tanous     // updating user properties other then username. If username
22326c51eab1SEd Tanous     // provided doesn't match the URI, then we are treating this as
22336c51eab1SEd Tanous     // user rename request.
223466b5ca76Sjayaprakash Mutyala     if (!newUserName || (newUserName.value() == username))
2235a840879dSEd Tanous     {
22361ef4c342SEd Tanous         updateUserProperties(asyncResp, username, password, enabled, roleId,
2237e518ef32SRavi Teja                              locked, accountTypes, userSelf, req.session);
223884e12cb7SAppaRao Puli         return;
223984e12cb7SAppaRao Puli     }
224084e12cb7SAppaRao Puli     crow::connections::systemBus->async_method_call(
22416c51eab1SEd Tanous         [asyncResp, username, password(std::move(password)),
22421ef4c342SEd Tanous          roleId(std::move(roleId)), enabled, newUser{std::string(*newUserName)},
2243e518ef32SRavi Teja          locked, userSelf, req, accountTypes(std::move(accountTypes))](
2244e81de512SEd Tanous             const boost::system::error_code& ec, sdbusplus::message_t& m) {
224584e12cb7SAppaRao Puli             if (ec)
224684e12cb7SAppaRao Puli             {
2247002d39b4SEd Tanous                 userErrorMessageHandler(m.get_error(), asyncResp, newUser,
2248002d39b4SEd Tanous                                         username);
2249a840879dSEd Tanous                 return;
2250a840879dSEd Tanous             }
2251a840879dSEd Tanous 
2252002d39b4SEd Tanous             updateUserProperties(asyncResp, newUser, password, enabled, roleId,
2253e518ef32SRavi Teja                                  locked, accountTypes, userSelf, req.session);
225484e12cb7SAppaRao Puli         },
22551ef4c342SEd Tanous         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
225684e12cb7SAppaRao Puli         "xyz.openbmc_project.User.Manager", "RenameUser", username,
225784e12cb7SAppaRao Puli         *newUserName);
22581ef4c342SEd Tanous }
22591ef4c342SEd Tanous 
22601ef4c342SEd Tanous inline void requestAccountServiceRoutes(App& app)
22611ef4c342SEd Tanous {
22621ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
22634c7d4d33SEd Tanous         .privileges(redfish::privileges::headAccountService)
22644c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
22654c7d4d33SEd Tanous             std::bind_front(handleAccountServiceHead, std::ref(app)));
22664c7d4d33SEd Tanous 
22674c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
22681ef4c342SEd Tanous         .privileges(redfish::privileges::getAccountService)
22691ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
22701ef4c342SEd Tanous             std::bind_front(handleAccountServiceGet, std::ref(app)));
22711ef4c342SEd Tanous 
22721ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
22731ef4c342SEd Tanous         .privileges(redfish::privileges::patchAccountService)
22741ef4c342SEd Tanous         .methods(boost::beast::http::verb::patch)(
22751ef4c342SEd Tanous             std::bind_front(handleAccountServicePatch, std::ref(app)));
22761ef4c342SEd Tanous 
22771aa375b8SEd Tanous     BMCWEB_ROUTE(
22781aa375b8SEd Tanous         app,
22791aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates")
22801aa375b8SEd Tanous         .privileges(redfish::privileges::headCertificateCollection)
22811aa375b8SEd Tanous         .methods(boost::beast::http::verb::head)(std::bind_front(
22821aa375b8SEd Tanous             handleAccountServiceClientCertificatesHead, std::ref(app)));
22831aa375b8SEd Tanous 
22841aa375b8SEd Tanous     BMCWEB_ROUTE(
22851aa375b8SEd Tanous         app,
22861aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates")
22871aa375b8SEd Tanous         .privileges(redfish::privileges::getCertificateCollection)
22881aa375b8SEd Tanous         .methods(boost::beast::http::verb::get)(std::bind_front(
22891aa375b8SEd Tanous             handleAccountServiceClientCertificatesGet, std::ref(app)));
22901aa375b8SEd Tanous 
22911aa375b8SEd Tanous     BMCWEB_ROUTE(
22921aa375b8SEd Tanous         app,
22931aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/<str>")
22941aa375b8SEd Tanous         .privileges(redfish::privileges::headCertificate)
22951aa375b8SEd Tanous         .methods(boost::beast::http::verb::head)(std::bind_front(
22961aa375b8SEd Tanous             handleAccountServiceClientCertificatesInstanceHead, std::ref(app)));
22971aa375b8SEd Tanous 
22981aa375b8SEd Tanous     BMCWEB_ROUTE(
22991aa375b8SEd Tanous         app,
23001aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/<str>/")
23011aa375b8SEd Tanous         .privileges(redfish::privileges::getCertificate)
23021aa375b8SEd Tanous         .methods(boost::beast::http::verb::get)(std::bind_front(
23031aa375b8SEd Tanous             handleAccountServiceClientCertificatesInstanceGet, std::ref(app)));
23041aa375b8SEd Tanous 
23051ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
23064c7d4d33SEd Tanous         .privileges(redfish::privileges::headManagerAccountCollection)
23074c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
23084c7d4d33SEd Tanous             std::bind_front(handleAccountCollectionHead, std::ref(app)));
23094c7d4d33SEd Tanous 
23104c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
23111ef4c342SEd Tanous         .privileges(redfish::privileges::getManagerAccountCollection)
23121ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
23131ef4c342SEd Tanous             std::bind_front(handleAccountCollectionGet, std::ref(app)));
23141ef4c342SEd Tanous 
23151ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
23161ef4c342SEd Tanous         .privileges(redfish::privileges::postManagerAccountCollection)
23171ef4c342SEd Tanous         .methods(boost::beast::http::verb::post)(
23181ef4c342SEd Tanous             std::bind_front(handleAccountCollectionPost, std::ref(app)));
23191ef4c342SEd Tanous 
23201ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
23214c7d4d33SEd Tanous         .privileges(redfish::privileges::headManagerAccount)
23224c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
23234c7d4d33SEd Tanous             std::bind_front(handleAccountHead, std::ref(app)));
23244c7d4d33SEd Tanous 
23254c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
23261ef4c342SEd Tanous         .privileges(redfish::privileges::getManagerAccount)
23271ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
23281ef4c342SEd Tanous             std::bind_front(handleAccountGet, std::ref(app)));
23291ef4c342SEd Tanous 
23301ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
23311ef4c342SEd Tanous         // TODO this privilege should be using the generated endpoints, but
23321ef4c342SEd Tanous         // because of the special handling of ConfigureSelf, it's not able to
23331ef4c342SEd Tanous         // yet
23341ef4c342SEd Tanous         .privileges({{"ConfigureUsers"}, {"ConfigureSelf"}})
23351ef4c342SEd Tanous         .methods(boost::beast::http::verb::patch)(
23361ef4c342SEd Tanous             std::bind_front(handleAccountPatch, std::ref(app)));
233784e12cb7SAppaRao Puli 
23386c51eab1SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
2339ed398213SEd Tanous         .privileges(redfish::privileges::deleteManagerAccount)
23406c51eab1SEd Tanous         .methods(boost::beast::http::verb::delete_)(
234120fc307fSGunnar Mills             std::bind_front(handleAccountDelete, std::ref(app)));
234206e086d9SEd Tanous }
234388d16c9aSLewanczyk, Dawid 
234488d16c9aSLewanczyk, Dawid } // namespace redfish
2345