xref: /openbmc/bmcweb/features/redfish/lib/account_service.hpp (revision 8b8444888a46062371689b10753e8641060fa8df)
140e9b92eSEd Tanous // SPDX-License-Identifier: Apache-2.0
240e9b92eSEd Tanous // SPDX-FileCopyrightText: Copyright OpenBMC Authors
340e9b92eSEd Tanous // SPDX-FileCopyrightText: Copyright 2018 Intel Corporation
488d16c9aSLewanczyk, Dawid #pragma once
588d16c9aSLewanczyk, Dawid 
6d7857201SEd Tanous #include "bmcweb_config.h"
7d7857201SEd Tanous 
83ccb3adbSEd Tanous #include "app.hpp"
9d7857201SEd Tanous #include "async_resp.hpp"
10a0735a4eSGunnar Mills #include "boost_formatters.hpp"
111aa375b8SEd Tanous #include "certificate_service.hpp"
123ccb3adbSEd Tanous #include "dbus_utility.hpp"
133ccb3adbSEd Tanous #include "error_messages.hpp"
140ec8b83dSEd Tanous #include "generated/enums/account_service.hpp"
15d7857201SEd Tanous #include "http_request.hpp"
16d7857201SEd Tanous #include "http_response.hpp"
17d7857201SEd Tanous #include "logging.hpp"
18d7857201SEd Tanous #include "pam_authenticate.hpp"
193ccb3adbSEd Tanous #include "persistent_data.hpp"
20d7857201SEd Tanous #include "privileges.hpp"
213ccb3adbSEd Tanous #include "query.hpp"
220ec8b83dSEd Tanous #include "registries/privilege_registry.hpp"
233281bcf1SEd Tanous #include "sessions.hpp"
241aa375b8SEd Tanous #include "utils/collection.hpp"
253ccb3adbSEd Tanous #include "utils/dbus_utils.hpp"
263ccb3adbSEd Tanous #include "utils/json_utils.hpp"
270ec8b83dSEd Tanous 
28d7857201SEd Tanous #include <security/_pam_types.h>
29d7857201SEd Tanous #include <systemd/sd-bus.h>
30d7857201SEd Tanous 
31d7857201SEd Tanous #include <boost/beast/http/field.hpp>
32d7857201SEd Tanous #include <boost/beast/http/status.hpp>
33d7857201SEd Tanous #include <boost/beast/http/verb.hpp>
341aa375b8SEd Tanous #include <boost/url/format.hpp>
351aa375b8SEd Tanous #include <boost/url/url.hpp>
36d7857201SEd Tanous #include <nlohmann/json.hpp>
37d7857201SEd Tanous #include <sdbusplus/message.hpp>
38d1bde9e5SKrzysztof Grobelny #include <sdbusplus/unpack_properties.hpp>
391214b7e7SGunnar Mills 
40d7857201SEd Tanous #include <algorithm>
412b73119cSGeorge Liu #include <array>
42d7857201SEd Tanous #include <cstddef>
43d7857201SEd Tanous #include <cstdint>
44d7857201SEd Tanous #include <cstring>
45d7857201SEd Tanous #include <format>
46d7857201SEd Tanous #include <functional>
471aa375b8SEd Tanous #include <memory>
48c7229815SAbhishek Patel #include <optional>
493544d2a7SEd Tanous #include <ranges>
50c7229815SAbhishek Patel #include <string>
512b73119cSGeorge Liu #include <string_view>
5220fa6a2cSEd Tanous #include <utility>
53d7857201SEd Tanous #include <variant>
54c7229815SAbhishek Patel #include <vector>
55c7229815SAbhishek Patel 
561abe55efSEd Tanous namespace redfish
571abe55efSEd Tanous {
5888d16c9aSLewanczyk, Dawid 
5923a21a1cSEd Tanous constexpr const char* ldapConfigObjectName =
606973a582SRatan Gupta     "/xyz/openbmc_project/user/ldap/openldap";
612c70f800SEd Tanous constexpr const char* adConfigObject =
62ab828d7cSRatan Gupta     "/xyz/openbmc_project/user/ldap/active_directory";
63ab828d7cSRatan Gupta 
64b477fd44SP Dheeraj Srujan Kumar constexpr const char* rootUserDbusPath = "/xyz/openbmc_project/user/";
656973a582SRatan Gupta constexpr const char* ldapRootObject = "/xyz/openbmc_project/user/ldap";
666973a582SRatan Gupta constexpr const char* ldapDbusService = "xyz.openbmc_project.Ldap.Config";
676973a582SRatan Gupta constexpr const char* ldapConfigInterface =
686973a582SRatan Gupta     "xyz.openbmc_project.User.Ldap.Config";
696973a582SRatan Gupta constexpr const char* ldapEnableInterface = "xyz.openbmc_project.Object.Enable";
7006785244SRatan Gupta constexpr const char* ldapPrivMapperInterface =
7106785244SRatan Gupta     "xyz.openbmc_project.User.PrivilegeMapper";
726973a582SRatan Gupta 
7354fc587aSNagaraju Goruganti struct LDAPRoleMapData
7454fc587aSNagaraju Goruganti {
7554fc587aSNagaraju Goruganti     std::string groupName;
7654fc587aSNagaraju Goruganti     std::string privilege;
7754fc587aSNagaraju Goruganti };
7854fc587aSNagaraju Goruganti 
796973a582SRatan Gupta struct LDAPConfigData
806973a582SRatan Gupta {
8147f2934cSEd Tanous     std::string uri;
8247f2934cSEd Tanous     std::string bindDN;
8347f2934cSEd Tanous     std::string baseDN;
8447f2934cSEd Tanous     std::string searchScope;
8547f2934cSEd Tanous     std::string serverType;
866973a582SRatan Gupta     bool serviceEnabled = false;
8747f2934cSEd Tanous     std::string userNameAttribute;
8847f2934cSEd Tanous     std::string groupAttribute;
8954fc587aSNagaraju Goruganti     std::vector<std::pair<std::string, LDAPRoleMapData>> groupRoleList;
906973a582SRatan Gupta };
916973a582SRatan Gupta 
9254fc587aSNagaraju Goruganti inline std::string getRoleIdFromPrivilege(std::string_view role)
9384e12cb7SAppaRao Puli {
9484e12cb7SAppaRao Puli     if (role == "priv-admin")
9584e12cb7SAppaRao Puli     {
9684e12cb7SAppaRao Puli         return "Administrator";
9784e12cb7SAppaRao Puli     }
983174e4dfSEd Tanous     if (role == "priv-user")
9984e12cb7SAppaRao Puli     {
100c80fee55SAppaRao Puli         return "ReadOnly";
10184e12cb7SAppaRao Puli     }
1023174e4dfSEd Tanous     if (role == "priv-operator")
10384e12cb7SAppaRao Puli     {
10484e12cb7SAppaRao Puli         return "Operator";
10584e12cb7SAppaRao Puli     }
10684e12cb7SAppaRao Puli     return "";
10784e12cb7SAppaRao Puli }
10854fc587aSNagaraju Goruganti inline std::string getPrivilegeFromRoleId(std::string_view role)
10984e12cb7SAppaRao Puli {
11084e12cb7SAppaRao Puli     if (role == "Administrator")
11184e12cb7SAppaRao Puli     {
11284e12cb7SAppaRao Puli         return "priv-admin";
11384e12cb7SAppaRao Puli     }
1143174e4dfSEd Tanous     if (role == "ReadOnly")
11584e12cb7SAppaRao Puli     {
11684e12cb7SAppaRao Puli         return "priv-user";
11784e12cb7SAppaRao Puli     }
1183174e4dfSEd Tanous     if (role == "Operator")
11984e12cb7SAppaRao Puli     {
12084e12cb7SAppaRao Puli         return "priv-operator";
12184e12cb7SAppaRao Puli     }
12284e12cb7SAppaRao Puli     return "";
12384e12cb7SAppaRao Puli }
124b9b2e0b2SEd Tanous 
125c7229815SAbhishek Patel /**
126c7229815SAbhishek Patel  * @brief Maps user group names retrieved from D-Bus object to
127c7229815SAbhishek Patel  * Account Types.
128c7229815SAbhishek Patel  *
129c7229815SAbhishek Patel  * @param[in] userGroups List of User groups
130c7229815SAbhishek Patel  * @param[out] res AccountTypes populated
131c7229815SAbhishek Patel  *
132c7229815SAbhishek Patel  * @return true in case of success, false if UserGroups contains
133c7229815SAbhishek Patel  * invalid group name(s).
134c7229815SAbhishek Patel  */
135c7229815SAbhishek Patel inline bool translateUserGroup(const std::vector<std::string>& userGroups,
136c7229815SAbhishek Patel                                crow::Response& res)
137c7229815SAbhishek Patel {
138c7229815SAbhishek Patel     std::vector<std::string> accountTypes;
139c7229815SAbhishek Patel     for (const auto& userGroup : userGroups)
140c7229815SAbhishek Patel     {
141c7229815SAbhishek Patel         if (userGroup == "redfish")
142c7229815SAbhishek Patel         {
143c7229815SAbhishek Patel             accountTypes.emplace_back("Redfish");
144c7229815SAbhishek Patel             accountTypes.emplace_back("WebUI");
145c7229815SAbhishek Patel         }
146c7229815SAbhishek Patel         else if (userGroup == "ipmi")
147c7229815SAbhishek Patel         {
148c7229815SAbhishek Patel             accountTypes.emplace_back("IPMI");
149c7229815SAbhishek Patel         }
150c7229815SAbhishek Patel         else if (userGroup == "ssh")
151c7229815SAbhishek Patel         {
152c7229815SAbhishek Patel             accountTypes.emplace_back("ManagerConsole");
153c7229815SAbhishek Patel         }
1543e72c202SNinad Palsule         else if (userGroup == "hostconsole")
1553e72c202SNinad Palsule         {
1563e72c202SNinad Palsule             // The hostconsole group controls who can access the host console
1573e72c202SNinad Palsule             // port via ssh and websocket.
1583e72c202SNinad Palsule             accountTypes.emplace_back("HostConsole");
1593e72c202SNinad Palsule         }
160c7229815SAbhishek Patel         else if (userGroup == "web")
161c7229815SAbhishek Patel         {
162c7229815SAbhishek Patel             // 'web' is one of the valid groups in the UserGroups property of
163c7229815SAbhishek Patel             // the user account in the D-Bus object. This group is currently not
164c7229815SAbhishek Patel             // doing anything, and is considered to be equivalent to 'redfish'.
165c7229815SAbhishek Patel             // 'redfish' user group is mapped to 'Redfish'and 'WebUI'
166c7229815SAbhishek Patel             // AccountTypes, so do nothing here...
167c7229815SAbhishek Patel         }
168c7229815SAbhishek Patel         else
169c7229815SAbhishek Patel         {
1708ece0e45SEd Tanous             // Invalid user group name. Caller throws an exception.
171c7229815SAbhishek Patel             return false;
172c7229815SAbhishek Patel         }
173c7229815SAbhishek Patel     }
174c7229815SAbhishek Patel 
175c7229815SAbhishek Patel     res.jsonValue["AccountTypes"] = std::move(accountTypes);
176c7229815SAbhishek Patel     return true;
177c7229815SAbhishek Patel }
178c7229815SAbhishek Patel 
17958345856SAbhishek Patel /**
18058345856SAbhishek Patel  * @brief Builds User Groups from the Account Types
18158345856SAbhishek Patel  *
18258345856SAbhishek Patel  * @param[in] asyncResp Async Response
18358345856SAbhishek Patel  * @param[in] accountTypes List of Account Types
18458345856SAbhishek Patel  * @param[out] userGroups List of User Groups mapped from Account Types
18558345856SAbhishek Patel  *
18658345856SAbhishek Patel  * @return true if Account Types mapped to User Groups, false otherwise.
18758345856SAbhishek Patel  */
188bd79bce8SPatrick Williams inline bool getUserGroupFromAccountType(
189bd79bce8SPatrick Williams     crow::Response& res, const std::vector<std::string>& accountTypes,
19058345856SAbhishek Patel     std::vector<std::string>& userGroups)
19158345856SAbhishek Patel {
19258345856SAbhishek Patel     // Need both Redfish and WebUI Account Types to map to 'redfish' User Group
19358345856SAbhishek Patel     bool redfishType = false;
19458345856SAbhishek Patel     bool webUIType = false;
19558345856SAbhishek Patel 
19658345856SAbhishek Patel     for (const auto& accountType : accountTypes)
19758345856SAbhishek Patel     {
19858345856SAbhishek Patel         if (accountType == "Redfish")
19958345856SAbhishek Patel         {
20058345856SAbhishek Patel             redfishType = true;
20158345856SAbhishek Patel         }
20258345856SAbhishek Patel         else if (accountType == "WebUI")
20358345856SAbhishek Patel         {
20458345856SAbhishek Patel             webUIType = true;
20558345856SAbhishek Patel         }
20658345856SAbhishek Patel         else if (accountType == "IPMI")
20758345856SAbhishek Patel         {
20858345856SAbhishek Patel             userGroups.emplace_back("ipmi");
20958345856SAbhishek Patel         }
21058345856SAbhishek Patel         else if (accountType == "HostConsole")
21158345856SAbhishek Patel         {
21258345856SAbhishek Patel             userGroups.emplace_back("hostconsole");
21358345856SAbhishek Patel         }
21458345856SAbhishek Patel         else if (accountType == "ManagerConsole")
21558345856SAbhishek Patel         {
21658345856SAbhishek Patel             userGroups.emplace_back("ssh");
21758345856SAbhishek Patel         }
21858345856SAbhishek Patel         else
21958345856SAbhishek Patel         {
22058345856SAbhishek Patel             // Invalid Account Type
22158345856SAbhishek Patel             messages::propertyValueNotInList(res, "AccountTypes", accountType);
22258345856SAbhishek Patel             return false;
22358345856SAbhishek Patel         }
22458345856SAbhishek Patel     }
22558345856SAbhishek Patel 
22658345856SAbhishek Patel     // Both  Redfish and WebUI Account Types are needed to PATCH
22758345856SAbhishek Patel     if (redfishType ^ webUIType)
22858345856SAbhishek Patel     {
22962598e31SEd Tanous         BMCWEB_LOG_ERROR(
23062598e31SEd Tanous             "Missing Redfish or WebUI Account Type to set redfish User Group");
23158345856SAbhishek Patel         messages::strictAccountTypes(res, "AccountTypes");
23258345856SAbhishek Patel         return false;
23358345856SAbhishek Patel     }
23458345856SAbhishek Patel 
23558345856SAbhishek Patel     if (redfishType && webUIType)
23658345856SAbhishek Patel     {
23758345856SAbhishek Patel         userGroups.emplace_back("redfish");
23858345856SAbhishek Patel     }
23958345856SAbhishek Patel 
24058345856SAbhishek Patel     return true;
24158345856SAbhishek Patel }
24258345856SAbhishek Patel 
24358345856SAbhishek Patel /**
24458345856SAbhishek Patel  * @brief Sets UserGroups property of the user based on the Account Types
24558345856SAbhishek Patel  *
24658345856SAbhishek Patel  * @param[in] accountTypes List of User Account Types
24758345856SAbhishek Patel  * @param[in] asyncResp Async Response
24858345856SAbhishek Patel  * @param[in] dbusObjectPath D-Bus Object Path
24958345856SAbhishek Patel  * @param[in] userSelf true if User is updating OWN Account Types
25058345856SAbhishek Patel  */
251504af5a0SPatrick Williams inline void patchAccountTypes(
252504af5a0SPatrick Williams     const std::vector<std::string>& accountTypes,
25358345856SAbhishek Patel     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
25458345856SAbhishek Patel     const std::string& dbusObjectPath, bool userSelf)
25558345856SAbhishek Patel {
25658345856SAbhishek Patel     // Check if User is disabling own Redfish Account Type
25758345856SAbhishek Patel     if (userSelf &&
25858345856SAbhishek Patel         (accountTypes.cend() ==
25958345856SAbhishek Patel          std::find(accountTypes.cbegin(), accountTypes.cend(), "Redfish")))
26058345856SAbhishek Patel     {
26162598e31SEd Tanous         BMCWEB_LOG_ERROR(
26262598e31SEd Tanous             "User disabling OWN Redfish Account Type is not allowed");
26358345856SAbhishek Patel         messages::strictAccountTypes(asyncResp->res, "AccountTypes");
26458345856SAbhishek Patel         return;
26558345856SAbhishek Patel     }
26658345856SAbhishek Patel 
26758345856SAbhishek Patel     std::vector<std::string> updatedUserGroups;
26858345856SAbhishek Patel     if (!getUserGroupFromAccountType(asyncResp->res, accountTypes,
26958345856SAbhishek Patel                                      updatedUserGroups))
27058345856SAbhishek Patel     {
27158345856SAbhishek Patel         // Problem in mapping Account Types to User Groups, Error already
27258345856SAbhishek Patel         // logged.
27358345856SAbhishek Patel         return;
27458345856SAbhishek Patel     }
275e93abac6SGinu George     setDbusProperty(asyncResp, "AccountTypes",
276e93abac6SGinu George                     "xyz.openbmc_project.User.Manager", dbusObjectPath,
277e93abac6SGinu George                     "xyz.openbmc_project.User.Attributes", "UserGroups",
278e93abac6SGinu George                     updatedUserGroups);
27958345856SAbhishek Patel }
28058345856SAbhishek Patel 
2818d1b46d7Szhanghch05 inline void userErrorMessageHandler(
2828d1b46d7Szhanghch05     const sd_bus_error* e, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2838d1b46d7Szhanghch05     const std::string& newUser, const std::string& username)
28466b5ca76Sjayaprakash Mutyala {
28566b5ca76Sjayaprakash Mutyala     if (e == nullptr)
28666b5ca76Sjayaprakash Mutyala     {
28766b5ca76Sjayaprakash Mutyala         messages::internalError(asyncResp->res);
28866b5ca76Sjayaprakash Mutyala         return;
28966b5ca76Sjayaprakash Mutyala     }
29066b5ca76Sjayaprakash Mutyala 
291055806b3SManojkiran Eda     const char* errorMessage = e->name;
29266b5ca76Sjayaprakash Mutyala     if (strcmp(errorMessage,
29366b5ca76Sjayaprakash Mutyala                "xyz.openbmc_project.User.Common.Error.UserNameExists") == 0)
29466b5ca76Sjayaprakash Mutyala     {
295d8a5d5d8SJiaqing Zhao         messages::resourceAlreadyExists(asyncResp->res, "ManagerAccount",
29666b5ca76Sjayaprakash Mutyala                                         "UserName", newUser);
29766b5ca76Sjayaprakash Mutyala     }
29866b5ca76Sjayaprakash Mutyala     else if (strcmp(errorMessage, "xyz.openbmc_project.User.Common.Error."
29966b5ca76Sjayaprakash Mutyala                                   "UserNameDoesNotExist") == 0)
30066b5ca76Sjayaprakash Mutyala     {
301d8a5d5d8SJiaqing Zhao         messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
30266b5ca76Sjayaprakash Mutyala     }
303d4d25793SEd Tanous     else if ((strcmp(errorMessage,
304d4d25793SEd Tanous                      "xyz.openbmc_project.Common.Error.InvalidArgument") ==
305d4d25793SEd Tanous               0) ||
3060fda0f12SGeorge Liu              (strcmp(
3070fda0f12SGeorge Liu                   errorMessage,
3080fda0f12SGeorge Liu                   "xyz.openbmc_project.User.Common.Error.UserNameGroupFail") ==
3090fda0f12SGeorge Liu               0))
31066b5ca76Sjayaprakash Mutyala     {
31166b5ca76Sjayaprakash Mutyala         messages::propertyValueFormatError(asyncResp->res, newUser, "UserName");
31266b5ca76Sjayaprakash Mutyala     }
31366b5ca76Sjayaprakash Mutyala     else if (strcmp(errorMessage,
31466b5ca76Sjayaprakash Mutyala                     "xyz.openbmc_project.User.Common.Error.NoResource") == 0)
31566b5ca76Sjayaprakash Mutyala     {
31666b5ca76Sjayaprakash Mutyala         messages::createLimitReachedForResource(asyncResp->res);
31766b5ca76Sjayaprakash Mutyala     }
31866b5ca76Sjayaprakash Mutyala     else
31966b5ca76Sjayaprakash Mutyala     {
320b8ad583fSGunnar Mills         BMCWEB_LOG_ERROR("DBUS response error {}", errorMessage);
32166b5ca76Sjayaprakash Mutyala         messages::internalError(asyncResp->res);
32266b5ca76Sjayaprakash Mutyala     }
32366b5ca76Sjayaprakash Mutyala }
32466b5ca76Sjayaprakash Mutyala 
32581ce609eSEd Tanous inline void parseLDAPConfigData(nlohmann::json& jsonResponse,
326ab828d7cSRatan Gupta                                 const LDAPConfigData& confData,
327ab828d7cSRatan Gupta                                 const std::string& ldapType)
3286973a582SRatan Gupta {
32949cc263fSEd Tanous     nlohmann::json::object_t ldap;
3301476687dSEd Tanous     ldap["ServiceEnabled"] = confData.serviceEnabled;
33149cc263fSEd Tanous     nlohmann::json::array_t serviceAddresses;
332092a33f1SEd Tanous     if (!confData.uri.empty())
333092a33f1SEd Tanous     {
33449cc263fSEd Tanous         serviceAddresses.emplace_back(confData.uri);
335092a33f1SEd Tanous     }
33649cc263fSEd Tanous     ldap["ServiceAddresses"] = std::move(serviceAddresses);
33749cc263fSEd Tanous 
33849cc263fSEd Tanous     nlohmann::json::object_t authentication;
33949cc263fSEd Tanous     authentication["AuthenticationType"] =
3400ec8b83dSEd Tanous         account_service::AuthenticationTypes::UsernameAndPassword;
34149cc263fSEd Tanous     authentication["Username"] = confData.bindDN;
34249cc263fSEd Tanous     authentication["Password"] = nullptr;
34349cc263fSEd Tanous     ldap["Authentication"] = std::move(authentication);
3441476687dSEd Tanous 
34549cc263fSEd Tanous     nlohmann::json::object_t ldapService;
34649cc263fSEd Tanous     nlohmann::json::object_t searchSettings;
34749cc263fSEd Tanous     nlohmann::json::array_t baseDistinguishedNames;
348092a33f1SEd Tanous     if (!confData.baseDN.empty())
349092a33f1SEd Tanous     {
35049cc263fSEd Tanous         baseDistinguishedNames.emplace_back(confData.baseDN);
351092a33f1SEd Tanous     }
3521476687dSEd Tanous 
35349cc263fSEd Tanous     searchSettings["BaseDistinguishedNames"] =
35449cc263fSEd Tanous         std::move(baseDistinguishedNames);
35549cc263fSEd Tanous     searchSettings["UsernameAttribute"] = confData.userNameAttribute;
35649cc263fSEd Tanous     searchSettings["GroupsAttribute"] = confData.groupAttribute;
35749cc263fSEd Tanous     ldapService["SearchSettings"] = std::move(searchSettings);
35849cc263fSEd Tanous     ldap["LDAPService"] = std::move(ldapService);
35949cc263fSEd Tanous 
36049cc263fSEd Tanous     nlohmann::json::array_t roleMapArray;
3619eb808c1SEd Tanous     for (const auto& obj : confData.groupRoleList)
36254fc587aSNagaraju Goruganti     {
36362598e31SEd Tanous         BMCWEB_LOG_DEBUG("Pushing the data groupName={}", obj.second.groupName);
364613dabeaSEd Tanous 
365613dabeaSEd Tanous         nlohmann::json::object_t remoteGroup;
366613dabeaSEd Tanous         remoteGroup["RemoteGroup"] = obj.second.groupName;
367329f0348SJorge Cisneros         remoteGroup["LocalRole"] = getRoleIdFromPrivilege(obj.second.privilege);
368329f0348SJorge Cisneros         roleMapArray.emplace_back(std::move(remoteGroup));
36954fc587aSNagaraju Goruganti     }
37049cc263fSEd Tanous 
37149cc263fSEd Tanous     ldap["RemoteRoleMapping"] = std::move(roleMapArray);
37249cc263fSEd Tanous 
37349cc263fSEd Tanous     jsonResponse[ldapType].update(ldap);
3746973a582SRatan Gupta }
3756973a582SRatan Gupta 
3766973a582SRatan Gupta /**
37706785244SRatan Gupta  *  @brief validates given JSON input and then calls appropriate method to
37806785244SRatan Gupta  * create, to delete or to set Rolemapping object based on the given input.
37906785244SRatan Gupta  *
38006785244SRatan Gupta  */
38123a21a1cSEd Tanous inline void handleRoleMapPatch(
3828d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
38306785244SRatan Gupta     const std::vector<std::pair<std::string, LDAPRoleMapData>>& roleMapObjData,
384c1019828SEd Tanous     const std::string& serverType,
385c1019828SEd Tanous     std::vector<std::variant<nlohmann::json::object_t, std::nullptr_t>>& input)
38606785244SRatan Gupta {
38706785244SRatan Gupta     for (size_t index = 0; index < input.size(); index++)
38806785244SRatan Gupta     {
389c1019828SEd Tanous         std::variant<nlohmann::json::object_t, std::nullptr_t>& thisJson =
390c1019828SEd Tanous             input[index];
391c1019828SEd Tanous         nlohmann::json::object_t* obj =
392c1019828SEd Tanous             std::get_if<nlohmann::json::object_t>(&thisJson);
393c1019828SEd Tanous         if (obj == nullptr)
39406785244SRatan Gupta         {
39506785244SRatan Gupta             // delete the existing object
39606785244SRatan Gupta             if (index < roleMapObjData.size())
39706785244SRatan Gupta             {
398177612aaSEd Tanous                 dbus::utility::async_method_call(
399177612aaSEd Tanous                     asyncResp,
40006785244SRatan Gupta                     [asyncResp, roleMapObjData, serverType,
4015e7e2dc5SEd Tanous                      index](const boost::system::error_code& ec) {
40206785244SRatan Gupta                         if (ec)
40306785244SRatan Gupta                         {
40462598e31SEd Tanous                             BMCWEB_LOG_ERROR("DBUS response error: {}", ec);
40506785244SRatan Gupta                             messages::internalError(asyncResp->res);
40606785244SRatan Gupta                             return;
40706785244SRatan Gupta                         }
408bd79bce8SPatrick Williams                         asyncResp->res
409bd79bce8SPatrick Williams                             .jsonValue[serverType]["RemoteRoleMapping"][index] =
410bd79bce8SPatrick Williams                             nullptr;
41106785244SRatan Gupta                     },
41206785244SRatan Gupta                     ldapDbusService, roleMapObjData[index].first,
41306785244SRatan Gupta                     "xyz.openbmc_project.Object.Delete", "Delete");
41406785244SRatan Gupta             }
41506785244SRatan Gupta             else
41606785244SRatan Gupta             {
41762598e31SEd Tanous                 BMCWEB_LOG_ERROR("Can't delete the object");
418bd79bce8SPatrick Williams                 messages::propertyValueTypeError(
419bd79bce8SPatrick Williams                     asyncResp->res, "null",
420bd79bce8SPatrick Williams                     "RemoteRoleMapping/" + std::to_string(index));
42106785244SRatan Gupta                 return;
42206785244SRatan Gupta             }
42306785244SRatan Gupta         }
424c1019828SEd Tanous         else if (obj->empty())
42506785244SRatan Gupta         {
42606785244SRatan Gupta             // Don't do anything for the empty objects,parse next json
42706785244SRatan Gupta             // eg {"RemoteRoleMapping",[{}]}
42806785244SRatan Gupta         }
42906785244SRatan Gupta         else
43006785244SRatan Gupta         {
43106785244SRatan Gupta             // update/create the object
43206785244SRatan Gupta             std::optional<std::string> remoteGroup;
43306785244SRatan Gupta             std::optional<std::string> localRole;
43406785244SRatan Gupta 
435afc474aeSMyung Bae             if (!json_util::readJsonObject(    //
436afc474aeSMyung Bae                     *obj, asyncResp->res,      //
437afc474aeSMyung Bae                     "LocalRole", localRole,    //
438afc474aeSMyung Bae                     "RemoteGroup", remoteGroup //
439afc474aeSMyung Bae                     ))
44006785244SRatan Gupta             {
44106785244SRatan Gupta                 continue;
44206785244SRatan Gupta             }
44306785244SRatan Gupta 
44406785244SRatan Gupta             // Update existing RoleMapping Object
44506785244SRatan Gupta             if (index < roleMapObjData.size())
44606785244SRatan Gupta             {
44762598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Update Role Map Object");
44806785244SRatan Gupta                 // If "RemoteGroup" info is provided
44906785244SRatan Gupta                 if (remoteGroup)
45006785244SRatan Gupta                 {
451d02aad39SEd Tanous                     setDbusProperty(
452e93abac6SGinu George                         asyncResp,
453d02aad39SEd Tanous                         std::format("RemoteRoleMapping/{}/RemoteGroup", index),
454e93abac6SGinu George                         ldapDbusService, roleMapObjData[index].first,
455e93abac6SGinu George                         "xyz.openbmc_project.User.PrivilegeMapperEntry",
456e93abac6SGinu George                         "GroupName", *remoteGroup);
45706785244SRatan Gupta                 }
45806785244SRatan Gupta 
45906785244SRatan Gupta                 // If "LocalRole" info is provided
46006785244SRatan Gupta                 if (localRole)
46106785244SRatan Gupta                 {
4626d0b80beSRavi Teja                     std::string priv = getPrivilegeFromRoleId(*localRole);
4636d0b80beSRavi Teja                     if (priv.empty())
4646d0b80beSRavi Teja                     {
4656d0b80beSRavi Teja                         messages::propertyValueNotInList(
4666d0b80beSRavi Teja                             asyncResp->res, *localRole,
4676d0b80beSRavi Teja                             std::format("RemoteRoleMapping/{}/LocalRole",
4686d0b80beSRavi Teja                                         index));
4696d0b80beSRavi Teja                         return;
4706d0b80beSRavi Teja                     }
471d02aad39SEd Tanous                     setDbusProperty(
472e93abac6SGinu George                         asyncResp,
473d02aad39SEd Tanous                         std::format("RemoteRoleMapping/{}/LocalRole", index),
474e93abac6SGinu George                         ldapDbusService, roleMapObjData[index].first,
475e93abac6SGinu George                         "xyz.openbmc_project.User.PrivilegeMapperEntry",
4766d0b80beSRavi Teja                         "Privilege", priv);
47706785244SRatan Gupta                 }
47806785244SRatan Gupta             }
47906785244SRatan Gupta             // Create a new RoleMapping Object.
48006785244SRatan Gupta             else
48106785244SRatan Gupta             {
48262598e31SEd Tanous                 BMCWEB_LOG_DEBUG(
48362598e31SEd Tanous                     "setRoleMappingProperties: Creating new Object");
484bd79bce8SPatrick Williams                 std::string pathString =
485bd79bce8SPatrick Williams                     "RemoteRoleMapping/" + std::to_string(index);
48606785244SRatan Gupta 
48706785244SRatan Gupta                 if (!localRole)
48806785244SRatan Gupta                 {
48906785244SRatan Gupta                     messages::propertyMissing(asyncResp->res,
49006785244SRatan Gupta                                               pathString + "/LocalRole");
49106785244SRatan Gupta                     continue;
49206785244SRatan Gupta                 }
49306785244SRatan Gupta                 if (!remoteGroup)
49406785244SRatan Gupta                 {
49506785244SRatan Gupta                     messages::propertyMissing(asyncResp->res,
49606785244SRatan Gupta                                               pathString + "/RemoteGroup");
49706785244SRatan Gupta                     continue;
49806785244SRatan Gupta                 }
49906785244SRatan Gupta 
50006785244SRatan Gupta                 std::string dbusObjectPath;
50106785244SRatan Gupta                 if (serverType == "ActiveDirectory")
50206785244SRatan Gupta                 {
5032c70f800SEd Tanous                     dbusObjectPath = adConfigObject;
50406785244SRatan Gupta                 }
50506785244SRatan Gupta                 else if (serverType == "LDAP")
50606785244SRatan Gupta                 {
50723a21a1cSEd Tanous                     dbusObjectPath = ldapConfigObjectName;
50806785244SRatan Gupta                 }
50906785244SRatan Gupta 
51062598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Remote Group={},LocalRole={}", *remoteGroup,
51162598e31SEd Tanous                                  *localRole);
51206785244SRatan Gupta 
513177612aaSEd Tanous                 dbus::utility::async_method_call(
514177612aaSEd Tanous                     asyncResp,
515271584abSEd Tanous                     [asyncResp, serverType, localRole,
5165e7e2dc5SEd Tanous                      remoteGroup](const boost::system::error_code& ec) {
51706785244SRatan Gupta                         if (ec)
51806785244SRatan Gupta                         {
51962598e31SEd Tanous                             BMCWEB_LOG_ERROR("DBUS response error: {}", ec);
52006785244SRatan Gupta                             messages::internalError(asyncResp->res);
52106785244SRatan Gupta                             return;
52206785244SRatan Gupta                         }
52306785244SRatan Gupta                         nlohmann::json& remoteRoleJson =
52406785244SRatan Gupta                             asyncResp->res
52506785244SRatan Gupta                                 .jsonValue[serverType]["RemoteRoleMapping"];
5261476687dSEd Tanous                         nlohmann::json::object_t roleMapEntry;
5271476687dSEd Tanous                         roleMapEntry["LocalRole"] = *localRole;
5281476687dSEd Tanous                         roleMapEntry["RemoteGroup"] = *remoteGroup;
529b2ba3072SPatrick Williams                         remoteRoleJson.emplace_back(std::move(roleMapEntry));
53006785244SRatan Gupta                     },
53106785244SRatan Gupta                     ldapDbusService, dbusObjectPath, ldapPrivMapperInterface,
5323174e4dfSEd Tanous                     "Create", *remoteGroup,
53306785244SRatan Gupta                     getPrivilegeFromRoleId(std::move(*localRole)));
53406785244SRatan Gupta             }
53506785244SRatan Gupta         }
53606785244SRatan Gupta     }
53706785244SRatan Gupta }
53806785244SRatan Gupta 
53906785244SRatan Gupta /**
5406973a582SRatan Gupta  * Function that retrieves all properties for LDAP config object
5416973a582SRatan Gupta  * into JSON
5426973a582SRatan Gupta  */
5436973a582SRatan Gupta template <typename CallbackFunc>
544504af5a0SPatrick Williams inline void getLDAPConfigData(const std::string& ldapType,
545504af5a0SPatrick Williams                               CallbackFunc&& callback)
5466973a582SRatan Gupta {
5472b73119cSGeorge Liu     constexpr std::array<std::string_view, 2> interfaces = {
5482b73119cSGeorge Liu         ldapEnableInterface, ldapConfigInterface};
54954fc587aSNagaraju Goruganti 
5502b73119cSGeorge Liu     dbus::utility::getDbusObject(
5512b73119cSGeorge Liu         ldapConfigObjectName, interfaces,
5528cb2c024SEd Tanous         [callback = std::forward<CallbackFunc>(callback),
553c1019828SEd Tanous          ldapType](const boost::system::error_code& ec,
554c1019828SEd Tanous                    const dbus::utility::MapperGetObject& resp) mutable {
55554fc587aSNagaraju Goruganti             if (ec || resp.empty())
55654fc587aSNagaraju Goruganti             {
557bf2ddedeSCarson Labrado                 BMCWEB_LOG_WARNING(
558bd79bce8SPatrick Williams                     "DBUS response error during getting of service name: {}",
559bd79bce8SPatrick Williams                     ec);
56023a21a1cSEd Tanous                 LDAPConfigData empty{};
56123a21a1cSEd Tanous                 callback(false, empty, ldapType);
56254fc587aSNagaraju Goruganti                 return;
56354fc587aSNagaraju Goruganti             }
56454fc587aSNagaraju Goruganti             std::string service = resp.begin()->first;
5655eb468daSGeorge Liu             sdbusplus::message::object_path path(ldapRootObject);
5665eb468daSGeorge Liu             dbus::utility::getManagedObjects(
5675eb468daSGeorge Liu                 service, path,
568bd79bce8SPatrick Williams                 [callback, ldapType](const boost::system::error_code& ec2,
569bd79bce8SPatrick Williams                                      const dbus::utility::ManagedObjectType&
570bd79bce8SPatrick Williams                                          ldapObjects) mutable {
5716973a582SRatan Gupta                     LDAPConfigData confData{};
5728b24275dSEd Tanous                     if (ec2)
5736973a582SRatan Gupta                     {
574ab828d7cSRatan Gupta                         callback(false, confData, ldapType);
575bf2ddedeSCarson Labrado                         BMCWEB_LOG_WARNING("D-Bus responses error: {}", ec2);
5766973a582SRatan Gupta                         return;
5776973a582SRatan Gupta                     }
578ab828d7cSRatan Gupta 
579ab828d7cSRatan Gupta                     std::string ldapDbusType;
58054fc587aSNagaraju Goruganti                     std::string searchString;
58154fc587aSNagaraju Goruganti 
582ab828d7cSRatan Gupta                     if (ldapType == "LDAP")
583ab828d7cSRatan Gupta                     {
5840fda0f12SGeorge Liu                         ldapDbusType =
5850fda0f12SGeorge Liu                             "xyz.openbmc_project.User.Ldap.Config.Type.OpenLdap";
58654fc587aSNagaraju Goruganti                         searchString = "openldap";
587ab828d7cSRatan Gupta                     }
588ab828d7cSRatan Gupta                     else if (ldapType == "ActiveDirectory")
589ab828d7cSRatan Gupta                     {
59054fc587aSNagaraju Goruganti                         ldapDbusType =
5910fda0f12SGeorge Liu                             "xyz.openbmc_project.User.Ldap.Config.Type.ActiveDirectory";
59254fc587aSNagaraju Goruganti                         searchString = "active_directory";
593ab828d7cSRatan Gupta                     }
594ab828d7cSRatan Gupta                     else
595ab828d7cSRatan Gupta                     {
596bd79bce8SPatrick Williams                         BMCWEB_LOG_ERROR(
597bd79bce8SPatrick Williams                             "Can't get the DbusType for the given type={}",
59862598e31SEd Tanous                             ldapType);
599ab828d7cSRatan Gupta                         callback(false, confData, ldapType);
600ab828d7cSRatan Gupta                         return;
601ab828d7cSRatan Gupta                     }
602ab828d7cSRatan Gupta 
603ab828d7cSRatan Gupta                     std::string ldapEnableInterfaceStr = ldapEnableInterface;
604ab828d7cSRatan Gupta                     std::string ldapConfigInterfaceStr = ldapConfigInterface;
605ab828d7cSRatan Gupta 
6066973a582SRatan Gupta                     for (const auto& object : ldapObjects)
6076973a582SRatan Gupta                     {
60854fc587aSNagaraju Goruganti                         // let's find the object whose ldap type is equal to the
60954fc587aSNagaraju Goruganti                         // given type
610bd79bce8SPatrick Williams                         if (object.first.str.find(searchString) ==
611bd79bce8SPatrick Williams                             std::string::npos)
6126973a582SRatan Gupta                         {
613ab828d7cSRatan Gupta                             continue;
614ab828d7cSRatan Gupta                         }
615ab828d7cSRatan Gupta 
6166973a582SRatan Gupta                         for (const auto& interface : object.second)
6176973a582SRatan Gupta                         {
6186973a582SRatan Gupta                             if (interface.first == ldapEnableInterfaceStr)
6196973a582SRatan Gupta                             {
6206973a582SRatan Gupta                                 // rest of the properties are string.
6216973a582SRatan Gupta                                 for (const auto& property : interface.second)
6226973a582SRatan Gupta                                 {
6236973a582SRatan Gupta                                     if (property.first == "Enabled")
6246973a582SRatan Gupta                                     {
6256973a582SRatan Gupta                                         const bool* value =
6266973a582SRatan Gupta                                             std::get_if<bool>(&property.second);
6276973a582SRatan Gupta                                         if (value == nullptr)
6286973a582SRatan Gupta                                         {
6296973a582SRatan Gupta                                             continue;
6306973a582SRatan Gupta                                         }
6316973a582SRatan Gupta                                         confData.serviceEnabled = *value;
6326973a582SRatan Gupta                                         break;
6336973a582SRatan Gupta                                     }
6346973a582SRatan Gupta                                 }
6356973a582SRatan Gupta                             }
6366973a582SRatan Gupta                             else if (interface.first == ldapConfigInterfaceStr)
6376973a582SRatan Gupta                             {
6386973a582SRatan Gupta                                 for (const auto& property : interface.second)
6396973a582SRatan Gupta                                 {
640271584abSEd Tanous                                     const std::string* strValue =
641bd79bce8SPatrick Williams                                         std::get_if<std::string>(
642bd79bce8SPatrick Williams                                             &property.second);
643271584abSEd Tanous                                     if (strValue == nullptr)
6446973a582SRatan Gupta                                     {
6456973a582SRatan Gupta                                         continue;
6466973a582SRatan Gupta                                     }
6476973a582SRatan Gupta                                     if (property.first == "LDAPServerURI")
6486973a582SRatan Gupta                                     {
649271584abSEd Tanous                                         confData.uri = *strValue;
6506973a582SRatan Gupta                                     }
6516973a582SRatan Gupta                                     else if (property.first == "LDAPBindDN")
6526973a582SRatan Gupta                                     {
653271584abSEd Tanous                                         confData.bindDN = *strValue;
6546973a582SRatan Gupta                                     }
6556973a582SRatan Gupta                                     else if (property.first == "LDAPBaseDN")
6566973a582SRatan Gupta                                     {
657271584abSEd Tanous                                         confData.baseDN = *strValue;
6586973a582SRatan Gupta                                     }
659bd79bce8SPatrick Williams                                     else if (property.first ==
660bd79bce8SPatrick Williams                                              "LDAPSearchScope")
6616973a582SRatan Gupta                                     {
662271584abSEd Tanous                                         confData.searchScope = *strValue;
6636973a582SRatan Gupta                                     }
664bd79bce8SPatrick Williams                                     else if (property.first ==
665bd79bce8SPatrick Williams                                              "GroupNameAttribute")
6666973a582SRatan Gupta                                     {
667271584abSEd Tanous                                         confData.groupAttribute = *strValue;
6686973a582SRatan Gupta                                     }
669bd79bce8SPatrick Williams                                     else if (property.first ==
670bd79bce8SPatrick Williams                                              "UserNameAttribute")
6716973a582SRatan Gupta                                     {
672271584abSEd Tanous                                         confData.userNameAttribute = *strValue;
6736973a582SRatan Gupta                                     }
67454fc587aSNagaraju Goruganti                                     else if (property.first == "LDAPType")
675ab828d7cSRatan Gupta                                     {
676271584abSEd Tanous                                         confData.serverType = *strValue;
67754fc587aSNagaraju Goruganti                                     }
67854fc587aSNagaraju Goruganti                                 }
67954fc587aSNagaraju Goruganti                             }
680bd79bce8SPatrick Williams                             else if (
681bd79bce8SPatrick Williams                                 interface.first ==
6820fda0f12SGeorge Liu                                 "xyz.openbmc_project.User.PrivilegeMapperEntry")
68354fc587aSNagaraju Goruganti                             {
68454fc587aSNagaraju Goruganti                                 LDAPRoleMapData roleMapData{};
68554fc587aSNagaraju Goruganti                                 for (const auto& property : interface.second)
68654fc587aSNagaraju Goruganti                                 {
687271584abSEd Tanous                                     const std::string* strValue =
688bd79bce8SPatrick Williams                                         std::get_if<std::string>(
689bd79bce8SPatrick Williams                                             &property.second);
69054fc587aSNagaraju Goruganti 
691271584abSEd Tanous                                     if (strValue == nullptr)
69254fc587aSNagaraju Goruganti                                     {
69354fc587aSNagaraju Goruganti                                         continue;
69454fc587aSNagaraju Goruganti                                     }
69554fc587aSNagaraju Goruganti 
69654fc587aSNagaraju Goruganti                                     if (property.first == "GroupName")
69754fc587aSNagaraju Goruganti                                     {
698271584abSEd Tanous                                         roleMapData.groupName = *strValue;
69954fc587aSNagaraju Goruganti                                     }
70054fc587aSNagaraju Goruganti                                     else if (property.first == "Privilege")
70154fc587aSNagaraju Goruganti                                     {
702271584abSEd Tanous                                         roleMapData.privilege = *strValue;
70354fc587aSNagaraju Goruganti                                     }
70454fc587aSNagaraju Goruganti                                 }
70554fc587aSNagaraju Goruganti 
706bd79bce8SPatrick Williams                                 confData.groupRoleList.emplace_back(
707bd79bce8SPatrick Williams                                     object.first.str, roleMapData);
70854fc587aSNagaraju Goruganti                             }
70954fc587aSNagaraju Goruganti                         }
71054fc587aSNagaraju Goruganti                     }
711ab828d7cSRatan Gupta                     callback(true, confData, ldapType);
7125eb468daSGeorge Liu                 });
7132b73119cSGeorge Liu         });
7146973a582SRatan Gupta }
7156973a582SRatan Gupta 
7168a07d286SRatan Gupta /**
7178a07d286SRatan Gupta  * @brief updates the LDAP server address and updates the
7188a07d286SRatan Gupta           json response with the new value.
7198a07d286SRatan Gupta  * @param serviceAddressList address to be updated.
7208a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7218a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7228a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7238a07d286SRatan Gupta  */
7248a07d286SRatan Gupta 
7254f48d5f6SEd Tanous inline void handleServiceAddressPatch(
7268a07d286SRatan Gupta     const std::vector<std::string>& serviceAddressList,
7278d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7288a07d286SRatan Gupta     const std::string& ldapServerElementName,
7298a07d286SRatan Gupta     const std::string& ldapConfigObject)
7308a07d286SRatan Gupta {
731e93abac6SGinu George     setDbusProperty(asyncResp, ldapServerElementName + "/ServiceAddress",
732e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapConfigInterface,
733e93abac6SGinu George                     "LDAPServerURI", serviceAddressList.front());
7348a07d286SRatan Gupta }
7358a07d286SRatan Gupta /**
7368a07d286SRatan Gupta  * @brief updates the LDAP Bind DN and updates the
7378a07d286SRatan Gupta           json response with the new value.
7388a07d286SRatan Gupta  * @param username name of the user 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 
744504af5a0SPatrick Williams inline void handleUserNamePatch(
745504af5a0SPatrick Williams     const std::string& username,
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/Username",
752e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapConfigInterface,
753e93abac6SGinu George                     "LDAPBindDN", username);
7548a07d286SRatan Gupta }
7558a07d286SRatan Gupta 
7568a07d286SRatan Gupta /**
7578a07d286SRatan Gupta  * @brief updates the LDAP password
7588a07d286SRatan Gupta  * @param password : ldap password which needs to be updated.
7598a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7608a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7618a07d286SRatan Gupta  *        server(openLDAP/ActiveDirectory)
7628a07d286SRatan Gupta  */
7638a07d286SRatan Gupta 
764504af5a0SPatrick Williams inline void handlePasswordPatch(
765504af5a0SPatrick Williams     const std::string& password,
7668d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7678a07d286SRatan Gupta     const std::string& ldapServerElementName,
7688a07d286SRatan Gupta     const std::string& ldapConfigObject)
7698a07d286SRatan Gupta {
770e93abac6SGinu George     setDbusProperty(asyncResp,
771d02aad39SEd Tanous                     ldapServerElementName + "/Authentication/Password",
772e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapConfigInterface,
773e93abac6SGinu George                     "LDAPBindDNPassword", password);
7748a07d286SRatan Gupta }
7758a07d286SRatan Gupta 
7768a07d286SRatan Gupta /**
7778a07d286SRatan Gupta  * @brief updates the LDAP BaseDN and updates the
7788a07d286SRatan Gupta           json response with the new value.
7798a07d286SRatan Gupta  * @param baseDNList baseDN list which needs to be updated.
7808a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7818a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7828a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7838a07d286SRatan Gupta  */
7848a07d286SRatan Gupta 
785504af5a0SPatrick Williams inline void handleBaseDNPatch(
786504af5a0SPatrick Williams     const std::vector<std::string>& baseDNList,
7878d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7888a07d286SRatan Gupta     const std::string& ldapServerElementName,
7898a07d286SRatan Gupta     const std::string& ldapConfigObject)
7908a07d286SRatan Gupta {
791e93abac6SGinu George     setDbusProperty(asyncResp,
792d02aad39SEd Tanous                     ldapServerElementName +
793d02aad39SEd Tanous                         "/LDAPService/SearchSettings/BaseDistinguishedNames",
794e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapConfigInterface,
795e93abac6SGinu George                     "LDAPBaseDN", baseDNList.front());
7968a07d286SRatan Gupta }
7978a07d286SRatan Gupta /**
7988a07d286SRatan Gupta  * @brief updates the LDAP user name attribute and updates the
7998a07d286SRatan Gupta           json response with the new value.
8008a07d286SRatan Gupta  * @param userNameAttribute attribute to be updated.
8018a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
8028a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
8038a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
8048a07d286SRatan Gupta  */
8058a07d286SRatan Gupta 
806bd79bce8SPatrick Williams inline void handleUserNameAttrPatch(
807bd79bce8SPatrick Williams     const std::string& userNameAttribute,
8088d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8098a07d286SRatan Gupta     const std::string& ldapServerElementName,
8108a07d286SRatan Gupta     const std::string& ldapConfigObject)
8118a07d286SRatan Gupta {
812bd79bce8SPatrick Williams     setDbusProperty(
813bd79bce8SPatrick Williams         asyncResp,
814bd79bce8SPatrick Williams         ldapServerElementName + "LDAPService/SearchSettings/UsernameAttribute",
815e93abac6SGinu George         ldapDbusService, ldapConfigObject, ldapConfigInterface,
816e93abac6SGinu George         "UserNameAttribute", userNameAttribute);
8178a07d286SRatan Gupta }
8188a07d286SRatan Gupta /**
8198a07d286SRatan Gupta  * @brief updates the LDAP group attribute and updates the
8208a07d286SRatan Gupta           json response with the new value.
8218a07d286SRatan Gupta  * @param groupsAttribute attribute to be updated.
8228a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
8238a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
8248a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
8258a07d286SRatan Gupta  */
8268a07d286SRatan Gupta 
8274f48d5f6SEd Tanous inline void handleGroupNameAttrPatch(
8288d1b46d7Szhanghch05     const std::string& groupsAttribute,
8298d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8308a07d286SRatan Gupta     const std::string& ldapServerElementName,
8318a07d286SRatan Gupta     const std::string& ldapConfigObject)
8328a07d286SRatan Gupta {
833bd79bce8SPatrick Williams     setDbusProperty(
834bd79bce8SPatrick Williams         asyncResp,
835bd79bce8SPatrick Williams         ldapServerElementName + "/LDAPService/SearchSettings/GroupsAttribute",
836e93abac6SGinu George         ldapDbusService, ldapConfigObject, ldapConfigInterface,
837e93abac6SGinu George         "GroupNameAttribute", groupsAttribute);
8388a07d286SRatan Gupta }
8398a07d286SRatan Gupta /**
8408a07d286SRatan Gupta  * @brief updates the LDAP service enable and updates the
8418a07d286SRatan Gupta           json response with the new value.
8428a07d286SRatan Gupta  * @param input JSON data.
8438a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
8448a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
8458a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
8468a07d286SRatan Gupta  */
8478a07d286SRatan Gupta 
8484f48d5f6SEd Tanous inline void handleServiceEnablePatch(
8496c51eab1SEd Tanous     bool serviceEnabled, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8508a07d286SRatan Gupta     const std::string& ldapServerElementName,
8518a07d286SRatan Gupta     const std::string& ldapConfigObject)
8528a07d286SRatan Gupta {
853e93abac6SGinu George     setDbusProperty(asyncResp, ldapServerElementName + "/ServiceEnabled",
854e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapEnableInterface,
855e93abac6SGinu George                     "Enabled", serviceEnabled);
8568a07d286SRatan Gupta }
8578a07d286SRatan Gupta 
858c1019828SEd Tanous struct AuthMethods
85978158631SZbigniew Kurzynski {
86078158631SZbigniew Kurzynski     std::optional<bool> basicAuth;
86178158631SZbigniew Kurzynski     std::optional<bool> cookie;
86278158631SZbigniew Kurzynski     std::optional<bool> sessionToken;
86378158631SZbigniew Kurzynski     std::optional<bool> xToken;
864501f1e58SZbigniew Kurzynski     std::optional<bool> tls;
865c1019828SEd Tanous };
86678158631SZbigniew Kurzynski 
867504af5a0SPatrick Williams inline void handleAuthMethodsPatch(
868504af5a0SPatrick Williams     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
869c1019828SEd Tanous     const AuthMethods& auth)
87078158631SZbigniew Kurzynski {
871c1019828SEd Tanous     persistent_data::AuthConfigMethods& authMethodsConfig =
87252cc112dSEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
87378158631SZbigniew Kurzynski 
874c1019828SEd Tanous     if (auth.basicAuth)
87578158631SZbigniew Kurzynski     {
87625b54dbaSEd Tanous         if constexpr (!BMCWEB_BASIC_AUTH)
87725b54dbaSEd Tanous         {
878f16f6263SAlan Kuo             messages::actionNotSupported(
8790fda0f12SGeorge Liu                 asyncResp->res,
8800fda0f12SGeorge Liu                 "Setting BasicAuth when basic-auth feature is disabled");
881f16f6263SAlan Kuo             return;
88225b54dbaSEd Tanous         }
88325b54dbaSEd Tanous 
884c1019828SEd Tanous         authMethodsConfig.basic = *auth.basicAuth;
88578158631SZbigniew Kurzynski     }
88678158631SZbigniew Kurzynski 
887c1019828SEd Tanous     if (auth.cookie)
88878158631SZbigniew Kurzynski     {
88925b54dbaSEd Tanous         if constexpr (!BMCWEB_COOKIE_AUTH)
89025b54dbaSEd Tanous         {
8910fda0f12SGeorge Liu             messages::actionNotSupported(
8920fda0f12SGeorge Liu                 asyncResp->res,
8930fda0f12SGeorge Liu                 "Setting Cookie when cookie-auth feature is disabled");
894f16f6263SAlan Kuo             return;
89525b54dbaSEd Tanous         }
896c1019828SEd Tanous         authMethodsConfig.cookie = *auth.cookie;
89778158631SZbigniew Kurzynski     }
89878158631SZbigniew Kurzynski 
899c1019828SEd Tanous     if (auth.sessionToken)
90078158631SZbigniew Kurzynski     {
90125b54dbaSEd Tanous         if constexpr (!BMCWEB_SESSION_AUTH)
90225b54dbaSEd Tanous         {
903f16f6263SAlan Kuo             messages::actionNotSupported(
9040fda0f12SGeorge Liu                 asyncResp->res,
9050fda0f12SGeorge Liu                 "Setting SessionToken when session-auth feature is disabled");
906f16f6263SAlan Kuo             return;
90725b54dbaSEd Tanous         }
908c1019828SEd Tanous         authMethodsConfig.sessionToken = *auth.sessionToken;
90978158631SZbigniew Kurzynski     }
91078158631SZbigniew Kurzynski 
911c1019828SEd Tanous     if (auth.xToken)
91278158631SZbigniew Kurzynski     {
91325b54dbaSEd Tanous         if constexpr (!BMCWEB_XTOKEN_AUTH)
91425b54dbaSEd Tanous         {
9150fda0f12SGeorge Liu             messages::actionNotSupported(
9160fda0f12SGeorge Liu                 asyncResp->res,
9170fda0f12SGeorge Liu                 "Setting XToken when xtoken-auth feature is disabled");
918f16f6263SAlan Kuo             return;
91925b54dbaSEd Tanous         }
920c1019828SEd Tanous         authMethodsConfig.xtoken = *auth.xToken;
92178158631SZbigniew Kurzynski     }
92278158631SZbigniew Kurzynski 
923c1019828SEd Tanous     if (auth.tls)
924501f1e58SZbigniew Kurzynski     {
92525b54dbaSEd Tanous         if constexpr (!BMCWEB_MUTUAL_TLS_AUTH)
92625b54dbaSEd Tanous         {
9270fda0f12SGeorge Liu             messages::actionNotSupported(
9280fda0f12SGeorge Liu                 asyncResp->res,
9290fda0f12SGeorge Liu                 "Setting TLS when mutual-tls-auth feature is disabled");
930f16f6263SAlan Kuo             return;
93125b54dbaSEd Tanous         }
932c1019828SEd Tanous         authMethodsConfig.tls = *auth.tls;
933501f1e58SZbigniew Kurzynski     }
934501f1e58SZbigniew Kurzynski 
93578158631SZbigniew Kurzynski     if (!authMethodsConfig.basic && !authMethodsConfig.cookie &&
936501f1e58SZbigniew Kurzynski         !authMethodsConfig.sessionToken && !authMethodsConfig.xtoken &&
937501f1e58SZbigniew Kurzynski         !authMethodsConfig.tls)
93878158631SZbigniew Kurzynski     {
93978158631SZbigniew Kurzynski         // Do not allow user to disable everything
94078158631SZbigniew Kurzynski         messages::actionNotSupported(asyncResp->res,
94178158631SZbigniew Kurzynski                                      "of disabling all available methods");
94278158631SZbigniew Kurzynski         return;
94378158631SZbigniew Kurzynski     }
94478158631SZbigniew Kurzynski 
94552cc112dSEd Tanous     persistent_data::SessionStore::getInstance().updateAuthMethodsConfig(
94652cc112dSEd Tanous         authMethodsConfig);
94778158631SZbigniew Kurzynski     // Save configuration immediately
94852cc112dSEd Tanous     persistent_data::getConfig().writeData();
94978158631SZbigniew Kurzynski 
95078158631SZbigniew Kurzynski     messages::success(asyncResp->res);
95178158631SZbigniew Kurzynski }
95278158631SZbigniew Kurzynski 
9538a07d286SRatan Gupta /**
9548a07d286SRatan Gupta  * @brief Get the required values from the given JSON, validates the
9558a07d286SRatan Gupta  *        value and create the LDAP config object.
9568a07d286SRatan Gupta  * @param input JSON data
9578a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
9588a07d286SRatan Gupta  * @param serverType Type of LDAP server(openLDAP/ActiveDirectory)
9598a07d286SRatan Gupta  */
9608a07d286SRatan Gupta 
96110cb44f3SEd Tanous struct LdapPatchParams
96210cb44f3SEd Tanous {
96310cb44f3SEd Tanous     std::optional<std::string> authType;
96410cb44f3SEd Tanous     std::optional<std::vector<std::string>> serviceAddressList;
96510cb44f3SEd Tanous     std::optional<bool> serviceEnabled;
96610cb44f3SEd Tanous     std::optional<std::vector<std::string>> baseDNList;
96710cb44f3SEd Tanous     std::optional<std::string> userNameAttribute;
96810cb44f3SEd Tanous     std::optional<std::string> groupsAttribute;
96910cb44f3SEd Tanous     std::optional<std::string> userName;
97010cb44f3SEd Tanous     std::optional<std::string> password;
97110cb44f3SEd Tanous     std::optional<
97210cb44f3SEd Tanous         std::vector<std::variant<nlohmann::json::object_t, std::nullptr_t>>>
97310cb44f3SEd Tanous         remoteRoleMapData;
97410cb44f3SEd Tanous };
97510cb44f3SEd Tanous 
97610cb44f3SEd Tanous inline void handleLDAPPatch(LdapPatchParams&& input,
9778d1b46d7Szhanghch05                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
9788a07d286SRatan Gupta                             const std::string& serverType)
9798a07d286SRatan Gupta {
980eb2bbe56SRatan Gupta     std::string dbusObjectPath;
981eb2bbe56SRatan Gupta     if (serverType == "ActiveDirectory")
982eb2bbe56SRatan Gupta     {
9832c70f800SEd Tanous         dbusObjectPath = adConfigObject;
984eb2bbe56SRatan Gupta     }
985eb2bbe56SRatan Gupta     else if (serverType == "LDAP")
986eb2bbe56SRatan Gupta     {
98723a21a1cSEd Tanous         dbusObjectPath = ldapConfigObjectName;
988eb2bbe56SRatan Gupta     }
989cb13a392SEd Tanous     else
990cb13a392SEd Tanous     {
99110cb44f3SEd Tanous         BMCWEB_LOG_ERROR("serverType wasn't AD or LDAP but was {}????",
99210cb44f3SEd Tanous                          serverType);
993cb13a392SEd Tanous         return;
994cb13a392SEd Tanous     }
995eb2bbe56SRatan Gupta 
99610cb44f3SEd Tanous     if (input.authType && *input.authType != "UsernameAndPassword")
9978a07d286SRatan Gupta     {
99810cb44f3SEd Tanous         messages::propertyValueNotInList(asyncResp->res, *input.authType,
999c1019828SEd Tanous                                          "AuthenticationType");
1000c1019828SEd Tanous         return;
10018a07d286SRatan Gupta     }
1002c1019828SEd Tanous 
100310cb44f3SEd Tanous     if (input.serviceAddressList)
10048a07d286SRatan Gupta     {
100510cb44f3SEd Tanous         if (input.serviceAddressList->empty())
10068a07d286SRatan Gupta         {
1007e2616cc5SEd Tanous             messages::propertyValueNotInList(
100810cb44f3SEd Tanous                 asyncResp->res, *input.serviceAddressList, "ServiceAddress");
10098a07d286SRatan Gupta             return;
10108a07d286SRatan Gupta         }
10118a07d286SRatan Gupta     }
101210cb44f3SEd Tanous     if (input.baseDNList)
10138a07d286SRatan Gupta     {
101410cb44f3SEd Tanous         if (input.baseDNList->empty())
10158a07d286SRatan Gupta         {
101610cb44f3SEd Tanous             messages::propertyValueNotInList(asyncResp->res, *input.baseDNList,
10178a07d286SRatan Gupta                                              "BaseDistinguishedNames");
10188a07d286SRatan Gupta             return;
10198a07d286SRatan Gupta         }
10208a07d286SRatan Gupta     }
10218a07d286SRatan Gupta 
10228a07d286SRatan Gupta     // nothing to update, then return
102310cb44f3SEd Tanous     if (!input.userName && !input.password && !input.serviceAddressList &&
102410cb44f3SEd Tanous         !input.baseDNList && !input.userNameAttribute &&
102510cb44f3SEd Tanous         !input.groupsAttribute && !input.serviceEnabled &&
102610cb44f3SEd Tanous         !input.remoteRoleMapData)
10278a07d286SRatan Gupta     {
10288a07d286SRatan Gupta         return;
10298a07d286SRatan Gupta     }
10308a07d286SRatan Gupta 
10318a07d286SRatan Gupta     // Get the existing resource first then keep modifying
10328a07d286SRatan Gupta     // whenever any property gets updated.
1033bd79bce8SPatrick Williams     getLDAPConfigData(serverType, [asyncResp, input = std::move(input),
103410cb44f3SEd Tanous                                    dbusObjectPath = std::move(dbusObjectPath)](
1035bd79bce8SPatrick Williams                                       bool success,
1036bd79bce8SPatrick Williams                                       const LDAPConfigData& confData,
1037c1019828SEd Tanous                                       const std::string& serverT) mutable {
10388a07d286SRatan Gupta         if (!success)
10398a07d286SRatan Gupta         {
10408a07d286SRatan Gupta             messages::internalError(asyncResp->res);
10418a07d286SRatan Gupta             return;
10428a07d286SRatan Gupta         }
10436c51eab1SEd Tanous         parseLDAPConfigData(asyncResp->res.jsonValue, confData, serverT);
10448a07d286SRatan Gupta         if (confData.serviceEnabled)
10458a07d286SRatan Gupta         {
10468a07d286SRatan Gupta             // Disable the service first and update the rest of
10478a07d286SRatan Gupta             // the properties.
10486c51eab1SEd Tanous             handleServiceEnablePatch(false, asyncResp, serverT, dbusObjectPath);
10498a07d286SRatan Gupta         }
10508a07d286SRatan Gupta 
105110cb44f3SEd Tanous         if (input.serviceAddressList)
10528a07d286SRatan Gupta         {
105310cb44f3SEd Tanous             handleServiceAddressPatch(*input.serviceAddressList, asyncResp,
105410cb44f3SEd Tanous                                       serverT, dbusObjectPath);
105510cb44f3SEd Tanous         }
105610cb44f3SEd Tanous         if (input.userName)
105710cb44f3SEd Tanous         {
105810cb44f3SEd Tanous             handleUserNamePatch(*input.userName, asyncResp, serverT,
10596c51eab1SEd Tanous                                 dbusObjectPath);
10608a07d286SRatan Gupta         }
106110cb44f3SEd Tanous         if (input.password)
10628a07d286SRatan Gupta         {
106310cb44f3SEd Tanous             handlePasswordPatch(*input.password, asyncResp, serverT,
106410cb44f3SEd Tanous                                 dbusObjectPath);
10658a07d286SRatan Gupta         }
10668a07d286SRatan Gupta 
106710cb44f3SEd Tanous         if (input.baseDNList)
10688a07d286SRatan Gupta         {
106910cb44f3SEd Tanous             handleBaseDNPatch(*input.baseDNList, asyncResp, serverT,
10706c51eab1SEd Tanous                               dbusObjectPath);
10718a07d286SRatan Gupta         }
107210cb44f3SEd Tanous         if (input.userNameAttribute)
10738a07d286SRatan Gupta         {
107410cb44f3SEd Tanous             handleUserNameAttrPatch(*input.userNameAttribute, asyncResp,
107510cb44f3SEd Tanous                                     serverT, dbusObjectPath);
107610cb44f3SEd Tanous         }
107710cb44f3SEd Tanous         if (input.groupsAttribute)
107810cb44f3SEd Tanous         {
107910cb44f3SEd Tanous             handleGroupNameAttrPatch(*input.groupsAttribute, asyncResp, serverT,
10806c51eab1SEd Tanous                                      dbusObjectPath);
10818a07d286SRatan Gupta         }
108210cb44f3SEd Tanous         if (input.serviceEnabled)
10838a07d286SRatan Gupta         {
10848a07d286SRatan Gupta             // if user has given the value as true then enable
10858a07d286SRatan Gupta             // the service. if user has given false then no-op
10868a07d286SRatan Gupta             // as service is already stopped.
108710cb44f3SEd Tanous             if (*input.serviceEnabled)
10888a07d286SRatan Gupta             {
108910cb44f3SEd Tanous                 handleServiceEnablePatch(*input.serviceEnabled, asyncResp,
109010cb44f3SEd Tanous                                          serverT, dbusObjectPath);
10918a07d286SRatan Gupta             }
10928a07d286SRatan Gupta         }
10938a07d286SRatan Gupta         else
10948a07d286SRatan Gupta         {
10958a07d286SRatan Gupta             // if user has not given the service enabled value
10968a07d286SRatan Gupta             // then revert it to the same state as it was
10978a07d286SRatan Gupta             // before.
10988a07d286SRatan Gupta             handleServiceEnablePatch(confData.serviceEnabled, asyncResp,
109923a21a1cSEd Tanous                                      serverT, dbusObjectPath);
11008a07d286SRatan Gupta         }
110106785244SRatan Gupta 
110210cb44f3SEd Tanous         if (input.remoteRoleMapData)
110306785244SRatan Gupta         {
11046c51eab1SEd Tanous             handleRoleMapPatch(asyncResp, confData.groupRoleList, serverT,
110510cb44f3SEd Tanous                                *input.remoteRoleMapData);
110606785244SRatan Gupta         }
11078a07d286SRatan Gupta     });
11088a07d286SRatan Gupta }
1109d4b5443fSEd Tanous 
1110492ec93aSEd Tanous struct UserUpdateParams
11111abe55efSEd Tanous {
1112492ec93aSEd Tanous     std::string username;
1113492ec93aSEd Tanous     std::optional<std::string> password;
1114492ec93aSEd Tanous     std::optional<bool> enabled;
1115492ec93aSEd Tanous     std::optional<std::string> roleId;
1116492ec93aSEd Tanous     std::optional<bool> locked;
1117492ec93aSEd Tanous     std::optional<std::vector<std::string>> accountTypes;
1118492ec93aSEd Tanous     bool userSelf;
1119492ec93aSEd Tanous     std::shared_ptr<persistent_data::UserSession> session;
1120492ec93aSEd Tanous     std::string dbusObjectPath;
1121492ec93aSEd Tanous };
11226c51eab1SEd Tanous 
1123504af5a0SPatrick Williams inline void afterVerifyUserExists(
1124504af5a0SPatrick Williams     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1125492ec93aSEd Tanous     const UserUpdateParams& params, int rc)
1126492ec93aSEd Tanous {
1127e662eae8SEd Tanous     if (rc <= 0)
11286c51eab1SEd Tanous     {
1129d8a5d5d8SJiaqing Zhao         messages::resourceNotFound(asyncResp->res, "ManagerAccount",
1130492ec93aSEd Tanous                                    params.username);
11316c51eab1SEd Tanous         return;
11326c51eab1SEd Tanous     }
11336c51eab1SEd Tanous 
1134492ec93aSEd Tanous     if (params.password)
11356c51eab1SEd Tanous     {
1136492ec93aSEd Tanous         int retval = pamUpdatePassword(params.username, *params.password);
11376c51eab1SEd Tanous 
11386c51eab1SEd Tanous         if (retval == PAM_USER_UNKNOWN)
11396c51eab1SEd Tanous         {
1140d8a5d5d8SJiaqing Zhao             messages::resourceNotFound(asyncResp->res, "ManagerAccount",
1141492ec93aSEd Tanous                                        params.username);
11426c51eab1SEd Tanous         }
11436c51eab1SEd Tanous         else if (retval == PAM_AUTHTOK_ERR)
11446c51eab1SEd Tanous         {
11456c51eab1SEd Tanous             // If password is invalid
11469bd80831SJason M. Bills             messages::propertyValueFormatError(asyncResp->res, nullptr,
11479bd80831SJason M. Bills                                                "Password");
114862598e31SEd Tanous             BMCWEB_LOG_ERROR("pamUpdatePassword Failed");
11496c51eab1SEd Tanous         }
11506c51eab1SEd Tanous         else if (retval != PAM_SUCCESS)
11516c51eab1SEd Tanous         {
11526c51eab1SEd Tanous             messages::internalError(asyncResp->res);
11536c51eab1SEd Tanous             return;
11546c51eab1SEd Tanous         }
1155e7b1b62bSEd Tanous         else
1156e7b1b62bSEd Tanous         {
1157bd79bce8SPatrick Williams             // Remove existing sessions of the user when password
1158bd79bce8SPatrick Williams             // changed
1159e518ef32SRavi Teja             persistent_data::SessionStore::getInstance()
1160492ec93aSEd Tanous                 .removeSessionsByUsernameExceptSession(params.username,
1161492ec93aSEd Tanous                                                        params.session);
1162e7b1b62bSEd Tanous             messages::success(asyncResp->res);
1163e7b1b62bSEd Tanous         }
11646c51eab1SEd Tanous     }
11656c51eab1SEd Tanous 
1166492ec93aSEd Tanous     if (params.enabled)
11676c51eab1SEd Tanous     {
1168bd79bce8SPatrick Williams         setDbusProperty(
1169bd79bce8SPatrick Williams             asyncResp, "Enabled", "xyz.openbmc_project.User.Manager",
1170492ec93aSEd Tanous             params.dbusObjectPath, "xyz.openbmc_project.User.Attributes",
1171492ec93aSEd Tanous             "UserEnabled", *params.enabled);
11726c51eab1SEd Tanous     }
11736c51eab1SEd Tanous 
1174492ec93aSEd Tanous     if (params.roleId)
11756c51eab1SEd Tanous     {
1176492ec93aSEd Tanous         std::string priv = getPrivilegeFromRoleId(*params.roleId);
11776c51eab1SEd Tanous         if (priv.empty())
11786c51eab1SEd Tanous         {
1179492ec93aSEd Tanous             messages::propertyValueNotInList(asyncResp->res, true, "Locked");
11806c51eab1SEd Tanous             return;
11816c51eab1SEd Tanous         }
1182492ec93aSEd Tanous         setDbusProperty(asyncResp, "RoleId", "xyz.openbmc_project.User.Manager",
1183492ec93aSEd Tanous                         params.dbusObjectPath,
1184492ec93aSEd Tanous                         "xyz.openbmc_project.User.Attributes", "UserPrivilege",
1185492ec93aSEd Tanous                         priv);
11866c51eab1SEd Tanous     }
11876c51eab1SEd Tanous 
1188492ec93aSEd Tanous     if (params.locked)
11896c51eab1SEd Tanous     {
11906c51eab1SEd Tanous         // admin can unlock the account which is locked by
11916c51eab1SEd Tanous         // successive authentication failures but admin should
11926c51eab1SEd Tanous         // not be allowed to lock an account.
1193492ec93aSEd Tanous         if (*params.locked)
11946c51eab1SEd Tanous         {
1195492ec93aSEd Tanous             messages::propertyValueNotInList(asyncResp->res, "true", "Locked");
11966c51eab1SEd Tanous             return;
11976c51eab1SEd Tanous         }
1198492ec93aSEd Tanous         setDbusProperty(asyncResp, "Locked", "xyz.openbmc_project.User.Manager",
1199492ec93aSEd Tanous                         params.dbusObjectPath,
1200492ec93aSEd Tanous                         "xyz.openbmc_project.User.Attributes",
1201492ec93aSEd Tanous                         "UserLockedForFailedAttempt", *params.locked);
12026c51eab1SEd Tanous     }
120358345856SAbhishek Patel 
1204492ec93aSEd Tanous     if (params.accountTypes)
120558345856SAbhishek Patel     {
1206492ec93aSEd Tanous         patchAccountTypes(*params.accountTypes, asyncResp,
1207492ec93aSEd Tanous                           params.dbusObjectPath, params.userSelf);
120858345856SAbhishek Patel     }
1209492ec93aSEd Tanous }
1210492ec93aSEd Tanous 
1211492ec93aSEd Tanous inline void updateUserProperties(
1212492ec93aSEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1213492ec93aSEd Tanous     const std::string& username, const std::optional<std::string>& password,
1214492ec93aSEd Tanous     const std::optional<bool>& enabled,
1215492ec93aSEd Tanous     const std::optional<std::string>& roleId, const std::optional<bool>& locked,
1216492ec93aSEd Tanous     const std::optional<std::vector<std::string>>& accountTypes, bool userSelf,
1217492ec93aSEd Tanous     const std::shared_ptr<persistent_data::UserSession>& session)
1218492ec93aSEd Tanous {
1219492ec93aSEd Tanous     sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
1220492ec93aSEd Tanous     tempObjPath /= username;
1221492ec93aSEd Tanous     std::string dbusObjectPath(tempObjPath);
1222492ec93aSEd Tanous 
1223492ec93aSEd Tanous     UserUpdateParams params{username, password, enabled,
1224492ec93aSEd Tanous                             roleId,   locked,   accountTypes,
1225492ec93aSEd Tanous                             userSelf, session,  dbusObjectPath};
1226492ec93aSEd Tanous 
1227492ec93aSEd Tanous     dbus::utility::checkDbusPathExists(
1228492ec93aSEd Tanous         dbusObjectPath,
1229492ec93aSEd Tanous         std::bind_front(afterVerifyUserExists, asyncResp, std::move(params)));
12306c51eab1SEd Tanous }
12316c51eab1SEd Tanous 
12324c7d4d33SEd Tanous inline void handleAccountServiceHead(
12334c7d4d33SEd Tanous     App& app, const crow::Request& req,
12341ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
12356c51eab1SEd Tanous {
12363ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
123745ca1b86SEd Tanous     {
123845ca1b86SEd Tanous         return;
123945ca1b86SEd Tanous     }
12404c7d4d33SEd Tanous     asyncResp->res.addHeader(
12414c7d4d33SEd Tanous         boost::beast::http::field::link,
12424c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/AccountService/AccountService.json>; rel=describedby");
12434c7d4d33SEd Tanous }
12444c7d4d33SEd Tanous 
1245504af5a0SPatrick Williams inline void getClientCertificates(
1246504af5a0SPatrick Williams     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
12471aa375b8SEd Tanous     const nlohmann::json::json_pointer& keyLocation)
12481aa375b8SEd Tanous {
12491aa375b8SEd Tanous     boost::urls::url url(
12501aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates");
12511aa375b8SEd Tanous     std::array<std::string_view, 1> interfaces = {
12521aa375b8SEd Tanous         "xyz.openbmc_project.Certs.Certificate"};
12531aa375b8SEd Tanous     std::string path = "/xyz/openbmc_project/certs/authority/truststore";
12541aa375b8SEd Tanous 
12551aa375b8SEd Tanous     collection_util::getCollectionToKey(asyncResp, url, interfaces, path,
12561aa375b8SEd Tanous                                         keyLocation);
12571aa375b8SEd Tanous }
12581aa375b8SEd Tanous 
12591aa375b8SEd Tanous inline void handleAccountServiceClientCertificatesInstanceHead(
12601aa375b8SEd Tanous     App& app, const crow::Request& req,
12611aa375b8SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
12621aa375b8SEd Tanous     const std::string& /*id*/)
12631aa375b8SEd Tanous {
12641aa375b8SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
12651aa375b8SEd Tanous     {
12661aa375b8SEd Tanous         return;
12671aa375b8SEd Tanous     }
12681aa375b8SEd Tanous 
12691aa375b8SEd Tanous     asyncResp->res.addHeader(
12701aa375b8SEd Tanous         boost::beast::http::field::link,
12711aa375b8SEd Tanous         "</redfish/v1/JsonSchemas/Certificate/Certificate.json>; rel=describedby");
12721aa375b8SEd Tanous }
12731aa375b8SEd Tanous 
12741aa375b8SEd Tanous inline void handleAccountServiceClientCertificatesInstanceGet(
12751aa375b8SEd Tanous     App& app, const crow::Request& req,
12761aa375b8SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, const std::string& id)
12771aa375b8SEd Tanous {
12781aa375b8SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
12791aa375b8SEd Tanous     {
12801aa375b8SEd Tanous         return;
12811aa375b8SEd Tanous     }
12821aa375b8SEd Tanous     BMCWEB_LOG_DEBUG("ClientCertificate Certificate ID={}", id);
12831aa375b8SEd Tanous     const boost::urls::url certURL = boost::urls::format(
12841aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/{}",
12851aa375b8SEd Tanous         id);
12861aa375b8SEd Tanous     std::string objPath =
12871aa375b8SEd Tanous         sdbusplus::message::object_path(certs::authorityObjectPath) / id;
12881aa375b8SEd Tanous     getCertificateProperties(
12891aa375b8SEd Tanous         asyncResp, objPath,
12901aa375b8SEd Tanous         "xyz.openbmc_project.Certs.Manager.Authority.Truststore", id, certURL,
12911aa375b8SEd Tanous         "Client Certificate");
12921aa375b8SEd Tanous }
12931aa375b8SEd Tanous 
12941aa375b8SEd Tanous inline void handleAccountServiceClientCertificatesHead(
12951aa375b8SEd Tanous     App& app, const crow::Request& req,
12961aa375b8SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
12971aa375b8SEd Tanous {
12981aa375b8SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
12991aa375b8SEd Tanous     {
13001aa375b8SEd Tanous         return;
13011aa375b8SEd Tanous     }
13021aa375b8SEd Tanous 
13031aa375b8SEd Tanous     asyncResp->res.addHeader(
13041aa375b8SEd Tanous         boost::beast::http::field::link,
13051aa375b8SEd Tanous         "</redfish/v1/JsonSchemas/CertificateCollection/CertificateCollection.json>; rel=describedby");
13061aa375b8SEd Tanous }
13071aa375b8SEd Tanous 
13081aa375b8SEd Tanous inline void handleAccountServiceClientCertificatesGet(
13091aa375b8SEd Tanous     App& app, const crow::Request& req,
13101aa375b8SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
13111aa375b8SEd Tanous {
13121aa375b8SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
13131aa375b8SEd Tanous     {
13141aa375b8SEd Tanous         return;
13151aa375b8SEd Tanous     }
13160f09ed32SMyung Bae 
13170f09ed32SMyung Bae     nlohmann::json& json = asyncResp->res.jsonValue;
13180f09ed32SMyung Bae     json["@odata.id"] =
13190f09ed32SMyung Bae         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates";
13200f09ed32SMyung Bae     json["@odata.type"] = "#CertificateCollection.CertificateCollection";
13210f09ed32SMyung Bae     json["Name"] = "Certificates Collection";
13220f09ed32SMyung Bae     json["Description"] = "Multi-factor Authentication Client Certificates";
13231aa375b8SEd Tanous     getClientCertificates(asyncResp, "/Members"_json_pointer);
13241aa375b8SEd Tanous }
13251aa375b8SEd Tanous 
13263ce3688aSEd Tanous using account_service::CertificateMappingAttribute;
13273ce3688aSEd Tanous using persistent_data::MTLSCommonNameParseMode;
1328504af5a0SPatrick Williams inline CertificateMappingAttribute getCertificateMapping(
1329504af5a0SPatrick Williams     MTLSCommonNameParseMode parse)
13303ce3688aSEd Tanous {
13313ce3688aSEd Tanous     switch (parse)
13323ce3688aSEd Tanous     {
13333ce3688aSEd Tanous         case MTLSCommonNameParseMode::CommonName:
13343ce3688aSEd Tanous         {
13353ce3688aSEd Tanous             return CertificateMappingAttribute::CommonName;
13363ce3688aSEd Tanous         }
13373ce3688aSEd Tanous         case MTLSCommonNameParseMode::Whole:
13383ce3688aSEd Tanous         {
13393ce3688aSEd Tanous             return CertificateMappingAttribute::Whole;
13403ce3688aSEd Tanous         }
13413ce3688aSEd Tanous         case MTLSCommonNameParseMode::UserPrincipalName:
13423ce3688aSEd Tanous         {
13433ce3688aSEd Tanous             return CertificateMappingAttribute::UserPrincipalName;
13443ce3688aSEd Tanous         }
13453ce3688aSEd Tanous         default:
13463ce3688aSEd Tanous         {
13473ce3688aSEd Tanous             return CertificateMappingAttribute::Invalid;
13483ce3688aSEd Tanous         }
13493ce3688aSEd Tanous     }
13503ce3688aSEd Tanous }
13513ce3688aSEd Tanous 
1352504af5a0SPatrick Williams inline void handleAccountServiceGet(
1353504af5a0SPatrick Williams     App& app, const crow::Request& req,
13544c7d4d33SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
13554c7d4d33SEd Tanous {
1356afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1357afd369c6SJiaqing Zhao     {
1358afd369c6SJiaqing Zhao         return;
1359afd369c6SJiaqing Zhao     }
13603e72c202SNinad Palsule 
13613e72c202SNinad Palsule     if (req.session == nullptr)
13623e72c202SNinad Palsule     {
13633e72c202SNinad Palsule         messages::internalError(asyncResp->res);
13643e72c202SNinad Palsule         return;
13653e72c202SNinad Palsule     }
13663e72c202SNinad Palsule 
1367c1019828SEd Tanous     const persistent_data::AuthConfigMethods& authMethodsConfig =
1368c1019828SEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
1369c1019828SEd Tanous 
1370afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1371afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1372afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/AccountService/AccountService.json>; rel=describedby");
1373afd369c6SJiaqing Zhao 
13741476687dSEd Tanous     nlohmann::json& json = asyncResp->res.jsonValue;
13751476687dSEd Tanous     json["@odata.id"] = "/redfish/v1/AccountService";
1376482a69e7SRavi Teja     json["@odata.type"] = "#AccountService.v1_15_0.AccountService";
13771476687dSEd Tanous     json["Id"] = "AccountService";
13781476687dSEd Tanous     json["Name"] = "Account Service";
13791476687dSEd Tanous     json["Description"] = "Account Service";
13801476687dSEd Tanous     json["ServiceEnabled"] = true;
13811476687dSEd Tanous     json["MaxPasswordLength"] = 20;
13821ef4c342SEd Tanous     json["Accounts"]["@odata.id"] = "/redfish/v1/AccountService/Accounts";
13831476687dSEd Tanous     json["Roles"]["@odata.id"] = "/redfish/v1/AccountService/Roles";
1384482a69e7SRavi Teja     json["HTTPBasicAuth"] = authMethodsConfig.basic
1385482a69e7SRavi Teja                                 ? account_service::BasicAuthState::Enabled
1386482a69e7SRavi Teja                                 : account_service::BasicAuthState::Disabled;
1387482a69e7SRavi Teja 
1388482a69e7SRavi Teja     nlohmann::json::array_t allowed;
1389482a69e7SRavi Teja     allowed.emplace_back(account_service::BasicAuthState::Enabled);
1390482a69e7SRavi Teja     allowed.emplace_back(account_service::BasicAuthState::Disabled);
1391482a69e7SRavi Teja     json["HTTPBasicAuth@AllowableValues"] = std::move(allowed);
1392482a69e7SRavi Teja 
13931aa375b8SEd Tanous     nlohmann::json::object_t clientCertificate;
13941aa375b8SEd Tanous     clientCertificate["Enabled"] = authMethodsConfig.tls;
13953281bcf1SEd Tanous     clientCertificate["RespondToUnauthenticatedClients"] =
13963281bcf1SEd Tanous         !authMethodsConfig.tlsStrict;
13973ce3688aSEd Tanous 
13983ce3688aSEd Tanous     using account_service::CertificateMappingAttribute;
13993ce3688aSEd Tanous 
14003ce3688aSEd Tanous     CertificateMappingAttribute mapping =
14013ce3688aSEd Tanous         getCertificateMapping(authMethodsConfig.mTLSCommonNameParsingMode);
14023ce3688aSEd Tanous     if (mapping == CertificateMappingAttribute::Invalid)
14033ce3688aSEd Tanous     {
14043ce3688aSEd Tanous         messages::internalError(asyncResp->res);
14053ce3688aSEd Tanous     }
14063ce3688aSEd Tanous     else
14073ce3688aSEd Tanous     {
14083ce3688aSEd Tanous         clientCertificate["CertificateMappingAttribute"] = mapping;
14093ce3688aSEd Tanous     }
14101aa375b8SEd Tanous     nlohmann::json::object_t certificates;
14111aa375b8SEd Tanous     certificates["@odata.id"] =
14121aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates";
14131aa375b8SEd Tanous     certificates["@odata.type"] =
14141aa375b8SEd Tanous         "#CertificateCollection.CertificateCollection";
14151aa375b8SEd Tanous     clientCertificate["Certificates"] = std::move(certificates);
14161aa375b8SEd Tanous     json["MultiFactorAuth"]["ClientCertificate"] = std::move(clientCertificate);
14171aa375b8SEd Tanous 
14181aa375b8SEd Tanous     getClientCertificates(
14191aa375b8SEd Tanous         asyncResp,
14201aa375b8SEd Tanous         "/MultiFactorAuth/ClientCertificate/Certificates/Members"_json_pointer);
14211aa375b8SEd Tanous 
14221476687dSEd Tanous     json["Oem"]["OpenBMC"]["@odata.type"] =
14235b5574acSEd Tanous         "#OpenBMCAccountService.v1_0_0.AccountService";
14241476687dSEd Tanous     json["Oem"]["OpenBMC"]["@odata.id"] =
14251476687dSEd Tanous         "/redfish/v1/AccountService#/Oem/OpenBMC";
14261476687dSEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["BasicAuth"] =
14271476687dSEd Tanous         authMethodsConfig.basic;
14281476687dSEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["SessionToken"] =
14291476687dSEd Tanous         authMethodsConfig.sessionToken;
14301ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["XToken"] = authMethodsConfig.xtoken;
14311ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["Cookie"] = authMethodsConfig.cookie;
14321ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["TLS"] = authMethodsConfig.tls;
14331476687dSEd Tanous 
14341ef4c342SEd Tanous     // /redfish/v1/AccountService/LDAP/Certificates is something only
14351ef4c342SEd Tanous     // ConfigureManager can access then only display when the user has
14361ef4c342SEd Tanous     // permissions ConfigureManager
143772048780SAbhishek Patel     Privileges effectiveUserPrivileges =
14383e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
143972048780SAbhishek Patel 
144072048780SAbhishek Patel     if (isOperationAllowedWithPrivileges({{"ConfigureManager"}},
144172048780SAbhishek Patel                                          effectiveUserPrivileges))
144272048780SAbhishek Patel     {
14431ef4c342SEd Tanous         asyncResp->res.jsonValue["LDAP"]["Certificates"]["@odata.id"] =
14441476687dSEd Tanous             "/redfish/v1/AccountService/LDAP/Certificates";
144572048780SAbhishek Patel     }
1446deae6a78SEd Tanous     dbus::utility::getAllProperties(
1447deae6a78SEd Tanous         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
1448deae6a78SEd Tanous         "xyz.openbmc_project.User.AccountPolicy",
14495e7e2dc5SEd Tanous         [asyncResp](const boost::system::error_code& ec,
14501ef4c342SEd Tanous                     const dbus::utility::DBusPropertiesMap& propertiesList) {
14513d958bbcSAppaRao Puli             if (ec)
14523d958bbcSAppaRao Puli             {
14533d958bbcSAppaRao Puli                 messages::internalError(asyncResp->res);
14543d958bbcSAppaRao Puli                 return;
14553d958bbcSAppaRao Puli             }
1456d1bde9e5SKrzysztof Grobelny 
145762598e31SEd Tanous             BMCWEB_LOG_DEBUG("Got {} properties for AccountService",
145862598e31SEd Tanous                              propertiesList.size());
1459d1bde9e5SKrzysztof Grobelny 
1460d1bde9e5SKrzysztof Grobelny             const uint8_t* minPasswordLength = nullptr;
1461d1bde9e5SKrzysztof Grobelny             const uint32_t* accountUnlockTimeout = nullptr;
1462d1bde9e5SKrzysztof Grobelny             const uint16_t* maxLoginAttemptBeforeLockout = nullptr;
1463d1bde9e5SKrzysztof Grobelny 
1464d1bde9e5SKrzysztof Grobelny             const bool success = sdbusplus::unpackPropertiesNoThrow(
1465d1bde9e5SKrzysztof Grobelny                 dbus_utils::UnpackErrorPrinter(), propertiesList,
1466d1bde9e5SKrzysztof Grobelny                 "MinPasswordLength", minPasswordLength, "AccountUnlockTimeout",
1467d1bde9e5SKrzysztof Grobelny                 accountUnlockTimeout, "MaxLoginAttemptBeforeLockout",
1468d1bde9e5SKrzysztof Grobelny                 maxLoginAttemptBeforeLockout);
1469d1bde9e5SKrzysztof Grobelny 
1470d1bde9e5SKrzysztof Grobelny             if (!success)
14713d958bbcSAppaRao Puli             {
1472d1bde9e5SKrzysztof Grobelny                 messages::internalError(asyncResp->res);
1473d1bde9e5SKrzysztof Grobelny                 return;
14743d958bbcSAppaRao Puli             }
1475d1bde9e5SKrzysztof Grobelny 
1476d1bde9e5SKrzysztof Grobelny             if (minPasswordLength != nullptr)
14773d958bbcSAppaRao Puli             {
1478bd79bce8SPatrick Williams                 asyncResp->res.jsonValue["MinPasswordLength"] =
1479bd79bce8SPatrick Williams                     *minPasswordLength;
14803d958bbcSAppaRao Puli             }
1481d1bde9e5SKrzysztof Grobelny 
1482d1bde9e5SKrzysztof Grobelny             if (accountUnlockTimeout != nullptr)
14833d958bbcSAppaRao Puli             {
1484d1bde9e5SKrzysztof Grobelny                 asyncResp->res.jsonValue["AccountLockoutDuration"] =
1485d1bde9e5SKrzysztof Grobelny                     *accountUnlockTimeout;
1486d1bde9e5SKrzysztof Grobelny             }
1487d1bde9e5SKrzysztof Grobelny 
1488d1bde9e5SKrzysztof Grobelny             if (maxLoginAttemptBeforeLockout != nullptr)
14893d958bbcSAppaRao Puli             {
1490002d39b4SEd Tanous                 asyncResp->res.jsonValue["AccountLockoutThreshold"] =
1491d1bde9e5SKrzysztof Grobelny                     *maxLoginAttemptBeforeLockout;
14923d958bbcSAppaRao Puli             }
1493d1bde9e5SKrzysztof Grobelny         });
14946973a582SRatan Gupta 
149502cad96eSEd Tanous     auto callback = [asyncResp](bool success, const LDAPConfigData& confData,
1496ab828d7cSRatan Gupta                                 const std::string& ldapType) {
1497cb13a392SEd Tanous         if (!success)
1498cb13a392SEd Tanous         {
1499cb13a392SEd Tanous             return;
1500cb13a392SEd Tanous         }
1501002d39b4SEd Tanous         parseLDAPConfigData(asyncResp->res.jsonValue, confData, ldapType);
1502ab828d7cSRatan Gupta     };
1503ab828d7cSRatan Gupta 
1504ab828d7cSRatan Gupta     getLDAPConfigData("LDAP", callback);
1505ab828d7cSRatan Gupta     getLDAPConfigData("ActiveDirectory", callback);
15061ef4c342SEd Tanous }
15076973a582SRatan Gupta 
1508bd79bce8SPatrick Williams inline void handleCertificateMappingAttributePatch(
1509bd79bce8SPatrick Williams     crow::Response& res, const std::string& certMapAttribute)
15103ce3688aSEd Tanous {
15113ce3688aSEd Tanous     MTLSCommonNameParseMode parseMode =
15123ce3688aSEd Tanous         persistent_data::getMTLSCommonNameParseMode(certMapAttribute);
15133ce3688aSEd Tanous     if (parseMode == MTLSCommonNameParseMode::Invalid)
15143ce3688aSEd Tanous     {
15153ce3688aSEd Tanous         messages::propertyValueNotInList(res, "CertificateMappingAttribute",
15163ce3688aSEd Tanous                                          certMapAttribute);
15173ce3688aSEd Tanous         return;
15183ce3688aSEd Tanous     }
15193ce3688aSEd Tanous 
15203ce3688aSEd Tanous     persistent_data::AuthConfigMethods& authMethodsConfig =
15213ce3688aSEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
15223ce3688aSEd Tanous     authMethodsConfig.mTLSCommonNameParsingMode = parseMode;
15233ce3688aSEd Tanous }
15243ce3688aSEd Tanous 
15253281bcf1SEd Tanous inline void handleRespondToUnauthenticatedClientsPatch(
15263281bcf1SEd Tanous     App& app, const crow::Request& req, crow::Response& res,
15273281bcf1SEd Tanous     bool respondToUnauthenticatedClients)
15283281bcf1SEd Tanous {
15293281bcf1SEd Tanous     if (req.session != nullptr)
15303281bcf1SEd Tanous     {
15313281bcf1SEd Tanous         // Sanity check.  If the user isn't currently authenticated with mutual
15323281bcf1SEd Tanous         // TLS, they very likely are about to permanently lock themselves out.
15333281bcf1SEd Tanous         // Make sure they're using mutual TLS before allowing locking.
15343281bcf1SEd Tanous         if (req.session->sessionType != persistent_data::SessionType::MutualTLS)
15353281bcf1SEd Tanous         {
15363281bcf1SEd Tanous             messages::propertyValueExternalConflict(
15373281bcf1SEd Tanous                 res,
15383281bcf1SEd Tanous                 "MultiFactorAuth/ClientCertificate/RespondToUnauthenticatedClients",
15393281bcf1SEd Tanous                 respondToUnauthenticatedClients);
15403281bcf1SEd Tanous             return;
15413281bcf1SEd Tanous         }
15423281bcf1SEd Tanous     }
15433281bcf1SEd Tanous 
15443281bcf1SEd Tanous     persistent_data::AuthConfigMethods& authMethodsConfig =
15453281bcf1SEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
15463281bcf1SEd Tanous 
15473281bcf1SEd Tanous     // Change the settings
15483281bcf1SEd Tanous     authMethodsConfig.tlsStrict = !respondToUnauthenticatedClients;
15493281bcf1SEd Tanous 
15503281bcf1SEd Tanous     // Write settings to disk
15513281bcf1SEd Tanous     persistent_data::getConfig().writeData();
15523281bcf1SEd Tanous 
15533281bcf1SEd Tanous     // Trigger a reload, to apply the new settings to new connections
15543281bcf1SEd Tanous     app.loadCertificate();
15553281bcf1SEd Tanous }
15563281bcf1SEd Tanous 
15571ef4c342SEd Tanous inline void handleAccountServicePatch(
15581ef4c342SEd Tanous     App& app, const crow::Request& req,
15591ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
15601ef4c342SEd Tanous {
15613ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
156245ca1b86SEd Tanous     {
156345ca1b86SEd Tanous         return;
156445ca1b86SEd Tanous     }
1565f5ffd806SEd Tanous     std::optional<uint32_t> unlockTimeout;
1566f5ffd806SEd Tanous     std::optional<uint16_t> lockoutThreshold;
1567ef73ad0dSPaul Fertser     std::optional<uint8_t> minPasswordLength;
1568f5ffd806SEd Tanous     std::optional<uint16_t> maxPasswordLength;
156910cb44f3SEd Tanous     LdapPatchParams ldapObject;
15703ce3688aSEd Tanous     std::optional<std::string> certificateMappingAttribute;
15713281bcf1SEd Tanous     std::optional<bool> respondToUnauthenticatedClients;
157210cb44f3SEd Tanous     LdapPatchParams activeDirectoryObject;
1573c1019828SEd Tanous     AuthMethods auth;
1574482a69e7SRavi Teja     std::optional<std::string> httpBasicAuth;
15753ce3688aSEd Tanous 
1576afc474aeSMyung Bae     if (!json_util::readJsonPatch(                                         //
1577afc474aeSMyung Bae             req, asyncResp->res,                                           //
1578afc474aeSMyung Bae             "AccountLockoutDuration", unlockTimeout,                       //
1579afc474aeSMyung Bae             "AccountLockoutThreshold", lockoutThreshold,                   //
1580afc474aeSMyung Bae             "ActiveDirectory/Authentication/AuthenticationType",
1581afc474aeSMyung Bae             activeDirectoryObject.authType,                                //
1582afc474aeSMyung Bae             "ActiveDirectory/Authentication/Password",
1583afc474aeSMyung Bae             activeDirectoryObject.password,                                //
1584afc474aeSMyung Bae             "ActiveDirectory/Authentication/Username",
1585afc474aeSMyung Bae             activeDirectoryObject.userName,                                //
1586afc474aeSMyung Bae             "ActiveDirectory/LDAPService/SearchSettings/BaseDistinguishedNames",
1587afc474aeSMyung Bae             activeDirectoryObject.baseDNList,                              //
1588afc474aeSMyung Bae             "ActiveDirectory/LDAPService/SearchSettings/GroupsAttribute",
1589afc474aeSMyung Bae             activeDirectoryObject.groupsAttribute,                         //
1590afc474aeSMyung Bae             "ActiveDirectory/LDAPService/SearchSettings/UsernameAttribute",
1591afc474aeSMyung Bae             activeDirectoryObject.userNameAttribute,                       //
1592afc474aeSMyung Bae             "ActiveDirectory/RemoteRoleMapping",
1593afc474aeSMyung Bae             activeDirectoryObject.remoteRoleMapData,                       //
1594afc474aeSMyung Bae             "ActiveDirectory/ServiceAddresses",
1595afc474aeSMyung Bae             activeDirectoryObject.serviceAddressList,                      //
1596afc474aeSMyung Bae             "ActiveDirectory/ServiceEnabled",
1597afc474aeSMyung Bae             activeDirectoryObject.serviceEnabled,                          //
1598afc474aeSMyung Bae             "HTTPBasicAuth", httpBasicAuth,                                //
1599afc474aeSMyung Bae             "LDAP/Authentication/AuthenticationType", ldapObject.authType, //
1600afc474aeSMyung Bae             "LDAP/Authentication/Password", ldapObject.password,           //
1601afc474aeSMyung Bae             "LDAP/Authentication/Username", ldapObject.userName,           //
1602afc474aeSMyung Bae             "LDAP/LDAPService/SearchSettings/BaseDistinguishedNames",
1603afc474aeSMyung Bae             ldapObject.baseDNList,                                         //
1604afc474aeSMyung Bae             "LDAP/LDAPService/SearchSettings/GroupsAttribute",
1605afc474aeSMyung Bae             ldapObject.groupsAttribute,                                    //
1606afc474aeSMyung Bae             "LDAP/LDAPService/SearchSettings/UsernameAttribute",
1607afc474aeSMyung Bae             ldapObject.userNameAttribute,                                  //
1608afc474aeSMyung Bae             "LDAP/RemoteRoleMapping", ldapObject.remoteRoleMapData,        //
1609afc474aeSMyung Bae             "LDAP/ServiceAddresses", ldapObject.serviceAddressList,        //
1610afc474aeSMyung Bae             "LDAP/ServiceEnabled", ldapObject.serviceEnabled,              //
1611afc474aeSMyung Bae             "MaxPasswordLength", maxPasswordLength,                        //
1612afc474aeSMyung Bae             "MinPasswordLength", minPasswordLength,                        //
1613afc474aeSMyung Bae             "MultiFactorAuth/ClientCertificate/CertificateMappingAttribute",
1614afc474aeSMyung Bae             certificateMappingAttribute,                                   //
1615afc474aeSMyung Bae             "MultiFactorAuth/ClientCertificate/RespondToUnauthenticatedClients",
1616afc474aeSMyung Bae             respondToUnauthenticatedClients,                               //
1617afc474aeSMyung Bae             "Oem/OpenBMC/AuthMethods/BasicAuth", auth.basicAuth,           //
1618afc474aeSMyung Bae             "Oem/OpenBMC/AuthMethods/Cookie", auth.cookie,                 //
1619afc474aeSMyung Bae             "Oem/OpenBMC/AuthMethods/SessionToken", auth.sessionToken,     //
1620afc474aeSMyung Bae             "Oem/OpenBMC/AuthMethods/TLS", auth.tls,                       //
1621afc474aeSMyung Bae             "Oem/OpenBMC/AuthMethods/XToken", auth.xToken                  //
1622afc474aeSMyung Bae             ))
1623f5ffd806SEd Tanous     {
1624f5ffd806SEd Tanous         return;
1625f5ffd806SEd Tanous     }
1626f5ffd806SEd Tanous 
1627482a69e7SRavi Teja     if (httpBasicAuth)
1628482a69e7SRavi Teja     {
1629482a69e7SRavi Teja         if (*httpBasicAuth == "Enabled")
1630482a69e7SRavi Teja         {
1631482a69e7SRavi Teja             auth.basicAuth = true;
1632482a69e7SRavi Teja         }
1633482a69e7SRavi Teja         else if (*httpBasicAuth == "Disabled")
1634482a69e7SRavi Teja         {
1635482a69e7SRavi Teja             auth.basicAuth = false;
1636482a69e7SRavi Teja         }
1637482a69e7SRavi Teja         else
1638482a69e7SRavi Teja         {
1639482a69e7SRavi Teja             messages::propertyValueNotInList(asyncResp->res, "HttpBasicAuth",
1640482a69e7SRavi Teja                                              *httpBasicAuth);
1641482a69e7SRavi Teja         }
1642482a69e7SRavi Teja     }
1643482a69e7SRavi Teja 
16443281bcf1SEd Tanous     if (respondToUnauthenticatedClients)
16453281bcf1SEd Tanous     {
16463281bcf1SEd Tanous         handleRespondToUnauthenticatedClientsPatch(
16473281bcf1SEd Tanous             app, req, asyncResp->res, *respondToUnauthenticatedClients);
16483281bcf1SEd Tanous     }
16493281bcf1SEd Tanous 
16503ce3688aSEd Tanous     if (certificateMappingAttribute)
16513ce3688aSEd Tanous     {
16523ce3688aSEd Tanous         handleCertificateMappingAttributePatch(asyncResp->res,
16533ce3688aSEd Tanous                                                *certificateMappingAttribute);
16543ce3688aSEd Tanous     }
16553ce3688aSEd Tanous 
1656f5ffd806SEd Tanous     if (minPasswordLength)
1657f5ffd806SEd Tanous     {
1658d02aad39SEd Tanous         setDbusProperty(
1659e93abac6SGinu George             asyncResp, "MinPasswordLength", "xyz.openbmc_project.User.Manager",
1660d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
16619ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy", "MinPasswordLength",
1662e93abac6SGinu George             *minPasswordLength);
1663f5ffd806SEd Tanous     }
1664f5ffd806SEd Tanous 
1665f5ffd806SEd Tanous     if (maxPasswordLength)
1666f5ffd806SEd Tanous     {
16671ef4c342SEd Tanous         messages::propertyNotWritable(asyncResp->res, "MaxPasswordLength");
1668f5ffd806SEd Tanous     }
1669f5ffd806SEd Tanous 
167010cb44f3SEd Tanous     handleLDAPPatch(std::move(activeDirectoryObject), asyncResp,
167110cb44f3SEd Tanous                     "ActiveDirectory");
167210cb44f3SEd Tanous     handleLDAPPatch(std::move(ldapObject), asyncResp, "LDAP");
1673f5ffd806SEd Tanous 
1674c1019828SEd Tanous     handleAuthMethodsPatch(asyncResp, auth);
1675f5ffd806SEd Tanous 
1676f5ffd806SEd Tanous     if (unlockTimeout)
1677f5ffd806SEd Tanous     {
1678d02aad39SEd Tanous         setDbusProperty(
1679e93abac6SGinu George             asyncResp, "AccountLockoutDuration",
1680e93abac6SGinu George             "xyz.openbmc_project.User.Manager",
1681d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
16829ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy", "AccountUnlockTimeout",
1683e93abac6SGinu George             *unlockTimeout);
1684f5ffd806SEd Tanous     }
1685f5ffd806SEd Tanous     if (lockoutThreshold)
1686f5ffd806SEd Tanous     {
1687d02aad39SEd Tanous         setDbusProperty(
1688e93abac6SGinu George             asyncResp, "AccountLockoutThreshold",
1689e93abac6SGinu George             "xyz.openbmc_project.User.Manager",
1690d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
16919ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy",
1692e93abac6SGinu George             "MaxLoginAttemptBeforeLockout", *lockoutThreshold);
1693f5ffd806SEd Tanous     }
16941ef4c342SEd Tanous }
1695f5ffd806SEd Tanous 
16964c7d4d33SEd Tanous inline void handleAccountCollectionHead(
16971ef4c342SEd Tanous     App& app, const crow::Request& req,
16981ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
16991ef4c342SEd Tanous {
17003ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
170145ca1b86SEd Tanous     {
170245ca1b86SEd Tanous         return;
170345ca1b86SEd Tanous     }
17044c7d4d33SEd Tanous     asyncResp->res.addHeader(
17054c7d4d33SEd Tanous         boost::beast::http::field::link,
17064c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/ManagerAccountCollection.json>; rel=describedby");
17074c7d4d33SEd Tanous }
17084c7d4d33SEd Tanous 
17094c7d4d33SEd Tanous inline void handleAccountCollectionGet(
17104c7d4d33SEd Tanous     App& app, const crow::Request& req,
17114c7d4d33SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
17124c7d4d33SEd Tanous {
1713afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1714afd369c6SJiaqing Zhao     {
1715afd369c6SJiaqing Zhao         return;
1716afd369c6SJiaqing Zhao     }
17173e72c202SNinad Palsule 
17183e72c202SNinad Palsule     if (req.session == nullptr)
17193e72c202SNinad Palsule     {
17203e72c202SNinad Palsule         messages::internalError(asyncResp->res);
17213e72c202SNinad Palsule         return;
17223e72c202SNinad Palsule     }
17233e72c202SNinad Palsule 
1724afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1725afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1726afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/ManagerAccountCollection.json>; rel=describedby");
17271476687dSEd Tanous 
17281476687dSEd Tanous     asyncResp->res.jsonValue["@odata.id"] =
17291476687dSEd Tanous         "/redfish/v1/AccountService/Accounts";
17301ef4c342SEd Tanous     asyncResp->res.jsonValue["@odata.type"] = "#ManagerAccountCollection."
17311476687dSEd Tanous                                               "ManagerAccountCollection";
17321476687dSEd Tanous     asyncResp->res.jsonValue["Name"] = "Accounts Collection";
17331476687dSEd Tanous     asyncResp->res.jsonValue["Description"] = "BMC User Accounts";
17340f74e643SEd Tanous 
17356c51eab1SEd Tanous     Privileges effectiveUserPrivileges =
17363e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
17376c51eab1SEd Tanous 
1738f5e29f33SJunLin Chen     std::string thisUser;
1739f5e29f33SJunLin Chen     if (req.session)
1740f5e29f33SJunLin Chen     {
1741f5e29f33SJunLin Chen         thisUser = req.session->username;
1742f5e29f33SJunLin Chen     }
17435eb468daSGeorge Liu     sdbusplus::message::object_path path("/xyz/openbmc_project/user");
17445eb468daSGeorge Liu     dbus::utility::getManagedObjects(
17455eb468daSGeorge Liu         "xyz.openbmc_project.User.Manager", path,
1746cef1ddfbSEd Tanous         [asyncResp, thisUser, effectiveUserPrivileges](
17475e7e2dc5SEd Tanous             const boost::system::error_code& ec,
1748711ac7a9SEd Tanous             const dbus::utility::ManagedObjectType& users) {
1749b9b2e0b2SEd Tanous             if (ec)
1750b9b2e0b2SEd Tanous             {
1751f12894f8SJason M. Bills                 messages::internalError(asyncResp->res);
1752b9b2e0b2SEd Tanous                 return;
1753b9b2e0b2SEd Tanous             }
1754b9b2e0b2SEd Tanous 
1755cef1ddfbSEd Tanous             bool userCanSeeAllAccounts =
1756002d39b4SEd Tanous                 effectiveUserPrivileges.isSupersetOf({"ConfigureUsers"});
1757cef1ddfbSEd Tanous 
1758cef1ddfbSEd Tanous             bool userCanSeeSelf =
1759002d39b4SEd Tanous                 effectiveUserPrivileges.isSupersetOf({"ConfigureSelf"});
1760cef1ddfbSEd Tanous 
1761002d39b4SEd Tanous             nlohmann::json& memberArray = asyncResp->res.jsonValue["Members"];
1762b9b2e0b2SEd Tanous             memberArray = nlohmann::json::array();
1763b9b2e0b2SEd Tanous 
17649eb808c1SEd Tanous             for (const auto& userpath : users)
1765b9b2e0b2SEd Tanous             {
17662dfd18efSEd Tanous                 std::string user = userpath.first.filename();
17672dfd18efSEd Tanous                 if (user.empty())
1768b9b2e0b2SEd Tanous                 {
17692dfd18efSEd Tanous                     messages::internalError(asyncResp->res);
177062598e31SEd Tanous                     BMCWEB_LOG_ERROR("Invalid firmware ID");
17712dfd18efSEd Tanous 
17722dfd18efSEd Tanous                     return;
1773b9b2e0b2SEd Tanous                 }
1774f365910cSGunnar Mills 
1775f365910cSGunnar Mills                 // As clarified by Redfish here:
1776f365910cSGunnar Mills                 // https://redfishforum.com/thread/281/manageraccountcollection-change-allows-account-enumeration
17776c51eab1SEd Tanous                 // Users without ConfigureUsers, only see their own
17786c51eab1SEd Tanous                 // account. Users with ConfigureUsers, see all
17796c51eab1SEd Tanous                 // accounts.
1780bd79bce8SPatrick Williams                 if (userCanSeeAllAccounts ||
1781bd79bce8SPatrick Williams                     (thisUser == user && userCanSeeSelf))
1782f365910cSGunnar Mills                 {
17831476687dSEd Tanous                     nlohmann::json::object_t member;
17843b32780dSEd Tanous                     member["@odata.id"] = boost::urls::format(
17853b32780dSEd Tanous                         "/redfish/v1/AccountService/Accounts/{}", user);
1786b2ba3072SPatrick Williams                     memberArray.emplace_back(std::move(member));
1787b9b2e0b2SEd Tanous                 }
1788f365910cSGunnar Mills             }
1789bd79bce8SPatrick Williams             asyncResp->res.jsonValue["Members@odata.count"] =
1790bd79bce8SPatrick Williams                 memberArray.size();
17915eb468daSGeorge Liu         });
17921ef4c342SEd Tanous }
17936c51eab1SEd Tanous 
179497e90da3SNinad Palsule inline void processAfterCreateUser(
179597e90da3SNinad Palsule     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
179697e90da3SNinad Palsule     const std::string& username, const std::string& password,
179797e90da3SNinad Palsule     const boost::system::error_code& ec, sdbusplus::message_t& m)
179897e90da3SNinad Palsule {
179997e90da3SNinad Palsule     if (ec)
180097e90da3SNinad Palsule     {
180197e90da3SNinad Palsule         userErrorMessageHandler(m.get_error(), asyncResp, username, "");
180297e90da3SNinad Palsule         return;
180397e90da3SNinad Palsule     }
180497e90da3SNinad Palsule 
180597e90da3SNinad Palsule     if (pamUpdatePassword(username, password) != PAM_SUCCESS)
180697e90da3SNinad Palsule     {
180797e90da3SNinad Palsule         // At this point we have a user that's been
180897e90da3SNinad Palsule         // created, but the password set
180997e90da3SNinad Palsule         // failed.Something is wrong, so delete the user
181097e90da3SNinad Palsule         // that we've already created
181197e90da3SNinad Palsule         sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
181297e90da3SNinad Palsule         tempObjPath /= username;
181397e90da3SNinad Palsule         const std::string userPath(tempObjPath);
181497e90da3SNinad Palsule 
1815177612aaSEd Tanous         dbus::utility::async_method_call(
1816177612aaSEd Tanous             asyncResp,
181797e90da3SNinad Palsule             [asyncResp, password](const boost::system::error_code& ec3) {
181897e90da3SNinad Palsule                 if (ec3)
181997e90da3SNinad Palsule                 {
182097e90da3SNinad Palsule                     messages::internalError(asyncResp->res);
182197e90da3SNinad Palsule                     return;
182297e90da3SNinad Palsule                 }
182397e90da3SNinad Palsule 
182497e90da3SNinad Palsule                 // If password is invalid
18259bd80831SJason M. Bills                 messages::propertyValueFormatError(asyncResp->res, nullptr,
182697e90da3SNinad Palsule                                                    "Password");
182797e90da3SNinad Palsule             },
182897e90da3SNinad Palsule             "xyz.openbmc_project.User.Manager", userPath,
182997e90da3SNinad Palsule             "xyz.openbmc_project.Object.Delete", "Delete");
183097e90da3SNinad Palsule 
183162598e31SEd Tanous         BMCWEB_LOG_ERROR("pamUpdatePassword Failed");
183297e90da3SNinad Palsule         return;
183397e90da3SNinad Palsule     }
183497e90da3SNinad Palsule 
183597e90da3SNinad Palsule     messages::created(asyncResp->res);
183697e90da3SNinad Palsule     asyncResp->res.addHeader("Location",
183797e90da3SNinad Palsule                              "/redfish/v1/AccountService/Accounts/" + username);
183897e90da3SNinad Palsule }
183997e90da3SNinad Palsule 
184097e90da3SNinad Palsule inline void processAfterGetAllGroups(
184197e90da3SNinad Palsule     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
184297e90da3SNinad Palsule     const std::string& username, const std::string& password,
1843e01d0c36SEd Tanous     const std::string& roleId, bool enabled,
18449ba73934SNinad Palsule     std::optional<std::vector<std::string>> accountTypes,
184597e90da3SNinad Palsule     const std::vector<std::string>& allGroupsList)
184697e90da3SNinad Palsule {
18473e72c202SNinad Palsule     std::vector<std::string> userGroups;
18489ba73934SNinad Palsule     std::vector<std::string> accountTypeUserGroups;
18499ba73934SNinad Palsule 
18509ba73934SNinad Palsule     // If user specified account types then convert them to unix user groups
18519ba73934SNinad Palsule     if (accountTypes)
18529ba73934SNinad Palsule     {
18539ba73934SNinad Palsule         if (!getUserGroupFromAccountType(asyncResp->res, *accountTypes,
18549ba73934SNinad Palsule                                          accountTypeUserGroups))
18559ba73934SNinad Palsule         {
18569ba73934SNinad Palsule             // Problem in mapping Account Types to User Groups, Error already
18579ba73934SNinad Palsule             // logged.
18589ba73934SNinad Palsule             return;
18599ba73934SNinad Palsule         }
18609ba73934SNinad Palsule     }
18619ba73934SNinad Palsule 
18623e72c202SNinad Palsule     for (const auto& grp : allGroupsList)
18633e72c202SNinad Palsule     {
18649ba73934SNinad Palsule         // If user specified the account type then only accept groups which are
18659ba73934SNinad Palsule         // in the account types group list.
18669ba73934SNinad Palsule         if (!accountTypeUserGroups.empty())
18679ba73934SNinad Palsule         {
18689ba73934SNinad Palsule             bool found = false;
18699ba73934SNinad Palsule             for (const auto& grp1 : accountTypeUserGroups)
18709ba73934SNinad Palsule             {
18719ba73934SNinad Palsule                 if (grp == grp1)
18729ba73934SNinad Palsule                 {
18739ba73934SNinad Palsule                     found = true;
18749ba73934SNinad Palsule                     break;
18759ba73934SNinad Palsule                 }
18769ba73934SNinad Palsule             }
18779ba73934SNinad Palsule             if (!found)
18789ba73934SNinad Palsule             {
18799ba73934SNinad Palsule                 continue;
18809ba73934SNinad Palsule             }
18819ba73934SNinad Palsule         }
18829ba73934SNinad Palsule 
18833e72c202SNinad Palsule         // Console access is provided to the user who is a member of
18843e72c202SNinad Palsule         // hostconsole group and has a administrator role. So, set
18853e72c202SNinad Palsule         // hostconsole group only for the administrator.
18869ba73934SNinad Palsule         if ((grp == "hostconsole") && (roleId != "priv-admin"))
18873e72c202SNinad Palsule         {
18889ba73934SNinad Palsule             if (!accountTypeUserGroups.empty())
18899ba73934SNinad Palsule             {
189062598e31SEd Tanous                 BMCWEB_LOG_ERROR(
189162598e31SEd Tanous                     "Only administrator can get HostConsole access");
18929ba73934SNinad Palsule                 asyncResp->res.result(boost::beast::http::status::bad_request);
18939ba73934SNinad Palsule                 return;
18949ba73934SNinad Palsule             }
18959ba73934SNinad Palsule             continue;
18969ba73934SNinad Palsule         }
18973e72c202SNinad Palsule         userGroups.emplace_back(grp);
18983e72c202SNinad Palsule     }
18999ba73934SNinad Palsule 
19009ba73934SNinad Palsule     // Make sure user specified groups are valid. This is internal error because
19019ba73934SNinad Palsule     // it some inconsistencies between user manager and bmcweb.
19029ba73934SNinad Palsule     if (!accountTypeUserGroups.empty() &&
19039ba73934SNinad Palsule         accountTypeUserGroups.size() != userGroups.size())
19049ba73934SNinad Palsule     {
19059ba73934SNinad Palsule         messages::internalError(asyncResp->res);
19069ba73934SNinad Palsule         return;
19073e72c202SNinad Palsule     }
1908177612aaSEd Tanous     dbus::utility::async_method_call(
1909177612aaSEd Tanous         asyncResp,
191097e90da3SNinad Palsule         [asyncResp, username, password](const boost::system::error_code& ec2,
191197e90da3SNinad Palsule                                         sdbusplus::message_t& m) {
191297e90da3SNinad Palsule             processAfterCreateUser(asyncResp, username, password, ec2, m);
191397e90da3SNinad Palsule         },
191497e90da3SNinad Palsule         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
19153e72c202SNinad Palsule         "xyz.openbmc_project.User.Manager", "CreateUser", username, userGroups,
1916e01d0c36SEd Tanous         roleId, enabled);
191797e90da3SNinad Palsule }
191897e90da3SNinad Palsule 
19191ef4c342SEd Tanous inline void handleAccountCollectionPost(
19201ef4c342SEd Tanous     App& app, const crow::Request& req,
19211ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
19221ef4c342SEd Tanous {
19233ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
192445ca1b86SEd Tanous     {
192545ca1b86SEd Tanous         return;
192645ca1b86SEd Tanous     }
19279712f8acSEd Tanous     std::string username;
19289712f8acSEd Tanous     std::string password;
1929e01d0c36SEd Tanous     std::optional<std::string> roleIdJson;
1930e01d0c36SEd Tanous     std::optional<bool> enabledJson;
19319ba73934SNinad Palsule     std::optional<std::vector<std::string>> accountTypes;
1932afc474aeSMyung Bae     if (!json_util::readJsonPatch(        //
1933afc474aeSMyung Bae             req, asyncResp->res,          //
1934afc474aeSMyung Bae             "AccountTypes", accountTypes, //
1935afc474aeSMyung Bae             "Enabled", enabledJson,       //
1936afc474aeSMyung Bae             "Password", password,         //
1937afc474aeSMyung Bae             "RoleId", roleIdJson,         //
1938afc474aeSMyung Bae             "UserName", username          //
1939afc474aeSMyung Bae             ))
194004ae99ecSEd Tanous     {
194104ae99ecSEd Tanous         return;
194204ae99ecSEd Tanous     }
194304ae99ecSEd Tanous 
1944e01d0c36SEd Tanous     std::string roleId = roleIdJson.value_or("User");
1945e01d0c36SEd Tanous     std::string priv = getPrivilegeFromRoleId(roleId);
194684e12cb7SAppaRao Puli     if (priv.empty())
194704ae99ecSEd Tanous     {
1948e01d0c36SEd Tanous         messages::propertyValueNotInList(asyncResp->res, roleId, "RoleId");
194904ae99ecSEd Tanous         return;
195004ae99ecSEd Tanous     }
19519712f8acSEd Tanous     roleId = priv;
195204ae99ecSEd Tanous 
1953e01d0c36SEd Tanous     bool enabled = enabledJson.value_or(true);
1954e01d0c36SEd Tanous 
1955599c71d8SAyushi Smriti     // Reading AllGroups property
1956deae6a78SEd Tanous     dbus::utility::getProperty<std::vector<std::string>>(
1957deae6a78SEd Tanous         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
1958deae6a78SEd Tanous         "xyz.openbmc_project.User.Manager", "AllGroups",
19599ba73934SNinad Palsule         [asyncResp, username, password{std::move(password)}, roleId, enabled,
19609ba73934SNinad Palsule          accountTypes](const boost::system::error_code& ec,
19611e1e598dSJonathan Doman                        const std::vector<std::string>& allGroupsList) {
1962599c71d8SAyushi Smriti             if (ec)
1963599c71d8SAyushi Smriti             {
1964a0735a4eSGunnar Mills                 BMCWEB_LOG_ERROR("D-Bus response error {}", ec);
1965599c71d8SAyushi Smriti                 messages::internalError(asyncResp->res);
1966599c71d8SAyushi Smriti                 return;
1967599c71d8SAyushi Smriti             }
1968599c71d8SAyushi Smriti 
19691e1e598dSJonathan Doman             if (allGroupsList.empty())
1970599c71d8SAyushi Smriti             {
1971599c71d8SAyushi Smriti                 messages::internalError(asyncResp->res);
1972599c71d8SAyushi Smriti                 return;
1973599c71d8SAyushi Smriti             }
1974599c71d8SAyushi Smriti 
1975bd79bce8SPatrick Williams             processAfterGetAllGroups(asyncResp, username, password, roleId,
1976bd79bce8SPatrick Williams                                      enabled, accountTypes, allGroupsList);
19771e1e598dSJonathan Doman         });
19781ef4c342SEd Tanous }
1979b9b2e0b2SEd Tanous 
1980504af5a0SPatrick Williams inline void handleAccountHead(
1981504af5a0SPatrick Williams     App& app, const crow::Request& req,
19826c51eab1SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
19834c7d4d33SEd Tanous     const std::string& /*accountName*/)
19841ef4c342SEd Tanous {
19853ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
198645ca1b86SEd Tanous     {
198745ca1b86SEd Tanous         return;
198845ca1b86SEd Tanous     }
19894c7d4d33SEd Tanous     asyncResp->res.addHeader(
19904c7d4d33SEd Tanous         boost::beast::http::field::link,
19914c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/ManagerAccount/ManagerAccount.json>; rel=describedby");
19924c7d4d33SEd Tanous }
1993afd369c6SJiaqing Zhao 
1994504af5a0SPatrick Williams inline void handleAccountGet(
1995504af5a0SPatrick Williams     App& app, const crow::Request& req,
19964c7d4d33SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
19974c7d4d33SEd Tanous     const std::string& accountName)
19984c7d4d33SEd Tanous {
1999afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2000afd369c6SJiaqing Zhao     {
2001afd369c6SJiaqing Zhao         return;
2002afd369c6SJiaqing Zhao     }
2003afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
2004afd369c6SJiaqing Zhao         boost::beast::http::field::link,
2005afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/ManagerAccount/ManagerAccount.json>; rel=describedby");
2006afd369c6SJiaqing Zhao 
200725b54dbaSEd Tanous     if constexpr (BMCWEB_INSECURE_DISABLE_AUTH)
200825b54dbaSEd Tanous     {
2009031514fbSJunLin Chen         // If authentication is disabled, there are no user accounts
201025b54dbaSEd Tanous         messages::resourceNotFound(asyncResp->res, "ManagerAccount",
201125b54dbaSEd Tanous                                    accountName);
2012031514fbSJunLin Chen         return;
201325b54dbaSEd Tanous     }
2014afd369c6SJiaqing Zhao 
2015031514fbSJunLin Chen     if (req.session == nullptr)
2016031514fbSJunLin Chen     {
2017031514fbSJunLin Chen         messages::internalError(asyncResp->res);
2018031514fbSJunLin Chen         return;
2019031514fbSJunLin Chen     }
20206c51eab1SEd Tanous     if (req.session->username != accountName)
2021b9b2e0b2SEd Tanous     {
20226c51eab1SEd Tanous         // At this point we've determined that the user is trying to
20231ef4c342SEd Tanous         // modify a user that isn't them.  We need to verify that they
20241ef4c342SEd Tanous         // have permissions to modify other users, so re-run the auth
20251ef4c342SEd Tanous         // check with the same permissions, minus ConfigureSelf.
20266c51eab1SEd Tanous         Privileges effectiveUserPrivileges =
20273e72c202SNinad Palsule             redfish::getUserPrivileges(*req.session);
20281ef4c342SEd Tanous         Privileges requiredPermissionsToChangeNonSelf = {"ConfigureUsers",
20291ef4c342SEd Tanous                                                          "ConfigureManager"};
20306c51eab1SEd Tanous         if (!effectiveUserPrivileges.isSupersetOf(
20316c51eab1SEd Tanous                 requiredPermissionsToChangeNonSelf))
2032900f9497SJoseph Reynolds         {
203362598e31SEd Tanous             BMCWEB_LOG_DEBUG("GET Account denied access");
2034900f9497SJoseph Reynolds             messages::insufficientPrivilege(asyncResp->res);
2035900f9497SJoseph Reynolds             return;
2036900f9497SJoseph Reynolds         }
2037900f9497SJoseph Reynolds     }
2038900f9497SJoseph Reynolds 
20395eb468daSGeorge Liu     sdbusplus::message::object_path path("/xyz/openbmc_project/user");
20405eb468daSGeorge Liu     dbus::utility::getManagedObjects(
20415eb468daSGeorge Liu         "xyz.openbmc_project.User.Manager", path,
20421ef4c342SEd Tanous         [asyncResp,
20435e7e2dc5SEd Tanous          accountName](const boost::system::error_code& ec,
2044711ac7a9SEd Tanous                       const dbus::utility::ManagedObjectType& users) {
2045b9b2e0b2SEd Tanous             if (ec)
2046b9b2e0b2SEd Tanous             {
2047f12894f8SJason M. Bills                 messages::internalError(asyncResp->res);
2048b9b2e0b2SEd Tanous                 return;
2049b9b2e0b2SEd Tanous             }
20503544d2a7SEd Tanous             const auto userIt = std::ranges::find_if(
205180f79a40SMichael Shen                 users,
205280f79a40SMichael Shen                 [accountName](
2053b477fd44SP Dheeraj Srujan Kumar                     const std::pair<sdbusplus::message::object_path,
205480f79a40SMichael Shen                                     dbus::utility::DBusInterfacesMap>& user) {
205555f79e6fSEd Tanous                     return accountName == user.first.filename();
2056b477fd44SP Dheeraj Srujan Kumar                 });
2057b9b2e0b2SEd Tanous 
205884e12cb7SAppaRao Puli             if (userIt == users.end())
2059b9b2e0b2SEd Tanous             {
2060002d39b4SEd Tanous                 messages::resourceNotFound(asyncResp->res, "ManagerAccount",
2061002d39b4SEd Tanous                                            accountName);
206284e12cb7SAppaRao Puli                 return;
206384e12cb7SAppaRao Puli             }
20644e68c45bSAyushi Smriti 
20651476687dSEd Tanous             asyncResp->res.jsonValue["@odata.type"] =
206658345856SAbhishek Patel                 "#ManagerAccount.v1_7_0.ManagerAccount";
20671476687dSEd Tanous             asyncResp->res.jsonValue["Name"] = "User Account";
20681476687dSEd Tanous             asyncResp->res.jsonValue["Description"] = "User Account";
20691476687dSEd Tanous             asyncResp->res.jsonValue["Password"] = nullptr;
207058345856SAbhishek Patel             asyncResp->res.jsonValue["StrictAccountTypes"] = true;
20714e68c45bSAyushi Smriti 
207284e12cb7SAppaRao Puli             for (const auto& interface : userIt->second)
207365b0dc32SEd Tanous             {
2074002d39b4SEd Tanous                 if (interface.first == "xyz.openbmc_project.User.Attributes")
207565b0dc32SEd Tanous                 {
2076b437a535SAsmitha Karunanithi                     const bool* userEnabled = nullptr;
2077b437a535SAsmitha Karunanithi                     const bool* userLocked = nullptr;
2078b437a535SAsmitha Karunanithi                     const std::string* userPrivPtr = nullptr;
2079b437a535SAsmitha Karunanithi                     const bool* userPasswordExpired = nullptr;
2080b437a535SAsmitha Karunanithi                     const std::vector<std::string>* userGroups = nullptr;
2081b437a535SAsmitha Karunanithi 
2082b437a535SAsmitha Karunanithi                     const bool success = sdbusplus::unpackPropertiesNoThrow(
2083b437a535SAsmitha Karunanithi                         dbus_utils::UnpackErrorPrinter(), interface.second,
2084b437a535SAsmitha Karunanithi                         "UserEnabled", userEnabled,
2085b437a535SAsmitha Karunanithi                         "UserLockedForFailedAttempt", userLocked,
2086b437a535SAsmitha Karunanithi                         "UserPrivilege", userPrivPtr, "UserPasswordExpired",
2087b437a535SAsmitha Karunanithi                         userPasswordExpired, "UserGroups", userGroups);
2088b437a535SAsmitha Karunanithi                     if (!success)
208965b0dc32SEd Tanous                     {
2090b437a535SAsmitha Karunanithi                         messages::internalError(asyncResp->res);
2091b437a535SAsmitha Karunanithi                         return;
2092b437a535SAsmitha Karunanithi                     }
209365b0dc32SEd Tanous                     if (userEnabled == nullptr)
209465b0dc32SEd Tanous                     {
209562598e31SEd Tanous                         BMCWEB_LOG_ERROR("UserEnabled wasn't a bool");
209684e12cb7SAppaRao Puli                         messages::internalError(asyncResp->res);
209784e12cb7SAppaRao Puli                         return;
209865b0dc32SEd Tanous                     }
2099002d39b4SEd Tanous                     asyncResp->res.jsonValue["Enabled"] = *userEnabled;
2100b437a535SAsmitha Karunanithi 
210165b0dc32SEd Tanous                     if (userLocked == nullptr)
210265b0dc32SEd Tanous                     {
210362598e31SEd Tanous                         BMCWEB_LOG_ERROR("UserLockedForF"
210484e12cb7SAppaRao Puli                                          "ailedAttempt "
210562598e31SEd Tanous                                          "wasn't a bool");
210684e12cb7SAppaRao Puli                         messages::internalError(asyncResp->res);
210784e12cb7SAppaRao Puli                         return;
210865b0dc32SEd Tanous                     }
2109002d39b4SEd Tanous                     asyncResp->res.jsonValue["Locked"] = *userLocked;
211020fa6a2cSEd Tanous                     nlohmann::json::array_t allowed;
211120fa6a2cSEd Tanous                     // can only unlock accounts
211220fa6a2cSEd Tanous                     allowed.emplace_back("false");
2113b437a535SAsmitha Karunanithi                     asyncResp->res.jsonValue["Locked@Redfish.AllowableValues"] =
211420fa6a2cSEd Tanous                         std::move(allowed);
2115b437a535SAsmitha Karunanithi 
211654fc587aSNagaraju Goruganti                     if (userPrivPtr == nullptr)
211784e12cb7SAppaRao Puli                     {
211862598e31SEd Tanous                         BMCWEB_LOG_ERROR("UserPrivilege wasn't a "
211962598e31SEd Tanous                                          "string");
212084e12cb7SAppaRao Puli                         messages::internalError(asyncResp->res);
212184e12cb7SAppaRao Puli                         return;
212284e12cb7SAppaRao Puli                     }
2123b437a535SAsmitha Karunanithi                     std::string role = getRoleIdFromPrivilege(*userPrivPtr);
212454fc587aSNagaraju Goruganti                     if (role.empty())
212584e12cb7SAppaRao Puli                     {
212662598e31SEd Tanous                         BMCWEB_LOG_ERROR("Invalid user role");
212784e12cb7SAppaRao Puli                         messages::internalError(asyncResp->res);
212884e12cb7SAppaRao Puli                         return;
212984e12cb7SAppaRao Puli                     }
213054fc587aSNagaraju Goruganti                     asyncResp->res.jsonValue["RoleId"] = role;
213184e12cb7SAppaRao Puli 
21321476687dSEd Tanous                     nlohmann::json& roleEntry =
2133002d39b4SEd Tanous                         asyncResp->res.jsonValue["Links"]["Role"];
21343b32780dSEd Tanous                     roleEntry["@odata.id"] = boost::urls::format(
21353b32780dSEd Tanous                         "/redfish/v1/AccountService/Roles/{}", role);
2136b437a535SAsmitha Karunanithi 
21373bf4e632SJoseph Reynolds                     if (userPasswordExpired == nullptr)
21383bf4e632SJoseph Reynolds                     {
2139b437a535SAsmitha Karunanithi                         BMCWEB_LOG_ERROR("UserPasswordExpired wasn't a bool");
21403bf4e632SJoseph Reynolds                         messages::internalError(asyncResp->res);
21413bf4e632SJoseph Reynolds                         return;
21423bf4e632SJoseph Reynolds                     }
2143002d39b4SEd Tanous                     asyncResp->res.jsonValue["PasswordChangeRequired"] =
21443bf4e632SJoseph Reynolds                         *userPasswordExpired;
2145b437a535SAsmitha Karunanithi 
2146c7229815SAbhishek Patel                     if (userGroups == nullptr)
2147c7229815SAbhishek Patel                     {
2148b437a535SAsmitha Karunanithi                         BMCWEB_LOG_ERROR("userGroups wasn't a string vector");
2149c7229815SAbhishek Patel                         messages::internalError(asyncResp->res);
2150c7229815SAbhishek Patel                         return;
2151c7229815SAbhishek Patel                     }
2152b437a535SAsmitha Karunanithi                     if (!translateUserGroup(*userGroups, asyncResp->res))
2153c7229815SAbhishek Patel                     {
215462598e31SEd Tanous                         BMCWEB_LOG_ERROR("userGroups mapping failed");
2155c7229815SAbhishek Patel                         messages::internalError(asyncResp->res);
2156c7229815SAbhishek Patel                         return;
2157c7229815SAbhishek Patel                     }
2158c7229815SAbhishek Patel                 }
215965b0dc32SEd Tanous             }
216065b0dc32SEd Tanous 
21613b32780dSEd Tanous             asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
21623b32780dSEd Tanous                 "/redfish/v1/AccountService/Accounts/{}", accountName);
2163b9b2e0b2SEd Tanous             asyncResp->res.jsonValue["Id"] = accountName;
2164b9b2e0b2SEd Tanous             asyncResp->res.jsonValue["UserName"] = accountName;
21655eb468daSGeorge Liu         });
21661ef4c342SEd Tanous }
2167a840879dSEd Tanous 
2168504af5a0SPatrick Williams inline void handleAccountDelete(
2169504af5a0SPatrick Williams     App& app, const crow::Request& req,
21706c51eab1SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
21711ef4c342SEd Tanous     const std::string& username)
21721ef4c342SEd Tanous {
21733ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
217445ca1b86SEd Tanous     {
217545ca1b86SEd Tanous         return;
217645ca1b86SEd Tanous     }
21771ef4c342SEd Tanous 
217825b54dbaSEd Tanous     if constexpr (BMCWEB_INSECURE_DISABLE_AUTH)
217925b54dbaSEd Tanous     {
2180031514fbSJunLin Chen         // If authentication is disabled, there are no user accounts
2181d8a5d5d8SJiaqing Zhao         messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
2182031514fbSJunLin Chen         return;
218325b54dbaSEd Tanous     }
21841ef4c342SEd Tanous     sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
21851ef4c342SEd Tanous     tempObjPath /= username;
21861ef4c342SEd Tanous     const std::string userPath(tempObjPath);
21871ef4c342SEd Tanous 
2188177612aaSEd Tanous     dbus::utility::async_method_call(
2189177612aaSEd Tanous         asyncResp,
21905e7e2dc5SEd Tanous         [asyncResp, username](const boost::system::error_code& ec) {
21911ef4c342SEd Tanous             if (ec)
21921ef4c342SEd Tanous             {
2193d8a5d5d8SJiaqing Zhao                 messages::resourceNotFound(asyncResp->res, "ManagerAccount",
21941ef4c342SEd Tanous                                            username);
21951ef4c342SEd Tanous                 return;
21961ef4c342SEd Tanous             }
21971ef4c342SEd Tanous 
21981ef4c342SEd Tanous             messages::accountRemoved(asyncResp->res);
21991ef4c342SEd Tanous         },
22001ef4c342SEd Tanous         "xyz.openbmc_project.User.Manager", userPath,
22011ef4c342SEd Tanous         "xyz.openbmc_project.Object.Delete", "Delete");
22021ef4c342SEd Tanous }
22031ef4c342SEd Tanous 
2204504af5a0SPatrick Williams inline void handleAccountPatch(
2205504af5a0SPatrick Williams     App& app, const crow::Request& req,
22061ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
22071ef4c342SEd Tanous     const std::string& username)
22081ef4c342SEd Tanous {
22091ef4c342SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
22101ef4c342SEd Tanous     {
22111ef4c342SEd Tanous         return;
22121ef4c342SEd Tanous     }
221325b54dbaSEd Tanous     if constexpr (BMCWEB_INSECURE_DISABLE_AUTH)
221425b54dbaSEd Tanous     {
22151ef4c342SEd Tanous         // If authentication is disabled, there are no user accounts
2216d8a5d5d8SJiaqing Zhao         messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
22171ef4c342SEd Tanous         return;
221825b54dbaSEd Tanous     }
2219a24526dcSEd Tanous     std::optional<std::string> newUserName;
2220a24526dcSEd Tanous     std::optional<std::string> password;
2221a24526dcSEd Tanous     std::optional<bool> enabled;
2222a24526dcSEd Tanous     std::optional<std::string> roleId;
222324c8542dSRatan Gupta     std::optional<bool> locked;
222458345856SAbhishek Patel     std::optional<std::vector<std::string>> accountTypes;
222558345856SAbhishek Patel 
2226031514fbSJunLin Chen     if (req.session == nullptr)
2227031514fbSJunLin Chen     {
2228031514fbSJunLin Chen         messages::internalError(asyncResp->res);
2229031514fbSJunLin Chen         return;
2230031514fbSJunLin Chen     }
2231031514fbSJunLin Chen 
22322b9c1dfeSEd Tanous     bool userSelf = (username == req.session->username);
22332b9c1dfeSEd Tanous 
2234e9cc5172SEd Tanous     Privileges effectiveUserPrivileges =
22353e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
2236e9cc5172SEd Tanous     Privileges configureUsers = {"ConfigureUsers"};
2237e9cc5172SEd Tanous     bool userHasConfigureUsers =
2238*8b844488SAbhilash Raju         effectiveUserPrivileges.isSupersetOf(configureUsers) &&
2239*8b844488SAbhilash Raju         !req.session->isConfigureSelfOnly;
2240e9cc5172SEd Tanous     if (userHasConfigureUsers)
2241e9cc5172SEd Tanous     {
2242e9cc5172SEd Tanous         // Users with ConfigureUsers can modify for all users
2243afc474aeSMyung Bae         if (!json_util::readJsonPatch(        //
2244afc474aeSMyung Bae                 req, asyncResp->res,          //
2245afc474aeSMyung Bae                 "AccountTypes", accountTypes, //
2246afc474aeSMyung Bae                 "Enabled", enabled,           //
2247afc474aeSMyung Bae                 "Locked", locked,             //
2248afc474aeSMyung Bae                 "Password", password,         //
2249afc474aeSMyung Bae                 "RoleId", roleId,             //
2250afc474aeSMyung Bae                 "UserName", newUserName       //
2251afc474aeSMyung Bae                 ))
2252a840879dSEd Tanous         {
2253a840879dSEd Tanous             return;
2254a840879dSEd Tanous         }
2255e9cc5172SEd Tanous     }
2256e9cc5172SEd Tanous     else
2257900f9497SJoseph Reynolds     {
2258e9cc5172SEd Tanous         // ConfigureSelf accounts can only modify their own account
225958345856SAbhishek Patel         if (!userSelf)
2260900f9497SJoseph Reynolds         {
2261900f9497SJoseph Reynolds             messages::insufficientPrivilege(asyncResp->res);
2262900f9497SJoseph Reynolds             return;
2263900f9497SJoseph Reynolds         }
2264031514fbSJunLin Chen 
2265e9cc5172SEd Tanous         // ConfigureSelf accounts can only modify their password
22661ef4c342SEd Tanous         if (!json_util::readJsonPatch(req, asyncResp->res, "Password",
22671ef4c342SEd Tanous                                       password))
2268e9cc5172SEd Tanous         {
2269e9cc5172SEd Tanous             return;
2270e9cc5172SEd Tanous         }
2271900f9497SJoseph Reynolds     }
2272900f9497SJoseph Reynolds 
227366b5ca76Sjayaprakash Mutyala     // if user name is not provided in the patch method or if it
22746c51eab1SEd Tanous     // matches the user name in the URI, then we are treating it as
22756c51eab1SEd Tanous     // updating user properties other then username. If username
22766c51eab1SEd Tanous     // provided doesn't match the URI, then we are treating this as
22776c51eab1SEd Tanous     // user rename request.
227866b5ca76Sjayaprakash Mutyala     if (!newUserName || (newUserName.value() == username))
2279a840879dSEd Tanous     {
22801ef4c342SEd Tanous         updateUserProperties(asyncResp, username, password, enabled, roleId,
2281e518ef32SRavi Teja                              locked, accountTypes, userSelf, req.session);
228284e12cb7SAppaRao Puli         return;
228384e12cb7SAppaRao Puli     }
2284177612aaSEd Tanous     dbus::utility::async_method_call(
2285177612aaSEd Tanous         asyncResp,
22866c51eab1SEd Tanous         [asyncResp, username, password(std::move(password)),
22871ef4c342SEd Tanous          roleId(std::move(roleId)), enabled, newUser{std::string(*newUserName)},
2288608ad2ccSEd Tanous          locked, userSelf, session = req.session,
2289608ad2ccSEd Tanous          accountTypes(std::move(accountTypes))](
2290e81de512SEd Tanous             const boost::system::error_code& ec, sdbusplus::message_t& m) {
229184e12cb7SAppaRao Puli             if (ec)
229284e12cb7SAppaRao Puli             {
2293002d39b4SEd Tanous                 userErrorMessageHandler(m.get_error(), asyncResp, newUser,
2294002d39b4SEd Tanous                                         username);
2295a840879dSEd Tanous                 return;
2296a840879dSEd Tanous             }
2297a840879dSEd Tanous 
2298002d39b4SEd Tanous             updateUserProperties(asyncResp, newUser, password, enabled, roleId,
2299608ad2ccSEd Tanous                                  locked, accountTypes, userSelf, session);
230084e12cb7SAppaRao Puli         },
23011ef4c342SEd Tanous         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
230284e12cb7SAppaRao Puli         "xyz.openbmc_project.User.Manager", "RenameUser", username,
230384e12cb7SAppaRao Puli         *newUserName);
23041ef4c342SEd Tanous }
23051ef4c342SEd Tanous 
23061ef4c342SEd Tanous inline void requestAccountServiceRoutes(App& app)
23071ef4c342SEd Tanous {
23081ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
23094c7d4d33SEd Tanous         .privileges(redfish::privileges::headAccountService)
23104c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
23114c7d4d33SEd Tanous             std::bind_front(handleAccountServiceHead, std::ref(app)));
23124c7d4d33SEd Tanous 
23134c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
23141ef4c342SEd Tanous         .privileges(redfish::privileges::getAccountService)
23151ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
23161ef4c342SEd Tanous             std::bind_front(handleAccountServiceGet, std::ref(app)));
23171ef4c342SEd Tanous 
23181ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
23191ef4c342SEd Tanous         .privileges(redfish::privileges::patchAccountService)
23201ef4c342SEd Tanous         .methods(boost::beast::http::verb::patch)(
23211ef4c342SEd Tanous             std::bind_front(handleAccountServicePatch, std::ref(app)));
23221ef4c342SEd Tanous 
23231aa375b8SEd Tanous     BMCWEB_ROUTE(
23241aa375b8SEd Tanous         app,
2325e9f12014SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/")
23261aa375b8SEd Tanous         .privileges(redfish::privileges::headCertificateCollection)
23271aa375b8SEd Tanous         .methods(boost::beast::http::verb::head)(std::bind_front(
23281aa375b8SEd Tanous             handleAccountServiceClientCertificatesHead, std::ref(app)));
23291aa375b8SEd Tanous 
23301aa375b8SEd Tanous     BMCWEB_ROUTE(
23311aa375b8SEd Tanous         app,
2332e9f12014SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/")
23331aa375b8SEd Tanous         .privileges(redfish::privileges::getCertificateCollection)
23341aa375b8SEd Tanous         .methods(boost::beast::http::verb::get)(std::bind_front(
23351aa375b8SEd Tanous             handleAccountServiceClientCertificatesGet, std::ref(app)));
23361aa375b8SEd Tanous 
23371aa375b8SEd Tanous     BMCWEB_ROUTE(
23381aa375b8SEd Tanous         app,
2339e9f12014SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/<str>/")
23401aa375b8SEd Tanous         .privileges(redfish::privileges::headCertificate)
23411aa375b8SEd Tanous         .methods(boost::beast::http::verb::head)(std::bind_front(
23421aa375b8SEd Tanous             handleAccountServiceClientCertificatesInstanceHead, std::ref(app)));
23431aa375b8SEd Tanous 
23441aa375b8SEd Tanous     BMCWEB_ROUTE(
23451aa375b8SEd Tanous         app,
23461aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/<str>/")
23471aa375b8SEd Tanous         .privileges(redfish::privileges::getCertificate)
23481aa375b8SEd Tanous         .methods(boost::beast::http::verb::get)(std::bind_front(
23491aa375b8SEd Tanous             handleAccountServiceClientCertificatesInstanceGet, std::ref(app)));
23501aa375b8SEd Tanous 
23511ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
23524c7d4d33SEd Tanous         .privileges(redfish::privileges::headManagerAccountCollection)
23534c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
23544c7d4d33SEd Tanous             std::bind_front(handleAccountCollectionHead, std::ref(app)));
23554c7d4d33SEd Tanous 
23564c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
23571ef4c342SEd Tanous         .privileges(redfish::privileges::getManagerAccountCollection)
23581ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
23591ef4c342SEd Tanous             std::bind_front(handleAccountCollectionGet, std::ref(app)));
23601ef4c342SEd Tanous 
23611ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
23621ef4c342SEd Tanous         .privileges(redfish::privileges::postManagerAccountCollection)
23631ef4c342SEd Tanous         .methods(boost::beast::http::verb::post)(
23641ef4c342SEd Tanous             std::bind_front(handleAccountCollectionPost, std::ref(app)));
23651ef4c342SEd Tanous 
23661ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
23674c7d4d33SEd Tanous         .privileges(redfish::privileges::headManagerAccount)
23684c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
23694c7d4d33SEd Tanous             std::bind_front(handleAccountHead, std::ref(app)));
23704c7d4d33SEd Tanous 
23714c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
23721ef4c342SEd Tanous         .privileges(redfish::privileges::getManagerAccount)
23731ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
23741ef4c342SEd Tanous             std::bind_front(handleAccountGet, std::ref(app)));
23751ef4c342SEd Tanous 
23761ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
23771ef4c342SEd Tanous         // TODO this privilege should be using the generated endpoints, but
23781ef4c342SEd Tanous         // because of the special handling of ConfigureSelf, it's not able to
23791ef4c342SEd Tanous         // yet
23801ef4c342SEd Tanous         .privileges({{"ConfigureUsers"}, {"ConfigureSelf"}})
23811ef4c342SEd Tanous         .methods(boost::beast::http::verb::patch)(
23821ef4c342SEd Tanous             std::bind_front(handleAccountPatch, std::ref(app)));
238384e12cb7SAppaRao Puli 
23846c51eab1SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
2385ed398213SEd Tanous         .privileges(redfish::privileges::deleteManagerAccount)
23866c51eab1SEd Tanous         .methods(boost::beast::http::verb::delete_)(
238720fc307fSGunnar Mills             std::bind_front(handleAccountDelete, std::ref(app)));
238806e086d9SEd Tanous }
238988d16c9aSLewanczyk, Dawid 
239088d16c9aSLewanczyk, Dawid } // namespace redfish
2391