]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/AuthController.php
Merge branch 'v0.11'
[bookstack] / app / Http / Controllers / Auth / AuthController.php
1 <?php namespace BookStack\Http\Controllers\Auth;
2
3 use BookStack\Exceptions\AuthException;
4 use Illuminate\Contracts\Auth\Authenticatable;
5 use Illuminate\Http\Request;
6 use BookStack\Exceptions\SocialSignInException;
7 use BookStack\Exceptions\UserRegistrationException;
8 use BookStack\Repos\UserRepo;
9 use BookStack\Services\EmailConfirmationService;
10 use BookStack\Services\SocialAuthService;
11 use BookStack\SocialAccount;
12 use Validator;
13 use BookStack\Http\Controllers\Controller;
14 use Illuminate\Foundation\Auth\ThrottlesLogins;
15 use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
16
17 class AuthController extends Controller
18 {
19     /*
20     |--------------------------------------------------------------------------
21     | Registration & Login Controller
22     |--------------------------------------------------------------------------
23     |
24     | This controller handles the registration of new users, as well as the
25     | authentication of existing users. By default, this controller uses
26     | a simple trait to add these behaviors. Why don't you explore it?
27     |
28     */
29
30     use AuthenticatesAndRegistersUsers, ThrottlesLogins;
31
32     protected $redirectPath = '/';
33     protected $redirectAfterLogout = '/login';
34     protected $username = 'email';
35
36     protected $socialAuthService;
37     protected $emailConfirmationService;
38     protected $userRepo;
39
40     /**
41      * Create a new authentication controller instance.
42      * @param SocialAuthService $socialAuthService
43      * @param EmailConfirmationService $emailConfirmationService
44      * @param UserRepo $userRepo
45      */
46     public function __construct(SocialAuthService $socialAuthService, EmailConfirmationService $emailConfirmationService, UserRepo $userRepo)
47     {
48         $this->middleware('guest', ['only' => ['getLogin', 'postLogin', 'getRegister', 'postRegister']]);
49         $this->socialAuthService = $socialAuthService;
50         $this->emailConfirmationService = $emailConfirmationService;
51         $this->userRepo = $userRepo;
52         $this->redirectPath = baseUrl('/');
53         $this->redirectAfterLogout = baseUrl('/login');
54         $this->username = config('auth.method') === 'standard' ? 'email' : 'username';
55         parent::__construct();
56     }
57
58     /**
59      * Get a validator for an incoming registration request.
60      * @param  array $data
61      * @return \Illuminate\Contracts\Validation\Validator
62      */
63     protected function validator(array $data)
64     {
65         return Validator::make($data, [
66             'name' => 'required|max:255',
67             'email' => 'required|email|max:255|unique:users',
68             'password' => 'required|min:6',
69         ]);
70     }
71
72     protected function checkRegistrationAllowed()
73     {
74         if (!setting('registration-enabled')) {
75             throw new UserRegistrationException('Registrations are currently disabled.', '/login');
76         }
77     }
78
79     /**
80      * Show the application registration form.
81      * @return \Illuminate\Http\Response
82      */
83     public function getRegister()
84     {
85         $this->checkRegistrationAllowed();
86         $socialDrivers = $this->socialAuthService->getActiveDrivers();
87         return view('auth.register', ['socialDrivers' => $socialDrivers]);
88     }
89
90     /**
91      * Handle a registration request for the application.
92      * @param  \Illuminate\Http\Request $request
93      * @return \Illuminate\Http\Response
94      * @throws UserRegistrationException
95      */
96     public function postRegister(Request $request)
97     {
98         $this->checkRegistrationAllowed();
99         $validator = $this->validator($request->all());
100
101         if ($validator->fails()) {
102             $this->throwValidationException(
103                 $request, $validator
104             );
105         }
106
107         $userData = $request->all();
108         return $this->registerUser($userData);
109     }
110
111
112     /**
113      * Overrides the action when a user is authenticated.
114      * If the user authenticated but does not exist in the user table we create them.
115      * @param Request $request
116      * @param Authenticatable $user
117      * @return \Illuminate\Http\RedirectResponse
118      * @throws AuthException
119      */
120     protected function authenticated(Request $request, Authenticatable $user)
121     {
122         // Explicitly log them out for now if they do no exist.
123         if (!$user->exists) auth()->logout($user);
124
125         if (!$user->exists && $user->email === null && !$request->has('email')) {
126             $request->flash();
127             session()->flash('request-email', true);
128             return redirect('/login');
129         }
130
131         if (!$user->exists && $user->email === null && $request->has('email')) {
132             $user->email = $request->get('email');
133         }
134
135         if (!$user->exists) {
136
137             // Check for users with same email already
138             $alreadyUser = $user->newQuery()->where('email', '=', $user->email)->count() > 0;
139             if ($alreadyUser) {
140                 throw new AuthException('A user with the email ' . $user->email . ' already exists but with different credentials.');
141             }
142
143             $user->save();
144             $this->userRepo->attachDefaultRole($user);
145             auth()->login($user);
146         }
147
148         return redirect()->intended($this->redirectPath());
149     }
150
151     /**
152      * Register a new user after a registration callback.
153      * @param $socialDriver
154      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
155      * @throws UserRegistrationException
156      */
157     protected function socialRegisterCallback($socialDriver)
158     {
159         $socialUser = $this->socialAuthService->handleRegistrationCallback($socialDriver);
160         $socialAccount = $this->socialAuthService->fillSocialAccount($socialDriver, $socialUser);
161
162         // Create an array of the user data to create a new user instance
163         $userData = [
164             'name' => $socialUser->getName(),
165             'email' => $socialUser->getEmail(),
166             'password' => str_random(30)
167         ];
168         return $this->registerUser($userData, $socialAccount);
169     }
170
171     /**
172      * The registrations flow for all users.
173      * @param array $userData
174      * @param bool|false|SocialAccount $socialAccount
175      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
176      * @throws UserRegistrationException
177      * @throws \BookStack\Exceptions\ConfirmationEmailException
178      */
179     protected function registerUser(array $userData, $socialAccount = false)
180     {
181         if (setting('registration-restrict')) {
182             $restrictedEmailDomains = explode(',', str_replace(' ', '', setting('registration-restrict')));
183             $userEmailDomain = $domain = substr(strrchr($userData['email'], "@"), 1);
184             if (!in_array($userEmailDomain, $restrictedEmailDomains)) {
185                 throw new UserRegistrationException('That email domain does not have access to this application', '/register');
186             }
187         }
188
189         $newUser = $this->userRepo->registerNew($userData);
190         if ($socialAccount) {
191             $newUser->socialAccounts()->save($socialAccount);
192         }
193
194         if (setting('registration-confirmation') || setting('registration-restrict')) {
195             $newUser->save();
196             $this->emailConfirmationService->sendConfirmation($newUser);
197             return redirect('/register/confirm');
198         }
199
200         auth()->login($newUser);
201         session()->flash('success', 'Thanks for signing up! You are now registered and signed in.');
202         return redirect($this->redirectPath());
203     }
204
205     /**
206      * Show the page to tell the user to check their email
207      * and confirm their address.
208      */
209     public function getRegisterConfirmation()
210     {
211         return view('auth/register-confirm');
212     }
213
214     /**
215      * View the confirmation email as a standard web page.
216      * @param $token
217      * @return \Illuminate\View\View
218      * @throws UserRegistrationException
219      */
220     public function viewConfirmEmail($token)
221     {
222         $confirmation = $this->emailConfirmationService->getEmailConfirmationFromToken($token);
223         return view('emails/email-confirmation', ['token' => $confirmation->token]);
224     }
225
226     /**
227      * Confirms an email via a token and logs the user into the system.
228      * @param $token
229      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
230      * @throws UserRegistrationException
231      */
232     public function confirmEmail($token)
233     {
234         $confirmation = $this->emailConfirmationService->getEmailConfirmationFromToken($token);
235         $user = $confirmation->user;
236         $user->email_confirmed = true;
237         $user->save();
238         auth()->login($confirmation->user);
239         session()->flash('success', 'Your email has been confirmed!');
240         $this->emailConfirmationService->deleteConfirmationsByUser($user);
241         return redirect($this->redirectPath);
242     }
243
244     /**
245      * Shows a notice that a user's email address has not been confirmed,
246      * Also has the option to re-send the confirmation email.
247      * @return \Illuminate\View\View
248      */
249     public function showAwaitingConfirmation()
250     {
251         return view('auth/user-unconfirmed');
252     }
253
254     /**
255      * Resend the confirmation email
256      * @param Request $request
257      * @return \Illuminate\View\View
258      */
259     public function resendConfirmation(Request $request)
260     {
261         $this->validate($request, [
262             'email' => 'required|email|exists:users,email'
263         ]);
264         $user = $this->userRepo->getByEmail($request->get('email'));
265         $this->emailConfirmationService->sendConfirmation($user);
266         session()->flash('success', 'Confirmation email resent, Please check your inbox.');
267         return redirect('/register/confirm');
268     }
269
270     /**
271      * Show the application login form.
272      * @return \Illuminate\Http\Response
273      */
274     public function getLogin()
275     {
276         $socialDrivers = $this->socialAuthService->getActiveDrivers();
277         $authMethod = config('auth.method');
278         return view('auth/login', ['socialDrivers' => $socialDrivers, 'authMethod' => $authMethod]);
279     }
280
281     /**
282      * Redirect to the relevant social site.
283      * @param $socialDriver
284      * @return \Symfony\Component\HttpFoundation\RedirectResponse
285      */
286     public function getSocialLogin($socialDriver)
287     {
288         session()->put('social-callback', 'login');
289         return $this->socialAuthService->startLogIn($socialDriver);
290     }
291
292     /**
293      * Redirect to the social site for authentication intended to register.
294      * @param $socialDriver
295      * @return mixed
296      */
297     public function socialRegister($socialDriver)
298     {
299         $this->checkRegistrationAllowed();
300         session()->put('social-callback', 'register');
301         return $this->socialAuthService->startRegister($socialDriver);
302     }
303
304     /**
305      * The callback for social login services.
306      * @param $socialDriver
307      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
308      * @throws SocialSignInException
309      */
310     public function socialCallback($socialDriver)
311     {
312         if (session()->has('social-callback')) {
313             $action = session()->pull('social-callback');
314             if ($action == 'login') {
315                 return $this->socialAuthService->handleLoginCallback($socialDriver);
316             } elseif ($action == 'register') {
317                 return $this->socialRegisterCallback($socialDriver);
318             }
319         } else {
320             throw new SocialSignInException('No action defined', '/login');
321         }
322         return redirect()->back();
323     }
324
325     /**
326      * Detach a social account from a user.
327      * @param $socialDriver
328      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
329      */
330     public function detachSocialAccount($socialDriver)
331     {
332         return $this->socialAuthService->detachSocialAccount($socialDriver);
333     }
334
335 }