]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/RegistrationService.php
Moved socal auth routes to their own controller
[bookstack] / app / Auth / Access / RegistrationService.php
1 <?php namespace BookStack\Auth\Access;
2
3 use BookStack\Auth\SocialAccount;
4 use BookStack\Auth\UserRepo;
5 use BookStack\Exceptions\UserRegistrationException;
6 use Exception;
7
8 class RegistrationService
9 {
10
11     protected $userRepo;
12     protected $emailConfirmationService;
13
14     /**
15      * RegistrationService constructor.
16      */
17     public function __construct(UserRepo $userRepo, EmailConfirmationService $emailConfirmationService)
18     {
19         $this->userRepo = $userRepo;
20         $this->emailConfirmationService = $emailConfirmationService;
21     }
22
23
24     /**
25      * Check whether or not registrations are allowed in the app settings.
26      * @throws UserRegistrationException
27      */
28     public function checkRegistrationAllowed()
29     {
30         if (!setting('registration-enabled') || config('auth.method') === 'ldap') {
31             throw new UserRegistrationException(trans('auth.registrations_disabled'), '/login');
32         }
33     }
34
35     /**
36      * The registrations flow for all users.
37      * @throws UserRegistrationException
38      */
39     public function registerUser(array $userData, ?SocialAccount $socialAccount = null, bool $emailVerified = false)
40     {
41         $registrationRestrict = setting('registration-restrict');
42
43         if ($registrationRestrict) {
44             $restrictedEmailDomains = explode(',', str_replace(' ', '', $registrationRestrict));
45             $userEmailDomain = $domain = mb_substr(mb_strrchr($userData['email'], "@"), 1);
46             if (!in_array($userEmailDomain, $restrictedEmailDomains)) {
47                 throw new UserRegistrationException(trans('auth.registration_email_domain_invalid'), '/register');
48             }
49         }
50
51         $newUser = $this->userRepo->registerNew($userData, $emailVerified);
52
53         if ($socialAccount) {
54             $newUser->socialAccounts()->save($socialAccount);
55         }
56
57         if ($this->emailConfirmationService->confirmationRequired() && !$emailVerified) {
58             $newUser->save();
59             $message = '';
60
61             try {
62                 $this->emailConfirmationService->sendConfirmation($newUser);
63             } catch (Exception $e) {
64                 $message = trans('auth.email_confirm_send_error');
65             }
66
67             throw new UserRegistrationException($message, '/register/confirm');
68         }
69
70         auth()->login($newUser);
71     }
72
73 }