]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Auth/AuthController.php
Got standard form-based registration working
[bookstack] / app / Http / Controllers / Auth / AuthController.php
1 <?php
2
3 namespace Oxbow\Http\Controllers\Auth;
4
5 use Illuminate\Http\Request;
6 use Oxbow\Exceptions\SocialSignInException;
7 use Oxbow\Exceptions\UserRegistrationException;
8 use Oxbow\Repos\UserRepo;
9 use Oxbow\Services\EmailConfirmationService;
10 use Oxbow\Services\Facades\Setting;
11 use Oxbow\Services\SocialAuthService;
12 use Oxbow\User;
13 use Validator;
14 use Oxbow\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 $loginPath = '/login';
34     protected $redirectPath = '/';
35     protected $redirectAfterLogout = '/login';
36
37     protected $socialAuthService;
38     protected $emailConfirmationService;
39     protected $userRepo;
40
41     /**
42      * Create a new authentication controller instance.
43      * @param SocialAuthService        $socialAuthService
44      * @param EmailConfirmationService $emailConfirmationService
45      * @param UserRepo                 $userRepo
46      */
47     public function __construct(SocialAuthService $socialAuthService, EmailConfirmationService $emailConfirmationService, UserRepo $userRepo)
48     {
49         $this->middleware('guest', ['only' => ['getLogin', 'postLogin', 'getRegister']]);
50         $this->socialAuthService = $socialAuthService;
51         $this->emailConfirmationService = $emailConfirmationService;
52         $this->userRepo = $userRepo;
53         parent::__construct();
54     }
55
56     /**
57      * Get a validator for an incoming registration request.
58      *
59      * @param  array $data
60      * @return \Illuminate\Contracts\Validation\Validator
61      */
62     protected function validator(array $data)
63     {
64         return Validator::make($data, [
65             'name'     => 'required|max:255',
66             'email'    => 'required|email|max:255|unique:users',
67             'password' => 'required|min:6',
68         ]);
69     }
70
71     /**
72      * Create a new user instance after a valid registration.
73      *
74      * @param  array $data
75      * @return User
76      */
77     protected function create(array $data)
78     {
79         return User::create([
80             'name'     => $data['name'],
81             'email'    => $data['email'],
82             'password' => bcrypt($data['password']),
83         ]);
84     }
85
86     protected function checkRegistrationAllowed()
87     {
88         if(!\Setting::get('registration-enabled')) {
89             throw new UserRegistrationException('Registrations are currently disabled.', '/login');
90         }
91     }
92
93     /**
94      * Show the application registration form.
95      *
96      * @return \Illuminate\Http\Response
97      */
98     public function getRegister()
99     {
100         $this->checkRegistrationAllowed();
101         $socialDrivers = $this->socialAuthService->getActiveDrivers();
102         return view('auth.register', ['socialDrivers' => $socialDrivers]);
103     }
104
105     /**
106      * Handle a registration request for the application.
107      *
108      * @param  \Illuminate\Http\Request $request
109      * @return \Illuminate\Http\Response
110      * @throws UserRegistrationException
111      */
112     public function postRegister(Request $request)
113     {
114         $this->checkRegistrationAllowed();
115         $validator = $this->validator($request->all());
116
117         if ($validator->fails()) {
118             $this->throwValidationException(
119                 $request, $validator
120             );
121         }
122
123         if(\Setting::get('registration-restrict')) {
124             $restrictedEmailDomains = explode(',', str_replace(' ', '', \Setting::get('registration-restrict')));
125             $userEmailDomain = $domain = substr(strrchr($request->get('email'), "@"), 1);
126             if(!in_array($userEmailDomain, $restrictedEmailDomains)) {
127                 throw new UserRegistrationException('That email domain does not have access to this application', '/register');
128             }
129         }
130
131         $newUser = $this->create($request->all());
132         $newUser->attachRoleId(\Setting::get('registration-role'), 1);
133
134         if(\Setting::get('registration-confirmation') || \Setting::get('registration-restrict')) {
135             $newUser->email_confirmed = false;
136             $newUser->save();
137             $this->emailConfirmationService->sendConfirmation($newUser);
138             return redirect('/register/confirm');
139         }
140
141         auth()->login($newUser);
142         return redirect($this->redirectPath());
143     }
144
145     /**
146      * Show the page to tell the user to check thier email
147      * and confirm their address.
148      */
149     public function getRegisterConfirmation()
150     {
151         return view('auth/register-confirm');
152     }
153
154     /**
155      * Confirms an email via a token and logs the user into the system.
156      * @param $token
157      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
158      * @throws UserRegistrationException
159      */
160     public function confirmEmail($token)
161     {
162         $confirmation = $this->emailConfirmationService->getEmailConfirmationFromToken($token);
163         $user = $confirmation->user;
164         $user->email_confirmed = true;
165         $user->save();
166         auth()->login($confirmation->user);
167         session()->flash('success', 'Your email has been confirmed!');
168         $this->emailConfirmationService->deleteConfirmationsByUser($user);
169         return redirect($this->redirectPath);
170     }
171
172     /**
173      * Shows a notice that a user's email address has not been confirmed,
174      * Also has the option to re-send the confirmation email.
175      * @return \Illuminate\View\View
176      */
177     public function showAwaitingConfirmation()
178     {
179         return view('auth/user-unconfirmed');
180     }
181
182     /**
183      * Resend the confirmation email
184      * @param Request $request
185      * @return \Illuminate\View\View
186      */
187     public function resendConfirmation(Request $request)
188     {
189         $this->validate($request, [
190             'email' => 'required|email|exists:users,email'
191         ]);
192         $user = $this->userRepo->getByEmail($request->get('email'));
193         $this->emailConfirmationService->sendConfirmation($user);
194         \Session::flash('success', 'Confirmation email resent, Please check your inbox.');
195         return redirect('/register/confirm');
196     }
197
198     /**
199      * Show the application login form.
200      *
201      * @return \Illuminate\Http\Response
202      */
203     public function getLogin()
204     {
205
206         if (view()->exists('auth.authenticate')) {
207             return view('auth.authenticate');
208         }
209
210         $socialDrivers = $this->socialAuthService->getActiveDrivers();
211         return view('auth.login', ['socialDrivers' => $socialDrivers]);
212     }
213
214     /**
215      * Redirect to the relevant social site.
216      * @param $socialDriver
217      * @return \Symfony\Component\HttpFoundation\RedirectResponse
218      */
219     public function getSocialLogin($socialDriver)
220     {
221         return $this->socialAuthService->startLogIn($socialDriver);
222     }
223
224     /**
225      * The callback for social login services.
226      *
227      * @param $socialDriver
228      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
229      * @throws SocialSignInException
230      */
231     public function socialCallback($socialDriver)
232     {
233         return $this->socialAuthService->handleCallback($socialDriver);
234     }
235
236     /**
237      * Detach a social account from a user.
238      * @param $socialDriver
239      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
240      */
241     public function detachSocialAccount($socialDriver)
242     {
243         return $this->socialAuthService->detachSocialAccount($socialDriver);
244     }
245
246 }