3 namespace BookStack\Auth\Access;
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;
17 protected const LAST_LOGIN_ATTEMPTED_SESSION_KEY = 'auth-login-last-attempted';
19 protected $mfaSession;
20 protected $emailConfirmationService;
22 public function __construct(MfaSession $mfaSession, EmailConfirmationService $emailConfirmationService)
24 $this->mfaSession = $mfaSession;
25 $this->emailConfirmationService = $emailConfirmationService;
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
35 public function login(User $user, string $method): void
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.
42 // TODO - Need to clear MFA sessions out upon logout
44 // Old MFA middleware todos:
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.
51 $this->clearLastLoginAttempted();
53 Activity::add(ActivityType::AUTH_LOGIN, "{$method}; {$user->logDescriptor()}");
54 Theme::dispatch(ThemeEvents::AUTH_LOGIN, $method, $user);
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);
66 * Reattempt a system login after a previous stopped attempt.
69 public function reattemptLoginFor(User $user)
71 if ($user->id !== ($this->getLastLoginAttemptUser()->id ?? null)) {
72 throw new Exception('Login reattempt user does align with current session state');
75 $this->login($user, $this->getLastLoginAttemptMethod());
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.
83 public function getLastLoginAttemptUser(): ?User
85 $id = $this->getLastLoginAttemptDetails()['user_id'];
86 return User::query()->where('id', '=', $id)->first();
90 * Get the method for the last login attempt.
92 protected function getLastLoginAttemptMethod(): ?string
94 return $this->getLastLoginAttemptDetails()['method'];
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}
102 protected function getLastLoginAttemptDetails(): array
104 $value = session()->get(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
106 return ['user_id' => null, 'method' => null];
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];
116 return ['user_id' => $id, 'method' => $method];
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.
124 protected function setLastLoginAttemptedForUser(User $user, string $method)
127 self::LAST_LOGIN_ATTEMPTED_SESSION_KEY,
128 implode(':', [$user->id, $method, time()])
133 * Clear the last login attempted session value.
135 protected function clearLastLoginAttempted(): void
137 session()->remove(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY);
141 * Check if MFA verification is needed.
143 public function needsMfaVerification(User $user): bool
145 return !$this->mfaSession->isVerifiedForUser($user) && $this->mfaSession->isRequiredForUser($user);
149 * Check if the given user is awaiting email confirmation.
151 public function awaitingEmailConfirmation(User $user): bool
153 return $this->emailConfirmationService->confirmationRequired() && !$user->email_confirmed;
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.
162 * @throws StoppedAuthenticationException
164 public function attempt(array $credentials, string $method, bool $remember = false): bool
166 $result = auth()->attempt($credentials, $remember);
168 $user = auth()->user();
170 $this->login($user, $method);