login_authorization.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace phpnotify;
  3. use \TypeError as TypeError;
  4. use \base64_encode as base64_encode;
  5. /**
  6. * This could be used to authorize by username and password.
  7. *
  8. * It could be used to authorize by login and password. It is better option
  9. * than empty authorization, which does not give any security, but it is
  10. * necessary to use TLS, because password and login does not being hashed,
  11. * and could being captured by intermediary when use empty HTTP.
  12. */
  13. class login_authorization extends authorization_method {
  14. /**
  15. * It store encoded login and password, in form which is used by header,
  16. * that mean `base64('login:password')`.
  17. * @var string
  18. */
  19. private string $coded;
  20. /**
  21. * This create new login authorization.
  22. *
  23. * This create new login authorization, require username and password
  24. * for them. Username and password could not being empty.
  25. *
  26. * @throws TypeError When login or password is empty.
  27. *
  28. * @param string $login Login of the user.
  29. * @param string $password Password for that user.
  30. */
  31. public function __construct(string $login, string $password) {
  32. $login = trim($login);
  33. $password = trim($password);
  34. if (strlen($login) === 0 || strlen($password) === 0) {
  35. throw new TypeError('Login and password could being empty.');
  36. }
  37. $this->coded = $this->encode($login, $password);
  38. }
  39. /**
  40. * It return true, because header is required when use login.
  41. *
  42. * @return bool True because header is required for login authorization.
  43. */
  44. public function is_header_required(): bool {
  45. return true;
  46. }
  47. /**
  48. * This return content of the header.
  49. *
  50. * This return content of the headed, which contain coded login and
  51. * password. It is coded in the base64, which is not hash function end
  52. * could be easy decoded. It is cause that TLS must being used.
  53. *
  54. * @return string Content of the headed.
  55. */
  56. public function header_content(): string {
  57. return 'Basic '.$this->coded;
  58. }
  59. /**
  60. * This encode login and password to use it headed.
  61. *
  62. * @param string $login Login of the user.
  63. * @param string $password Password for that user.
  64. * @return string Encoded form of login and password.
  65. */
  66. private function encode(string $login, string $password): string {
  67. return base64_encode($login.':'.$password);
  68. }
  69. }