Account.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 delete_password();
  41. // A null password means that this account was missing from /etc/shadow.
  42. // It's considered to have a password in that case, and authentication will always fail.
  43. bool has_password() const { return !m_password_hash.is_empty() || m_password_hash.is_null(); }
  44. uid_t uid() const { return m_uid; }
  45. gid_t gid() const { return m_gid; }
  46. const String& gecos() const { return m_gecos; }
  47. const String& home_directory() const { return m_home_directory; }
  48. const String& shell() const { return m_shell; }
  49. const Vector<gid_t>& extra_gids() const { return m_extra_gids; }
  50. bool sync();
  51. private:
  52. static Result<Account, String> from_passwd(const passwd&, const spwd&);
  53. Account(const passwd& pwd, const spwd& spwd, Vector<gid_t> extra_gids);
  54. String generate_passwd_file() const;
  55. #ifndef AK_OS_BSD_GENERIC
  56. String generate_shadow_file() const;
  57. #endif
  58. String m_username;
  59. String m_password_hash;
  60. uid_t m_uid { 0 };
  61. gid_t m_gid { 0 };
  62. String m_gecos;
  63. String m_home_directory;
  64. String m_shell;
  65. Vector<gid_t> m_extra_gids;
  66. };
  67. }