]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/RegisterController.php
Set /app PHP code to PSR-2 standard
[bookstack] / app / Http / Controllers / Auth / RegisterController.php
1 <?php
2
3 namespace BookStack\Http\Controllers\Auth;
4
5 use BookStack\Exceptions\ConfirmationEmailException;
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 BookStack\User;
13 use Exception;
14 use Illuminate\Http\Request;
15 use Illuminate\Http\Response;
16 use Validator;
17 use BookStack\Http\Controllers\Controller;
18 use Illuminate\Foundation\Auth\RegistersUsers;
19
20 class RegisterController extends Controller
21 {
22     /*
23     |--------------------------------------------------------------------------
24     | Register Controller
25     |--------------------------------------------------------------------------
26     |
27     | This controller handles the registration of new users as well as their
28     | validation and creation. By default this controller uses a trait to
29     | provide this functionality without requiring any additional code.
30     |
31     */
32
33     use RegistersUsers;
34
35     protected $socialAuthService;
36     protected $emailConfirmationService;
37     protected $userRepo;
38
39     /**
40      * Where to redirect users after login / registration.
41      *
42      * @var string
43      */
44     protected $redirectTo = '/';
45     protected $redirectPath = '/';
46
47     /**
48      * Create a new controller instance.
49      *
50      * @param SocialAuthService $socialAuthService
51      * @param EmailConfirmationService $emailConfirmationService
52      * @param UserRepo $userRepo
53      */
54     public function __construct(SocialAuthService $socialAuthService, EmailConfirmationService $emailConfirmationService, UserRepo $userRepo)
55     {
56         $this->middleware('guest')->only(['getRegister', 'postRegister', 'socialRegister']);
57         $this->socialAuthService = $socialAuthService;
58         $this->emailConfirmationService = $emailConfirmationService;
59         $this->userRepo = $userRepo;
60         $this->redirectTo = baseUrl('/');
61         $this->redirectPath = baseUrl('/');
62         parent::__construct();
63     }
64
65     /**
66      * Get a validator for an incoming registration request.
67      *
68      * @param  array $data
69      * @return \Illuminate\Contracts\Validation\Validator
70      */
71     protected function validator(array $data)
72     {
73         return Validator::make($data, [
74             'name' => 'required|max:255',
75             'email' => 'required|email|max:255|unique:users',
76             'password' => 'required|min:6',
77         ]);
78     }
79
80     /**
81      * Check whether or not registrations are allowed in the app settings.
82      * @throws UserRegistrationException
83      */
84     protected function checkRegistrationAllowed()
85     {
86         if (!setting('registration-enabled')) {
87             throw new UserRegistrationException(trans('auth.registrations_disabled'), '/login');
88         }
89     }
90
91     /**
92      * Show the application registration form.
93      * @return Response
94      */
95     public function getRegister()
96     {
97         $this->checkRegistrationAllowed();
98         $socialDrivers = $this->socialAuthService->getActiveDrivers();
99         return view('auth.register', ['socialDrivers' => $socialDrivers]);
100     }
101
102     /**
103      * Handle a registration request for the application.
104      * @param Request|\Illuminate\Http\Request $request
105      * @return Response
106      * @throws UserRegistrationException
107      * @throws \Illuminate\Validation\ValidationException
108      */
109     public function postRegister(Request $request)
110     {
111         $this->checkRegistrationAllowed();
112         $validator = $this->validator($request->all());
113
114         if ($validator->fails()) {
115             $this->throwValidationException(
116                 $request,
117                 $validator
118             );
119         }
120
121         $userData = $request->all();
122         return $this->registerUser($userData);
123     }
124
125     /**
126      * Create a new user instance after a valid registration.
127      * @param  array  $data
128      * @return User
129      */
130     protected function create(array $data)
131     {
132         return User::create([
133             'name' => $data['name'],
134             'email' => $data['email'],
135             'password' => bcrypt($data['password']),
136         ]);
137     }
138
139     /**
140      * The registrations flow for all users.
141      * @param array $userData
142      * @param bool|false|SocialAccount $socialAccount
143      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
144      * @throws UserRegistrationException
145      * @throws ConfirmationEmailException
146      */
147     protected function registerUser(array $userData, $socialAccount = false)
148     {
149         if (setting('registration-restrict')) {
150             $restrictedEmailDomains = explode(',', str_replace(' ', '', setting('registration-restrict')));
151             $userEmailDomain = $domain = substr(strrchr($userData['email'], "@"), 1);
152             if (!in_array($userEmailDomain, $restrictedEmailDomains)) {
153                 throw new UserRegistrationException(trans('auth.registration_email_domain_invalid'), '/register');
154             }
155         }
156
157         $newUser = $this->userRepo->registerNew($userData);
158         if ($socialAccount) {
159             $newUser->socialAccounts()->save($socialAccount);
160         }
161
162         if (setting('registration-confirmation') || setting('registration-restrict')) {
163             $newUser->save();
164
165             try {
166                 $this->emailConfirmationService->sendConfirmation($newUser);
167             } catch (Exception $e) {
168                 session()->flash('error', trans('auth.email_confirm_send_error'));
169             }
170
171             return redirect('/register/confirm');
172         }
173
174         auth()->login($newUser);
175         session()->flash('success', trans('auth.register_success'));
176         return redirect($this->redirectPath());
177     }
178
179     /**
180      * Show the page to tell the user to check their email
181      * and confirm their address.
182      */
183     public function getRegisterConfirmation()
184     {
185         return view('auth/register-confirm');
186     }
187
188     /**
189      * Confirms an email via a token and logs the user into the system.
190      * @param $token
191      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
192      * @throws UserRegistrationException
193      */
194     public function confirmEmail($token)
195     {
196         $confirmation = $this->emailConfirmationService->getEmailConfirmationFromToken($token);
197         $user = $confirmation->user;
198         $user->email_confirmed = true;
199         $user->save();
200         auth()->login($user);
201         session()->flash('success', trans('auth.email_confirm_success'));
202         $this->emailConfirmationService->deleteConfirmationsByUser($user);
203         return redirect($this->redirectPath);
204     }
205
206     /**
207      * Shows a notice that a user's email address has not been confirmed,
208      * Also has the option to re-send the confirmation email.
209      * @return \Illuminate\View\View
210      */
211     public function showAwaitingConfirmation()
212     {
213         return view('auth/user-unconfirmed');
214     }
215
216     /**
217      * Resend the confirmation email
218      * @param Request $request
219      * @return \Illuminate\View\View
220      */
221     public function resendConfirmation(Request $request)
222     {
223         $this->validate($request, [
224             'email' => 'required|email|exists:users,email'
225         ]);
226         $user = $this->userRepo->getByEmail($request->get('email'));
227
228         try {
229             $this->emailConfirmationService->sendConfirmation($user);
230         } catch (Exception $e) {
231             session()->flash('error', trans('auth.email_confirm_send_error'));
232             return redirect('/register/confirm');
233         }
234
235         session()->flash('success', trans('auth.email_confirm_resent'));
236         return redirect('/register/confirm');
237     }
238
239     /**
240      * Redirect to the social site for authentication intended to register.
241      * @param $socialDriver
242      * @return mixed
243      */
244     public function socialRegister($socialDriver)
245     {
246         $this->checkRegistrationAllowed();
247         session()->put('social-callback', 'register');
248         return $this->socialAuthService->startRegister($socialDriver);
249     }
250
251     /**
252      * The callback for social login services.
253      * @param $socialDriver
254      * @param Request $request
255      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
256      * @throws SocialSignInException
257      * @throws UserRegistrationException
258      * @throws \BookStack\Exceptions\SocialDriverNotConfigured
259      * @throws ConfirmationEmailException
260      */
261     public function socialCallback($socialDriver, Request $request)
262     {
263         if (!session()->has('social-callback')) {
264             throw new SocialSignInException(trans('errors.social_no_action_defined'), '/login');
265         }
266
267         // Check request for error information
268         if ($request->has('error') && $request->has('error_description')) {
269             throw new SocialSignInException(trans('errors.social_login_bad_response', [
270                 'socialAccount' => $socialDriver,
271                 'error' => $request->get('error_description'),
272             ]), '/login');
273         }
274
275         $action = session()->pull('social-callback');
276         if ($action == 'login') {
277             return $this->socialAuthService->handleLoginCallback($socialDriver);
278         }
279         if ($action == 'register') {
280             return $this->socialRegisterCallback($socialDriver);
281         }
282         return redirect()->back();
283     }
284
285     /**
286      * Detach a social account from a user.
287      * @param $socialDriver
288      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
289      */
290     public function detachSocialAccount($socialDriver)
291     {
292         return $this->socialAuthService->detachSocialAccount($socialDriver);
293     }
294
295     /**
296      * Register a new user after a registration callback.
297      * @param $socialDriver
298      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
299      * @throws ConfirmationEmailException
300      * @throws UserRegistrationException
301      * @throws \BookStack\Exceptions\SocialDriverNotConfigured
302      */
303     protected function socialRegisterCallback($socialDriver)
304     {
305         $socialUser = $this->socialAuthService->handleRegistrationCallback($socialDriver);
306         $socialAccount = $this->socialAuthService->fillSocialAccount($socialDriver, $socialUser);
307
308         // Create an array of the user data to create a new user instance
309         $userData = [
310             'name' => $socialUser->getName(),
311             'email' => $socialUser->getEmail(),
312             'password' => str_random(30)
313         ];
314         return $this->registerUser($userData, $socialAccount);
315     }
316 }