Account.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright (c) 2020, Peter Elliott <pelliott@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Result.h>
  8. #include <AK/String.h>
  9. #include <AK/Types.h>
  10. #include <AK/Vector.h>
  11. #include <LibCore/SecretString.h>
  12. #include <pwd.h>
  13. #ifndef AK_OS_BSD_GENERIC
  14. # include <shadow.h>
  15. #endif
  16. #include <sys/types.h>
  17. namespace Core {
  18. #ifdef AK_OS_BSD_GENERIC
  19. struct spwd {
  20. char* sp_namp;
  21. char* sp_pwdp;
  22. };
  23. #endif
  24. class Account {
  25. public:
  26. enum class Read {
  27. All,
  28. PasswdOnly
  29. };
  30. static Account self(Read options = Read::All);
  31. static Result<Account, String> from_name(const char* username, Read options = Read::All);
  32. static Result<Account, String> from_uid(uid_t uid, Read options = Read::All);
  33. bool authenticate(SecretString const& password) const;
  34. bool login() const;
  35. String username() const { return m_username; }
  36. String password_hash() const { return m_password_hash; }
  37. // Setters only affect in-memory copy of password.
  38. // You must call sync to apply changes.
  39. void set_password(const char* password);
  40. void set_password_enabled(bool enabled);
  41. void set_home_directory(const char* home_directory) { m_home_directory = home_directory; }
  42. void set_uid(uid_t uid) { m_uid = uid; }
  43. void set_gid(gid_t gid) { m_gid = gid; }
  44. void set_shell(const char* shell) { m_shell = shell; }
  45. void set_gecos(const char* gecos) { m_gecos = gecos; }
  46. void delete_password();
  47. // A null password means that this account was missing from /etc/shadow.
  48. // It's considered to have a password in that case, and authentication will always fail.
  49. bool has_password() const { return !m_password_hash.is_empty() || m_password_hash.is_null(); }
  50. uid_t uid() const { return m_uid; }
  51. gid_t gid() const { return m_gid; }
  52. const String& gecos() const { return m_gecos; }
  53. const String& home_directory() const { return m_home_directory; }
  54. const String& shell() const { return m_shell; }
  55. const Vector<gid_t>& extra_gids() const { return m_extra_gids; }
  56. bool sync();
  57. private:
  58. static Result<Account, String> from_passwd(const passwd&, const spwd&);
  59. Account(const passwd& pwd, const spwd& spwd, Vector<gid_t> extra_gids);
  60. String generate_passwd_file() const;
  61. #ifndef AK_OS_BSD_GENERIC
  62. String generate_shadow_file() const;
  63. #endif
  64. String m_username;
  65. String m_password_hash;
  66. uid_t m_uid { 0 };
  67. gid_t m_gid { 0 };
  68. String m_gecos;
  69. String m_home_directory;
  70. String m_shell;
  71. Vector<gid_t> m_extra_gids;
  72. };
  73. }