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