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