]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/AuthController.php
21abfb24c84950675f725c9ae2a7d104007ac573
[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         if(!$user->exists && $user->email === null && !$request->has('email')) {
122             $request->flash();
123             session()->flash('request-email', true);
124             return redirect('/login');
125         }
126
127         if(!$user->exists && $user->email === null && $request->has('email')) {
128             $user->email = $request->get('email');
129         }
130
131         if(!$user->exists) {
132             $user->save();
133             $this->userRepo->attachDefaultRole($user);
134             auth()->login($user);
135         }
136
137         return redirect()->intended($this->redirectPath());
138     }
139
140     /**
141      * Register a new user after a registration callback.
142      * @param $socialDriver
143      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
144      * @throws UserRegistrationException
145      */
146     protected function socialRegisterCallback($socialDriver)
147     {
148         $socialUser = $this->socialAuthService->handleRegistrationCallback($socialDriver);
149         $socialAccount = $this->socialAuthService->fillSocialAccount($socialDriver, $socialUser);
150
151         // Create an array of the user data to create a new user instance
152         $userData = [
153             'name'     => $socialUser->getName(),
154             'email'    => $socialUser->getEmail(),
155             'password' => str_random(30)
156         ];
157         return $this->registerUser($userData, $socialAccount);
158     }
159
160     /**
161      * The registrations flow for all users.
162      * @param array                    $userData
163      * @param bool|false|SocialAccount $socialAccount
164      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
165      * @throws UserRegistrationException
166      * @throws \BookStack\Exceptions\ConfirmationEmailException
167      */
168     protected function registerUser(array $userData, $socialAccount = false)
169     {
170         if (\Setting::get('registration-restrict')) {
171             $restrictedEmailDomains = explode(',', str_replace(' ', '', \Setting::get('registration-restrict')));
172             $userEmailDomain = $domain = substr(strrchr($userData['email'], "@"), 1);
173             if (!in_array($userEmailDomain, $restrictedEmailDomains)) {
174                 throw new UserRegistrationException('That email domain does not have access to this application', '/register');
175             }
176         }
177
178         $newUser = $this->userRepo->registerNew($userData);
179         if ($socialAccount) {
180             $newUser->socialAccounts()->save($socialAccount);
181         }
182
183         if (\Setting::get('registration-confirmation') || \Setting::get('registration-restrict')) {
184             $newUser->email_confirmed = false;
185             $newUser->save();
186             $this->emailConfirmationService->sendConfirmation($newUser);
187             return redirect('/register/confirm');
188         }
189
190         $newUser->email_confirmed = true;
191         auth()->login($newUser);
192         session()->flash('success', 'Thanks for signing up! You are now registered and signed in.');
193         return redirect($this->redirectPath());
194     }
195
196     /**
197      * Show the page to tell the user to check their email
198      * and confirm their address.
199      */
200     public function getRegisterConfirmation()
201     {
202         return view('auth/register-confirm');
203     }
204
205     /**
206      * View the confirmation email as a standard web page.
207      * @param $token
208      * @return \Illuminate\View\View
209      * @throws UserRegistrationException
210      */
211     public function viewConfirmEmail($token)
212     {
213         $confirmation = $this->emailConfirmationService->getEmailConfirmationFromToken($token);
214         return view('emails/email-confirmation', ['token' => $confirmation->token]);
215     }
216
217     /**
218      * Confirms an email via a token and logs the user into the system.
219      * @param $token
220      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
221      * @throws UserRegistrationException
222      */
223     public function confirmEmail($token)
224     {
225         $confirmation = $this->emailConfirmationService->getEmailConfirmationFromToken($token);
226         $user = $confirmation->user;
227         $user->email_confirmed = true;
228         $user->save();
229         auth()->login($confirmation->user);
230         session()->flash('success', 'Your email has been confirmed!');
231         $this->emailConfirmationService->deleteConfirmationsByUser($user);
232         return redirect($this->redirectPath);
233     }
234
235     /**
236      * Shows a notice that a user's email address has not been confirmed,
237      * Also has the option to re-send the confirmation email.
238      * @return \Illuminate\View\View
239      */
240     public function showAwaitingConfirmation()
241     {
242         return view('auth/user-unconfirmed');
243     }
244
245     /**
246      * Resend the confirmation email
247      * @param Request $request
248      * @return \Illuminate\View\View
249      */
250     public function resendConfirmation(Request $request)
251     {
252         $this->validate($request, [
253             'email' => 'required|email|exists:users,email'
254         ]);
255         $user = $this->userRepo->getByEmail($request->get('email'));
256         $this->emailConfirmationService->sendConfirmation($user);
257         session()->flash('success', 'Confirmation email resent, Please check your inbox.');
258         return redirect('/register/confirm');
259     }
260
261     /**
262      * Show the application login form.
263      * @return \Illuminate\Http\Response
264      */
265     public function getLogin()
266     {
267         $socialDrivers = $this->socialAuthService->getActiveDrivers();
268         $authMethod = config('auth.method');
269         return view('auth/login', ['socialDrivers' => $socialDrivers, 'authMethod' => $authMethod]);
270     }
271
272     /**
273      * Redirect to the relevant social site.
274      * @param $socialDriver
275      * @return \Symfony\Component\HttpFoundation\RedirectResponse
276      */
277     public function getSocialLogin($socialDriver)
278     {
279         session()->put('social-callback', 'login');
280         return $this->socialAuthService->startLogIn($socialDriver);
281     }
282
283     /**
284      * Redirect to the social site for authentication intended to register.
285      * @param $socialDriver
286      * @return mixed
287      */
288     public function socialRegister($socialDriver)
289     {
290         $this->checkRegistrationAllowed();
291         session()->put('social-callback', 'register');
292         return $this->socialAuthService->startRegister($socialDriver);
293     }
294
295     /**
296      * The callback for social login services.
297      * @param $socialDriver
298      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
299      * @throws SocialSignInException
300      */
301     public function socialCallback($socialDriver)
302     {
303         if (session()->has('social-callback')) {
304             $action = session()->pull('social-callback');
305             if ($action == 'login') {
306                 return $this->socialAuthService->handleLoginCallback($socialDriver);
307             } elseif ($action == 'register') {
308                 return $this->socialRegisterCallback($socialDriver);
309             }
310         } else {
311             throw new SocialSignInException('No action defined', '/login');
312         }
313         return redirect()->back();
314     }
315
316     /**
317      * Detach a social account from a user.
318      * @param $socialDriver
319      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
320      */
321     public function detachSocialAccount($socialDriver)
322     {
323         return $this->socialAuthService->detachSocialAccount($socialDriver);
324     }
325
326 }