]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/AuthController.php
Added tests for confirmed registration
[bookstack] / app / Http / Controllers / Auth / AuthController.php
1 <?php
2
3 namespace BookStack\Http\Controllers\Auth;
4
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 $loginPath = '/login';
33     protected $redirectPath = '/';
34     protected $redirectAfterLogout = '/login';
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         parent::__construct();
53     }
54
55     /**
56      * Get a validator for an incoming registration request.
57      * @param  array $data
58      * @return \Illuminate\Contracts\Validation\Validator
59      */
60     protected function validator(array $data)
61     {
62         return Validator::make($data, [
63             'name'     => 'required|max:255',
64             'email'    => 'required|email|max:255|unique:users',
65             'password' => 'required|min:6',
66         ]);
67     }
68
69     protected function checkRegistrationAllowed()
70     {
71         if (!\Setting::get('registration-enabled')) {
72             throw new UserRegistrationException('Registrations are currently disabled.', '/login');
73         }
74     }
75
76     /**
77      * Show the application registration form.
78      * @return \Illuminate\Http\Response
79      */
80     public function getRegister()
81     {
82         $this->checkRegistrationAllowed();
83         $socialDrivers = $this->socialAuthService->getActiveDrivers();
84         return view('auth.register', ['socialDrivers' => $socialDrivers]);
85     }
86
87     /**
88      * Handle a registration request for the application.
89      * @param  \Illuminate\Http\Request $request
90      * @return \Illuminate\Http\Response
91      * @throws UserRegistrationException
92      */
93     public function postRegister(Request $request)
94     {
95         $this->checkRegistrationAllowed();
96         $validator = $this->validator($request->all());
97
98         if ($validator->fails()) {
99             $this->throwValidationException(
100                 $request, $validator
101             );
102         }
103
104         $userData = $request->all();
105         return $this->registerUser($userData);
106     }
107
108     /**
109      * Register a new user after a registration callback.
110      * @param $socialDriver
111      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
112      * @throws UserRegistrationException
113      */
114     protected function socialRegisterCallback($socialDriver)
115     {
116         $socialUser = $this->socialAuthService->handleRegistrationCallback($socialDriver);
117         $socialAccount = $this->socialAuthService->fillSocialAccount($socialDriver, $socialUser);
118
119         // Create an array of the user data to create a new user instance
120         $userData = [
121             'name'     => $socialUser->getName(),
122             'email'    => $socialUser->getEmail(),
123             'password' => str_random(30)
124         ];
125         return $this->registerUser($userData, $socialAccount);
126     }
127
128     /**
129      * The registrations flow for all users.
130      * @param array                    $userData
131      * @param bool|false|SocialAccount $socialAccount
132      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
133      * @throws UserRegistrationException
134      * @throws \BookStack\Exceptions\ConfirmationEmailException
135      */
136     protected function registerUser(array $userData, $socialAccount = false)
137     {
138         if (\Setting::get('registration-restrict')) {
139             $restrictedEmailDomains = explode(',', str_replace(' ', '', \Setting::get('registration-restrict')));
140             $userEmailDomain = $domain = substr(strrchr($userData['email'], "@"), 1);
141             if (!in_array($userEmailDomain, $restrictedEmailDomains)) {
142                 throw new UserRegistrationException('That email domain does not have access to this application', '/register');
143             }
144         }
145
146         $newUser = $this->userRepo->registerNew($userData);
147         if ($socialAccount) {
148             $newUser->socialAccounts()->save($socialAccount);
149         }
150
151         if (\Setting::get('registration-confirmation') || \Setting::get('registration-restrict')) {
152             $newUser->email_confirmed = false;
153             $newUser->save();
154             $this->emailConfirmationService->sendConfirmation($newUser);
155             return redirect('/register/confirm');
156         }
157
158         $newUser->email_confirmed = true;
159         auth()->login($newUser);
160         session()->flash('success', 'Thanks for signing up! You are now registered and signed in.');
161         return redirect($this->redirectPath());
162     }
163
164     /**
165      * Show the page to tell the user to check thier email
166      * and confirm their address.
167      */
168     public function getRegisterConfirmation()
169     {
170         return view('auth/register-confirm');
171     }
172
173     /**
174      * View the confirmation email as a standard web page.
175      * @param $token
176      * @return \Illuminate\View\View
177      * @throws UserRegistrationException
178      */
179     public function viewConfirmEmail($token)
180     {
181         $confirmation = $this->emailConfirmationService->getEmailConfirmationFromToken($token);
182         return view('emails/email-confirmation', ['token' => $confirmation->token]);
183     }
184
185     /**
186      * Confirms an email via a token and logs the user into the system.
187      * @param $token
188      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
189      * @throws UserRegistrationException
190      */
191     public function confirmEmail($token)
192     {
193         $confirmation = $this->emailConfirmationService->getEmailConfirmationFromToken($token);
194         $user = $confirmation->user;
195         $user->email_confirmed = true;
196         $user->save();
197         auth()->login($confirmation->user);
198         session()->flash('success', 'Your email has been confirmed!');
199         $this->emailConfirmationService->deleteConfirmationsByUser($user);
200         return redirect($this->redirectPath);
201     }
202
203     /**
204      * Shows a notice that a user's email address has not been confirmed,
205      * Also has the option to re-send the confirmation email.
206      * @return \Illuminate\View\View
207      */
208     public function showAwaitingConfirmation()
209     {
210         return view('auth/user-unconfirmed');
211     }
212
213     /**
214      * Resend the confirmation email
215      * @param Request $request
216      * @return \Illuminate\View\View
217      */
218     public function resendConfirmation(Request $request)
219     {
220         $this->validate($request, [
221             'email' => 'required|email|exists:users,email'
222         ]);
223         $user = $this->userRepo->getByEmail($request->get('email'));
224         $this->emailConfirmationService->sendConfirmation($user);
225         \Session::flash('success', 'Confirmation email resent, Please check your inbox.');
226         return redirect('/register/confirm');
227     }
228
229     /**
230      * Show the application login form.
231      * @return \Illuminate\Http\Response
232      */
233     public function getLogin()
234     {
235
236         if (view()->exists('auth.authenticate')) {
237             return view('auth.authenticate');
238         }
239
240         $socialDrivers = $this->socialAuthService->getActiveDrivers();
241         return view('auth.login', ['socialDrivers' => $socialDrivers]);
242     }
243
244     /**
245      * Redirect to the relevant social site.
246      * @param $socialDriver
247      * @return \Symfony\Component\HttpFoundation\RedirectResponse
248      */
249     public function getSocialLogin($socialDriver)
250     {
251         session()->put('social-callback', 'login');
252         return $this->socialAuthService->startLogIn($socialDriver);
253     }
254
255     /**
256      * Redirect to the social site for authentication initended to register.
257      * @param $socialDriver
258      * @return mixed
259      */
260     public function socialRegister($socialDriver)
261     {
262         $this->checkRegistrationAllowed();
263         session()->put('social-callback', 'register');
264         return $this->socialAuthService->startRegister($socialDriver);
265     }
266
267     /**
268      * The callback for social login services.
269      * @param $socialDriver
270      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
271      * @throws SocialSignInException
272      */
273     public function socialCallback($socialDriver)
274     {
275         if (session()->has('social-callback')) {
276             $action = session()->pull('social-callback');
277             if ($action == 'login') {
278                 return $this->socialAuthService->handleLoginCallback($socialDriver);
279             } elseif ($action == 'register') {
280                 return $this->socialRegisterCallback($socialDriver);
281             }
282         } else {
283             throw new SocialSignInException('No action defined', '/login');
284         }
285         return redirect()->back();
286     }
287
288     /**
289      * Detach a social account from a user.
290      * @param $socialDriver
291      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
292      */
293     public function detachSocialAccount($socialDriver)
294     {
295         return $this->socialAuthService->detachSocialAccount($socialDriver);
296     }
297
298 }