user_flow = $user_flow; } /** * Start the login flow for a user * * Redirects the user to the SSO service * * @return mixed */ public function login() { // TODO: Pass in 'previous' URL from session so we can redirect back // if we were redirected to login from a guard? return redirect($this->user_flow->getRedirectUrl(config('authkit.authn.openid.redirect_uri'), config('authkit.authn.scopes'))); } /** * Handle the response from the SSO service * * Exchange the code for a token and fetches basic user information. * Attempts to log the user into this app, and creates them if they * don't exist. Then redirects the user to the configured post_login url. * * @param Request $request * @return mixed */ public function callback(Request $request) { // Verify the passed in state value $this->user_flow->validateState($request->state); // TODO: Check for error response // Exchange the code for a token $oidc_token = $this->user_flow->exchangeCodeForToken($request->code, config('authkit.authn.openid.redirect_uri')); $user_info = $oidc_token->getUserInfo(); // Try and find a token for that user id $token = Token::where('id', $oidc_token->getUserId())->first(); // If that failed if (!isset($token)) { // No token for that user, either create them or migrate $register_event_result = event(new \authkit2\Events\UserRegistration($user_info)); $user = null; foreach ($register_event_result as $result) { if (is_object($result)) { $user = $result; } } if (!isset($user)) { // TODO: Log a useful error abort(500); } $token = new Token(); $token->id = $oidc_token->getUserId(); $token->access_token = $oidc_token->getAccessToken(); $token->refresh_token = $oidc_token->getRefreshToken(); $token->user_id = $user->{$user->getAuthIdentifierName()}; $token->save(); } \Auth::login($user); event(new \authkit2\Events\UserLogin($user, $user_info)); return redirect(url(config('authkit.authn.urls.post_login'))); } /** * Explicitly log out of this application and the SSO service * * @return mixed */ public function logout() { event(new \authkit2\Events\UserLogout(\Auth::user())); // Log out locally \Auth::logout(); // Redirect to log out remotely as well return redirect($this->user_flow->getLogoutUrl(url(config('authkit.authn.urls.post_logout')))); } }