+ protected array $config;
+ protected RegistrationService $registrationService;
+ protected LoginService $loginService;
+ protected GroupSyncService $groupSyncService;
+
+ public function __construct(
+ RegistrationService $registrationService,
+ LoginService $loginService,
+ GroupSyncService $groupSyncService
+ ) {
+ $this->config = config('saml2');
+ $this->registrationService = $registrationService;
+ $this->loginService = $loginService;
+ $this->groupSyncService = $groupSyncService;
+ }
+
+ /**
+ * Initiate a login flow.
+ *
+ * @throws Error
+ */
+ public function login(): array
+ {
+ $toolKit = $this->getToolkit();
+ $returnRoute = url('/saml2/acs');
+
+ return [
+ 'url' => $toolKit->login($returnRoute, [], false, false, true),
+ 'id' => $toolKit->getLastRequestID(),
+ ];
+ }
+
+ /**
+ * Initiate a logout flow.
+ *
+ * @throws Error
+ */
+ public function logout(User $user): array
+ {
+ $toolKit = $this->getToolkit();
+ $returnRoute = url('/');
+
+ try {
+ $url = $toolKit->logout(
+ $returnRoute,
+ [],
+ $user->email,
+ null,
+ true,
+ Constants::NAMEID_EMAIL_ADDRESS
+ );
+ $id = $toolKit->getLastRequestID();
+ } catch (Error $error) {
+ if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
+ throw $error;
+ }
+
+ $this->actionLogout();
+ $url = '/';
+ $id = null;
+ }
+
+ return ['url' => $url, 'id' => $id];
+ }
+
+ /**
+ * Process the ACS response from the idp and return the
+ * matching, or new if registration active, user matched to the idp.
+ * Returns null if not authenticated.
+ *
+ * @throws Error
+ * @throws SamlException
+ * @throws ValidationError
+ * @throws JsonDebugException
+ * @throws UserRegistrationException
+ */
+ public function processAcsResponse(?string $requestId, string $samlResponse): ?User
+ {
+ // The SAML2 toolkit expects the response to be within the $_POST superglobal
+ // so we need to manually put it back there at this point.
+ $_POST['SAMLResponse'] = $samlResponse;
+ $toolkit = $this->getToolkit();
+ $toolkit->processResponse($requestId);
+ $errors = $toolkit->getErrors();
+
+ if (!empty($errors)) {
+ $reason = $toolkit->getLastErrorReason();
+ $message = 'Invalid ACS Response; Errors: ' . implode(', ', $errors);
+ $message .= $reason ? "; Reason: {$reason}" : '';
+ throw new Error($message);
+ }
+
+ if (!$toolkit->isAuthenticated()) {
+ return null;
+ }
+
+ $attrs = $toolkit->getAttributes();
+ $id = $toolkit->getNameId();
+
+ return $this->processLoginCallback($id, $attrs);
+ }