Account.h 2.5 KB

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