]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/LoginService.php
Reviewed and refactored additional editor draft save warnings
[bookstack] / app / Auth / Access / LoginService.php
1 <?php
2
3 namespace BookStack\Auth\Access;
4
5 use BookStack\Actions\ActivityType;
6 use BookStack\Auth\Access\Mfa\MfaSession;
7 use BookStack\Auth\User;
8 use BookStack\Exceptions\StoppedAuthenticationException;
9 use BookStack\Facades\Activity;
10 use BookStack\Facades\Theme;
11 use BookStack\Theming\ThemeEvents;
12 use Exception;
13
14 class LoginService
15 {
16     protected const LAST_LOGIN_ATTEMPTED_SESSION_KEY = 'auth-login-last-attempted';
17
18     protected $mfaSession;
19     protected $emailConfirmationService;
20
21     public function __construct(MfaSession $mfaSession, EmailConfirmationService $emailConfirmationService)
22     {
23         $this->mfaSession = $mfaSession;
24         $this->emailConfirmationService = $emailConfirmationService;
25     }
26
27     /**
28      * Log the given user into the system.
29      * Will start a login of the given user but will prevent if there's
30      * a reason to (MFA or Unconfirmed Email).
31      * Returns a boolean to indicate the current login result.
32      *
33      * @throws StoppedAuthenticationException
34      */
35     public function login(User $user, string $method, bool $remember = false): void
36     {
37         if ($this->awaitingEmailConfirmation($user) || $this->needsMfaVerification($user)) {
38             $this->setLastLoginAttemptedForUser($user, $method, $remember);
39
40             throw new StoppedAuthenticationException($user, $this);
41         }
42
43         $this->clearLastLoginAttempted();
44         auth()->login($user, $remember);
45         Activity::add(ActivityType::AUTH_LOGIN, "{$method}; {$user->logDescriptor()}");
46         Theme::dispatch(ThemeEvents::AUTH_LOGIN, $method, $user);
47
48         // Authenticate on all session guards if a likely admin
49         if ($user->can('users-manage') && $user->can('user-roles-manage')) {
50             $guards = ['standard', 'ldap', 'saml2'];
51             foreach ($guards as $guard) {
52                 auth($guard)->login($user);
53             }
54         }
55     }
56
57     /**
58      * Reattempt a system login after a previous stopped attempt.
59      *
60      * @throws Exception
61      */
62     public function reattemptLoginFor(User $user)
63     {
64         if ($user->id !== ($this->getLastLoginAttemptUser()->id ?? null)) {
65             throw new Exception('Login reattempt user does align with current session state');
66         }
67
68         $lastLoginDetails = $this->getLastLoginAttemptDetails();
69         $this->login($user, $lastLoginDetails['method'], $lastLoginDetails['remember'] ?? false);
70     }
71
72     /**
73      * Get the last user that was attempted to be logged in.
74      * Only exists if the last login attempt had correct credentials
75      * but had been prevented by a secondary factor.
76      */
77     public function getLastLoginAttemptUser(): ?User
78     {
79         $id = $this->getLastLoginAttemptDetails()['user_id'];
80
81         return User::query()->where('id', '=', $id)->first();
82     }
83
84     /**
85      * Get the details of the last login attempt.
86      * Checks upon a ttl of about 1 hour since that last attempted login.
87      *
88      * @return array{user_id: ?string, method: ?string, remember: bool}
89      */
90     protected function getLastLoginAttemptDetails(): array
91     {
92         $value = session()->get(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
93         if (!$value) {
94             return ['user_id' => null, 'method' => null];
95         }
96
97         [$id, $method, $remember, $time] = explode(':', $value);
98         $hourAgo = time() - (60 * 60);
99         if ($time < $hourAgo) {
100             $this->clearLastLoginAttempted();
101
102             return ['user_id' => null, 'method' => null];
103         }
104
105         return ['user_id' => $id, 'method' => $method, 'remember' => boolval($remember)];
106     }
107
108     /**
109      * Set the last login attempted user.
110      * Must be only used when credentials are correct and a login could be
111      * achieved but a secondary factor has stopped the login.
112      */
113     protected function setLastLoginAttemptedForUser(User $user, string $method, bool $remember)
114     {
115         session()->put(
116             self::LAST_LOGIN_ATTEMPTED_SESSION_KEY,
117             implode(':', [$user->id, $method, $remember, time()])
118         );
119     }
120
121     /**
122      * Clear the last login attempted session value.
123      */
124     protected function clearLastLoginAttempted(): void
125     {
126         session()->remove(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
127     }
128
129     /**
130      * Check if MFA verification is needed.
131      */
132     public function needsMfaVerification(User $user): bool
133     {
134         return !$this->mfaSession->isVerifiedForUser($user) && $this->mfaSession->isRequiredForUser($user);
135     }
136
137     /**
138      * Check if the given user is awaiting email confirmation.
139      */
140     public function awaitingEmailConfirmation(User $user): bool
141     {
142         return $this->emailConfirmationService->confirmationRequired() && !$user->email_confirmed;
143     }
144
145     /**
146      * Attempt the login of a user using the given credentials.
147      * Meant to mirror Laravel's default guard 'attempt' method
148      * but in a manner that always routes through our login system.
149      * May interrupt the flow if extra authentication requirements are imposed.
150      *
151      * @throws StoppedAuthenticationException
152      */
153     public function attempt(array $credentials, string $method, bool $remember = false): bool
154     {
155         $result = auth()->attempt($credentials, $remember);
156         if ($result) {
157             $user = auth()->user();
158             auth()->logout();
159             $this->login($user, $method, $remember);
160         }
161
162         return $result;
163     }
164 }