Account.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. static Result<Account, String> from_name(const char* username);
  26. static Result<Account, String> from_uid(uid_t uid);
  27. bool authenticate(const char* password) const;
  28. bool login() const;
  29. String username() const { return m_username; }
  30. String password_hash() const { return m_password_hash; }
  31. // Setters only affect in-memory copy of password.
  32. // You must call sync to apply changes.
  33. void set_password(const char* password);
  34. void set_password_enabled(bool enabled);
  35. void delete_password();
  36. // A null password means that this account was missing from /etc/shadow.
  37. // It's considered to have a password in that case, and authentication will always fail.
  38. bool has_password() const { return !m_password_hash.is_empty() || m_password_hash.is_null(); }
  39. uid_t uid() const { return m_uid; }
  40. gid_t gid() const { return m_gid; }
  41. const String& gecos() const { return m_gecos; }
  42. const String& home_directory() const { return m_home_directory; }
  43. const String& shell() const { return m_shell; }
  44. const Vector<gid_t>& extra_gids() const { return m_extra_gids; }
  45. bool sync();
  46. private:
  47. static Result<Account, String> from_passwd(const passwd&, const spwd&);
  48. Account(const passwd& pwd, const spwd& spwd, Vector<gid_t> extra_gids);
  49. String generate_passwd_file() const;
  50. #ifndef AK_OS_BSD_GENERIC
  51. String generate_shadow_file() const;
  52. #endif
  53. String m_username;
  54. String m_password_hash;
  55. uid_t m_uid { 0 };
  56. gid_t m_gid { 0 };
  57. String m_gecos;
  58. String m_home_directory;
  59. String m_shell;
  60. Vector<gid_t> m_extra_gids;
  61. };
  62. }