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