]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/LoginService.php
Worked on MFA setup required flow
[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 use phpDocumentor\Reflection\DocBlock\Tags\Method;
14
15 class LoginService
16 {
17
18     protected const LAST_LOGIN_ATTEMPTED_SESSION_KEY = 'auth-login-last-attempted';
19
20     protected $mfaSession;
21
22     public function __construct(MfaSession $mfaSession)
23     {
24         $this->mfaSession = $mfaSession;
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      * @throws StoppedAuthenticationException
33      */
34     public function login(User $user, string $method): void
35     {
36         if ($this->awaitingEmailConfirmation($user) || $this->needsMfaVerification($user)) {
37             $this->setLastLoginAttemptedForUser($user, $method);
38             throw new StoppedAuthenticationException($user, $this);
39             // TODO - Does 'remember' still work? Probably not right now.
40
41             // TODO - Need to clear MFA sessions out upon logout
42
43             // Old MFA middleware todos:
44
45             // TODO - Handle email confirmation handling
46             //  Left BookStack\Http\Middleware\Authenticate@emailConfirmationErrorResponse in which needs
47             //  be removed as an example of old behaviour.
48         }
49
50         $this->clearLastLoginAttempted();
51         auth()->login($user);
52         Activity::add(ActivityType::AUTH_LOGIN, "{$method}; {$user->logDescriptor()}");
53         Theme::dispatch(ThemeEvents::AUTH_LOGIN, $method, $user);
54
55         // Authenticate on all session guards if a likely admin
56         if ($user->can('users-manage') && $user->can('user-roles-manage')) {
57             $guards = ['standard', 'ldap', 'saml2'];
58             foreach ($guards as $guard) {
59                 auth($guard)->login($user);
60             }
61         }
62     }
63
64     /**
65      * Reattempt a system login after a previous stopped attempt.
66      * @throws Exception
67      */
68     public function reattemptLoginFor(User $user)
69     {
70         if ($user->id !== ($this->getLastLoginAttemptUser()->id ?? null)) {
71             throw new Exception('Login reattempt user does align with current session state');
72         }
73
74         $this->login($user, $this->getLastLoginAttemptMethod());
75     }
76
77     /**
78      * Get the last user that was attempted to be logged in.
79      * Only exists if the last login attempt had correct credentials
80      * but had been prevented by a secondary factor.
81      */
82     public function getLastLoginAttemptUser(): ?User
83     {
84         $id = $this->getLastLoginAttemptDetails()['user_id'];
85         return User::query()->where('id', '=', $id)->first();
86     }
87
88     /**
89      * Get the method for the last login attempt.
90      */
91     protected function getLastLoginAttemptMethod(): ?string
92     {
93         return $this->getLastLoginAttemptDetails()['method'];
94     }
95
96     /**
97      * Get the details of the last login attempt.
98      * Checks upon a ttl of about 1 hour since that last attempted login.
99      * @return array{user_id: ?string, method: ?string}
100      */
101     protected function getLastLoginAttemptDetails(): array
102     {
103         $value = session()->get(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
104         if (!$value) {
105             return ['user_id' => null, 'method' => null];
106         }
107
108         [$id, $method, $time] = explode(':', $value);
109         $hourAgo = time() - (60*60);
110         if ($time < $hourAgo) {
111             $this->clearLastLoginAttempted();
112             return ['user_id' => null, 'method' => null];
113         }
114
115         return ['user_id' => $id, 'method' => $method];
116     }
117
118     /**
119      * Set the last login attempted user.
120      * Must be only used when credentials are correct and a login could be
121      * achieved but a secondary factor has stopped the login.
122      */
123     protected function setLastLoginAttemptedForUser(User $user, string $method)
124     {
125         session()->put(
126             self::LAST_LOGIN_ATTEMPTED_SESSION_KEY,
127             implode(':', [$user->id, $method, time()])
128         );
129     }
130
131     /**
132      * Clear the last login attempted session value.
133      */
134     protected function clearLastLoginAttempted(): void
135     {
136         session()->remove(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
137     }
138
139     /**
140      * Check if MFA verification is needed.
141      */
142     public function needsMfaVerification(User $user): bool
143     {
144         return !$this->mfaSession->isVerifiedForUser($user) && $this->mfaSession->isRequiredForUser($user);
145     }
146
147     /**
148      * Check if the given user is awaiting email confirmation.
149      */
150     public function awaitingEmailConfirmation(User $user): bool
151     {
152         $requireConfirmation = (setting('registration-confirmation') || setting('registration-restrict'));
153         return $requireConfirmation && !$user->email_confirmed;
154     }
155
156     /**
157      * Attempt the login of a user using the given credentials.
158      * Meant to mirror Laravel's default guard 'attempt' method
159      * but in a manner that always routes through our login system.
160      * May interrupt the flow if extra authentication requirements are imposed.
161      *
162      * @throws StoppedAuthenticationException
163      */
164     public function attempt(array $credentials, string $method, bool $remember = false): bool
165     {
166         $result = auth()->attempt($credentials, $remember);
167         if ($result) {
168             $user = auth()->user();
169             auth()->logout();
170             $this->login($user, $method);
171         }
172
173         return $result;
174     }
175
176 }