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