request_id = $this->getRequestId(); } public function signin() { $this->sessionLogging($this->request_id, ['session' => session()->all()], 'authCallback:Initiated'); // Initialize the OAuth client $oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([ 'clientId' => config('azure.appId'), 'clientSecret' => config('azure.appSecret'), 'redirectUri' => config('azure.redirectUri'), 'urlAuthorize' => config('azure.authority').config('azure.authorizeEndpoint'), 'urlAccessToken' => config('azure.authority').config('azure.tokenEndpoint'), 'urlResourceOwnerDetails' => '', 'scopes' => config('azure.scopes') ]); $authUrl = $oauthClient->getAuthorizationUrl(); $oauthState = $oauthClient->getState(); $this->sessionLogging($this->request_id, ['authUrl' => $authUrl], 'authCallback:Got the oauthState', $oauthState); // Save client state so we can validate in callback session(['oauthState' => $oauthState]); // Redirect to AAD signin page return redirect()->away($authUrl); } public function getOauthStateToken($providedState){ $this->sessionLogging($this->request_id, [], 'authCallback:authState Not Found - checking getOauthStateToken from session'); $sessionLog = DB::table('session_logging')->where('oauthState', $providedState)->first(['id']); if (isset($sessionLog->id)){ return $providedState; } return false; } public function callback(Request $request) { // Validate state $expectedState = session('oauthState'); $request->session()->forget('oauthState'); $providedState = $request->query('state'); //$this->sessionLogging($this->request_id, ['request' => $request->all(), 'session' => $request->session()->all()], 'authCallback:Received'); if (!isset($expectedState)) { //$this->sessionLogging($this->request_id, [], 'authCallback:State Error, Init Not found checking alternative'); //Check from temp token if ($expectedStateToken = $this->getOauthStateToken($providedState)){ //$this->sessionLogging($this->request_id, ['expectedStateToken' => $expectedStateToken], 'authCallback:authState oauthState Found- oauthState updated'); $expectedState = $expectedStateToken; }else { // If there is no expected state in the session, // do nothing and redirect to the home page. //$this->sessionLogging($this->request_id, ['status' => 'Failed', 'request' => $request->all()], 'authCallback:State Error, Redirected to /'); return redirect('/'); } } if (!isset($providedState) || $expectedState != $providedState) { //$this->sessionLogging($this->request_id, ['status' => 'Failed', 'request' => $request->all()], 'authCallback:expectedState and providedState is not matching, Redirected to /'); return redirect('/') ->with('error', 'Invalid auth state') ->with('errorDetail', 'The provided auth state did not match the expected value'); } // Authorization code should be in the "code" query param $authCode = $request->query('code'); if (isset($authCode)) { // Initialize the OAuth client $oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([ 'clientId' => config('azure.appId'), 'clientSecret' => config('azure.appSecret'), 'redirectUri' => config('azure.redirectUri'), 'urlAuthorize' => config('azure.authority').config('azure.authorizeEndpoint'), 'urlAccessToken' => config('azure.authority').config('azure.tokenEndpoint'), 'urlResourceOwnerDetails' => '', 'scopes' => config('azure.scopes') ]); try { // Make the token request $accessToken = $oauthClient->getAccessToken('authorization_code', [ 'code' => $authCode ]); //$this->sessionLogging($this->request_id, ['accessToken' => $accessToken], 'authCallback:access Token Received.'); $graph = new Graph(); $graph->setAccessToken($accessToken->getToken()); $user = $graph->createRequest('GET', '/me?$select=displayName,mail,mailboxSettings,userPrincipalName') ->setReturnType(Model\User::class) ->execute(); //$this->sessionLogging($this->request_id, ['user' => $user->getMail()], 'authCallback:user Check Done.'); $refreshToken = $accessToken->getRefreshToken(); $expires = $accessToken->getExpires(); $tokenCache = new TokenCache(); $tokenCache->storeTokens($accessToken, $user); $request->merge(['accessToken' => $accessToken, 'refreshToken' => $refreshToken]); //$this->sessionLogging($this->request_id, ['user' => $user->getMail(), 'refreshToken' => $refreshToken], 'authCallback:logging into the system'); if ($user && $user->getMail()) { $email = $user->getMail(); if (strpos($email, '@creditfair.in') !== false || strpos($email, '@kmglobal.in') !== false || strpos($email, '@babyready.app') !== false) { $userData = User::where('email', $user->getMail())->where('user_type', '>=', 5)->whereNull('deleted_at')->first(['id']); if (isset($userData->id)) { /*$hashids = new Hashids('Creditfair by CS', 20); $hashid = $hashids->encode($userData->id); $hashidTime = $hashids->encode(Carbon::now()->addSecond(30)->timestamp); User::where('id', $userData->id)->where('user_type', '>=', 5)->update(['admin_login_counter' => 0, 'access_token' => $request->get('accessToken'), 'refreshToken' => $request->get('refreshToken')]); return \redirect('/admin/authenticating_user')->with('ckn', $hashid . '|' . $hashidTime);*/ //return view('login_m', ['user' => wall_encrypt($user->getMail()), 'refreshToken' => $refreshToken, 'providedState' => $providedState, 'expectedState' => $expectedState, 'tkn' => '/admin/otp/login/?cknt=' . csrf_token() . '&ckn=' . $hashid . '|' . $hashidTime]); } } } $session = $this->loginUser($request, $user); //$this->sessionLogging($this->request_id, ['Status' => 'Success', 'user' => $user->getMail(), 'userLoginInfo' => json_encode($session), 'redirectInfo' => $this->getRedirectInfo($session)], 'authCallback:user logging info'); return $session; } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) { //$this->sessionLogging($this->request_id, ['status' => 'Failed', 'error' => $e->getResponseBody(), 'message' => $e->getMessage(), 'Line' => $e->getLine()], 'authCallback:Error requesting access token, Redirected to /'); return redirect('/') ->with('error', 'Error requesting access token') ->with('errorDetail', json_encode($e->getResponseBody())); } } $this->sessionLogging($this->request_id, ['status' => 'Failed', 'error' => $request->query('error'), 'error_description' => $request->query('error_description')], 'authCallback:Error not auth code found, Redirected to /'); return redirect('/') ->with('error', $request->query('error')) ->with('errorDetail', $request->query('error_description')); } public function getAccessToken($user_id){ try { if((class_exists(\League\OAuth2\Client\Provider\GenericProvider::class))){ //User::where('id', 27)->whereNotNull('access_token')->first(['access_token']); $user = User::where('id', $user_id)->first(['refreshToken']); if (isset($user->refreshToken) && $user->refreshToken) { $oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([ 'clientId' => config('azure.appId'), 'clientSecret' => config('azure.appSecret'), 'redirectUri' => config('azure.redirectUri'), 'urlAuthorize' => config('azure.authority') . config('azure.authorizeEndpoint'), 'urlAccessToken' => config('azure.authority') . config('azure.tokenEndpoint'), 'urlResourceOwnerDetails' => '', 'scopes' => config('azure.scopes') ]); $accessToken = $oauthClient->getAccessToken('refresh_token', [ 'refresh_token' => $user->refreshToken ]); //$access_token = $accessToken->getToken(); //$this->sendCWNotifWithData('Slack Message Alert', ['accessToken' => $accessToken->getToken(), 'refresh_token' => $user->refreshToken]); return $accessToken->getToken() ?? ''; } }else{ //$this->sendCWNotifWithData('Slack Message Alert - OAuth2 404', ['Token' => 'Token Missing']); } return ''; }catch (\Exception $e){ //$this->sendCWNotifWithData('Slack Message Alert', ['exception' => $e->getMessage(), 'file' => "microsoft auth controller"]); return ''; } } public function sendCWNotifWithData($message, $data){ $cwFactory = new CloudWatchLoggerFactory(); $_title = array('message' => $message); $_data = array_merge($_title, $data); $cwFactory->logger(json_encode($_data)); } public function signout() { $tokenCache = new TokenCache(); $tokenCache->clearTokens(); return redirect('/'); } private function loginUser(Request $request, $user){ try { $login = new LoginController($request); //$user = Socialite::driver('google')->user(); if ($user && $user->getMail()) { $email = $user->getMail(); //$authEmailArray = ['Sharmabhaskar21@gmail.com','Poojaaagarwal1998@gmail.com']; if (strpos($email, '@creditfair.in') !== false || strpos($email, '@kmglobal.in') !== false || strpos($email, '@babyready.app') !== false) { $userData = User::where('email', $user->getMail())->where('user_type', '>=', 5)->whereNull('deleted_at')->first(); if (isset($userData->id)) { if ($userData->id == 27){ $userUpdate = User::find($userData->id); $userUpdate->google_token = isset($user->id) ? $user->id : ''; //$userUpdate->access_token = $request->get('accessToken'); $userUpdate->refreshToken = $request->get('refreshToken'); $userUpdate->save(); } //$refreshToken = $user->refreshToken; // not always provided //$expiresIn = $user->expiresIn; //$token = $user->token; //$tokenSecret = $user->tokenSecret; if (isset($user->_propDict)) { if (array_key_exists("id", $user->_propDict)) { $user_id = $this->_propDict["id"] ?? ''; } } \Session::put(['gData' => [ 'id' => $user_id ?? '', 'nick_name' => $user->getMailNickname(), 'name' => $user->getDisplayName(), 'avatar' => $user->getPhoto()]] ); if (Auth::loginUsingId($userData->id)) { $login->rememberSession($userData); session(['session_key_debug' => time()]); session()->save(); usleep(500000); //0.5 seconds delay if ($login->loadPermissions()) { $data = Session::get('permissionsLinks'); if(!isset($data['admin'])){ foreach ($data as $key => $item){ if($item && !(strpos($key, '}') !== false)){ return redirect()->to($key); } } }else{ return redirect()->intended('admin'); } } } else { \Session::flash('error', 'Incorrect username or password. Please try again...'); return redirect()->to('admin\login')->withInput(); } } } } }catch (\Exception $e){ $url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"; return Redirect::to(str_replace('https://','https://www.',$url)); } \Session::flash('error','Incorrect username or password. Please try again.'); return redirect()->to('admin\login')->withInput(); //$user = Socialite::driver('google')->userFromToken($token); } public function sessionLogging($request_id, $data, $action, $oauthState = ''){ /*DB::table('session_logging')->insert( [ 'request_id' => $request_id, 'action' => $action, 'session' => json_encode($data), 'oauthState' => $oauthState, 'created_at' => Carbon::now()->toDateString() ] );*/ } private function getRedirectInfo($session){ $targetUrl = $session->getTargetUrl(); return ['targetUrl' => $targetUrl, 'session' => session()->all()]; } private function getRequestId(){ $v = new VendorIntegrationController(new Request()); return $v->guidv4(); } }