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