]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/RegistrationService.php
Fixed lack of oidc discovery filtering during testing
[bookstack] / app / Auth / Access / RegistrationService.php
1 <?php
2
3 namespace BookStack\Auth\Access;
4
5 use BookStack\Actions\ActivityType;
6 use BookStack\Auth\SocialAccount;
7 use BookStack\Auth\User;
8 use BookStack\Auth\UserRepo;
9 use BookStack\Exceptions\UserRegistrationException;
10 use BookStack\Facades\Activity;
11 use BookStack\Facades\Theme;
12 use BookStack\Theming\ThemeEvents;
13 use Exception;
14 use Illuminate\Support\Str;
15
16 class RegistrationService
17 {
18     protected $userRepo;
19     protected $emailConfirmationService;
20
21     /**
22      * RegistrationService constructor.
23      */
24     public function __construct(UserRepo $userRepo, EmailConfirmationService $emailConfirmationService)
25     {
26         $this->userRepo = $userRepo;
27         $this->emailConfirmationService = $emailConfirmationService;
28     }
29
30     /**
31      * Check whether or not registrations are allowed in the app settings.
32      *
33      * @throws UserRegistrationException
34      */
35     public function ensureRegistrationAllowed()
36     {
37         if (!$this->registrationAllowed()) {
38             throw new UserRegistrationException(trans('auth.registrations_disabled'), '/login');
39         }
40     }
41
42     /**
43      * Check if standard BookStack User registrations are currently allowed.
44      * Does not prevent external-auth based registration.
45      */
46     protected function registrationAllowed(): bool
47     {
48         $authMethod = config('auth.method');
49         $authMethodsWithRegistration = ['standard'];
50
51         return in_array($authMethod, $authMethodsWithRegistration) && setting('registration-enabled');
52     }
53
54     /**
55      * Attempt to find a user in the system otherwise register them as a new
56      * user. For use with external auth systems since password is auto-generated.
57      * @throws UserRegistrationException
58      */
59     public function findOrRegister(string $name, string $email, string $externalId): User
60     {
61         $user = User::query()
62             ->where('external_auth_id', '=', $externalId)
63             ->first();
64
65         if (is_null($user)) {
66             $userData = [
67                 'name'             => $name,
68                 'email'            => $email,
69                 'password'         => Str::random(32),
70                 'external_auth_id' => $externalId,
71             ];
72
73             $user = $this->registerUser($userData, null, false);
74         }
75
76         return $user;
77     }
78
79     /**
80      * The registrations flow for all users.
81      *
82      * @throws UserRegistrationException
83      */
84     public function registerUser(array $userData, ?SocialAccount $socialAccount = null, bool $emailConfirmed = false): User
85     {
86         $userEmail = $userData['email'];
87
88         // Email restriction
89         $this->ensureEmailDomainAllowed($userEmail);
90
91         // Ensure user does not already exist
92         $alreadyUser = !is_null($this->userRepo->getByEmail($userEmail));
93         if ($alreadyUser) {
94             throw new UserRegistrationException(trans('errors.error_user_exists_different_creds', ['email' => $userEmail]), '/login');
95         }
96
97         // Create the user
98         $newUser = $this->userRepo->registerNew($userData, $emailConfirmed);
99
100         // Assign social account if given
101         if ($socialAccount) {
102             $newUser->socialAccounts()->save($socialAccount);
103         }
104
105         Activity::add(ActivityType::AUTH_REGISTER, $socialAccount ?? $newUser);
106         Theme::dispatch(ThemeEvents::AUTH_REGISTER, $socialAccount ? $socialAccount->driver : auth()->getDefaultDriver(), $newUser);
107
108         // Start email confirmation flow if required
109         if ($this->emailConfirmationService->confirmationRequired() && !$emailConfirmed) {
110             $newUser->save();
111
112             try {
113                 $this->emailConfirmationService->sendConfirmation($newUser);
114                 session()->flash('sent-email-confirmation', true);
115             } catch (Exception $e) {
116                 $message = trans('auth.email_confirm_send_error');
117
118                 throw new UserRegistrationException($message, '/register/confirm');
119             }
120         }
121
122         return $newUser;
123     }
124
125     /**
126      * Ensure that the given email meets any active email domain registration restrictions.
127      * Throws if restrictions are active and the email does not match an allowed domain.
128      *
129      * @throws UserRegistrationException
130      */
131     protected function ensureEmailDomainAllowed(string $userEmail): void
132     {
133         $registrationRestrict = setting('registration-restrict');
134
135         if (!$registrationRestrict) {
136             return;
137         }
138
139         $restrictedEmailDomains = explode(',', str_replace(' ', '', $registrationRestrict));
140         $userEmailDomain = $domain = mb_substr(mb_strrchr($userEmail, '@'), 1);
141         if (!in_array($userEmailDomain, $restrictedEmailDomains)) {
142             $redirect = $this->registrationAllowed() ? '/register' : '/login';
143
144             throw new UserRegistrationException(trans('auth.registration_email_domain_invalid'), $redirect);
145         }
146     }
147 }