]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/LoginService.php
Quick test of email confirmation routes and fix of tests
[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
17     protected const LAST_LOGIN_ATTEMPTED_SESSION_KEY = 'auth-login-last-attempted';
18
19     protected $mfaSession;
20     protected $emailConfirmationService;
21
22     public function __construct(MfaSession $mfaSession, EmailConfirmationService $emailConfirmationService)
23     {
24         $this->mfaSession = $mfaSession;
25         $this->emailConfirmationService = $emailConfirmationService;
26     }
27
28     /**
29      * Log the given user into the system.
30      * Will start a login of the given user but will prevent if there's
31      * a reason to (MFA or Unconfirmed Email).
32      * Returns a boolean to indicate the current login result.
33      * @throws StoppedAuthenticationException
34      */
35     public function login(User $user, string $method): void
36     {
37         if ($this->awaitingEmailConfirmation($user) || $this->needsMfaVerification($user)) {
38             $this->setLastLoginAttemptedForUser($user, $method);
39             throw new StoppedAuthenticationException($user, $this);
40             // TODO - Does 'remember' still work? Probably not right now.
41
42             // TODO - Need to clear MFA sessions out upon logout
43
44             // Old MFA middleware todos:
45
46             // TODO - Handle email confirmation handling
47             //  Left BookStack\Http\Middleware\Authenticate@emailConfirmationErrorResponse in which needs
48             //  be removed as an example of old behaviour.
49         }
50
51         $this->clearLastLoginAttempted();
52         auth()->login($user);
53         Activity::add(ActivityType::AUTH_LOGIN, "{$method}; {$user->logDescriptor()}");
54         Theme::dispatch(ThemeEvents::AUTH_LOGIN, $method, $user);
55
56         // Authenticate on all session guards if a likely admin
57         if ($user->can('users-manage') && $user->can('user-roles-manage')) {
58             $guards = ['standard', 'ldap', 'saml2'];
59             foreach ($guards as $guard) {
60                 auth($guard)->login($user);
61             }
62         }
63     }
64
65     /**
66      * Reattempt a system login after a previous stopped attempt.
67      * @throws Exception
68      */
69     public function reattemptLoginFor(User $user)
70     {
71         if ($user->id !== ($this->getLastLoginAttemptUser()->id ?? null)) {
72             throw new Exception('Login reattempt user does align with current session state');
73         }
74
75         $this->login($user, $this->getLastLoginAttemptMethod());
76     }
77
78     /**
79      * Get the last user that was attempted to be logged in.
80      * Only exists if the last login attempt had correct credentials
81      * but had been prevented by a secondary factor.
82      */
83     public function getLastLoginAttemptUser(): ?User
84     {
85         $id = $this->getLastLoginAttemptDetails()['user_id'];
86         return User::query()->where('id', '=', $id)->first();
87     }
88
89     /**
90      * Get the method for the last login attempt.
91      */
92     protected function getLastLoginAttemptMethod(): ?string
93     {
94         return $this->getLastLoginAttemptDetails()['method'];
95     }
96
97     /**
98      * Get the details of the last login attempt.
99      * Checks upon a ttl of about 1 hour since that last attempted login.
100      * @return array{user_id: ?string, method: ?string}
101      */
102     protected function getLastLoginAttemptDetails(): array
103     {
104         $value = session()->get(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
105         if (!$value) {
106             return ['user_id' => null, 'method' => null];
107         }
108
109         [$id, $method, $time] = explode(':', $value);
110         $hourAgo = time() - (60*60);
111         if ($time < $hourAgo) {
112             $this->clearLastLoginAttempted();
113             return ['user_id' => null, 'method' => null];
114         }
115
116         return ['user_id' => $id, 'method' => $method];
117     }
118
119     /**
120      * Set the last login attempted user.
121      * Must be only used when credentials are correct and a login could be
122      * achieved but a secondary factor has stopped the login.
123      */
124     protected function setLastLoginAttemptedForUser(User $user, string $method)
125     {
126         session()->put(
127             self::LAST_LOGIN_ATTEMPTED_SESSION_KEY,
128             implode(':', [$user->id, $method, time()])
129         );
130     }
131
132     /**
133      * Clear the last login attempted session value.
134      */
135     protected function clearLastLoginAttempted(): void
136     {
137         session()->remove(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
138     }
139
140     /**
141      * Check if MFA verification is needed.
142      */
143     public function needsMfaVerification(User $user): bool
144     {
145         return !$this->mfaSession->isVerifiedForUser($user) && $this->mfaSession->isRequiredForUser($user);
146     }
147
148     /**
149      * Check if the given user is awaiting email confirmation.
150      */
151     public function awaitingEmailConfirmation(User $user): bool
152     {
153         return $this->emailConfirmationService->confirmationRequired() && !$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 }