public function loadUserByOAuthUserResponse(UserResponseInterface $response) { # $username = $response->getUsername(); # var_dump($username);exit; $username = $response->getResponse()["username"]; var_dump($username); $user = $this->userManager->findUserBy(array('username' => $username)); //when the user is registrating if (null === $user) { $service = $response->getResourceOwner()->getName(); $setter = 'set' . ucfirst($service); $setter_id = $setter . 'Id'; $setter_token = $setter . 'AccessToken'; // create new user here $user = $this->userManager->createUser(); $user->{$setter_id}($username); $user->{$setter_token}($response->getAccessToken()); //I have set all requested data with the user's username //modify here with relevant data $user->setUsername($username); # $user->setNickname($response->getNickName()); $user->setEmail($username . '@yoursite.com'); $user->setPassword($username); # $user->setPath($response->getProfilePicture()); $user->setEnabled(true); $this->userManager->updateUser($user); return $user; } //if user exists - go with the HWIOAuth way $serviceName = $response->getResourceOwner()->getName(); $setter = 'set' . ucfirst($serviceName) . 'AccessToken'; //update access token $user->{$setter}($response->getAccessToken()); return $user; }
public function handleResponse(UserResponseInterface $response, UserService $userService) { $fields = $response->getResponse(); $gitHubLogin = $fields['login']; $accessToken = $response->getAccessToken(); $user = $userService->findByGitHubLogin($gitHubLogin); if (null === $user) { throw new UsernameNotFoundException(); } $oAuthUser = new OAuthUser($user); $oAuthUser->addRole('ROLE_GITHUB_USER'); $oAuthUser->setAccessToken($accessToken); if (array_key_exists('name', $fields)) { $gitHubName = $fields['name']; $oAuthUser->setRealName($gitHubName); } else { $oAuthUser->setRealName($gitHubLogin); } $client = new Client(); $client->setOption('api_version', 'v3'); $client->authenticate($response->getAccessToken(), Client::AUTH_HTTP_TOKEN); /* @var \Github\Api\CurrentUser $currentUserApi */ $currentUserApi = $client->api('current_user'); $emails = $currentUserApi->emails(); $allEMails = $emails->all(); $oAuthUser->setEmail($this->getPrimaryEmailAddress($allEMails)); return $oAuthUser; }
/** * {@inheritdoc} */ public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $username = $response->getUsername(); $useremail = $response->getEmail(); // get facebook email id $user = $this->userManager->findUserByEmail($useremail); //$user = $this->userManager->findUserBy(array($this->getProperty($response) => $useremail)); //when the user is registrating if (null === $user) { $service = $response->getResourceOwner()->getName(); $setter = 'set' . ucfirst($service); $setter_id = $setter . 'Id'; $setter_token = $setter . 'AccessToken'; // create new user here $user = $this->userManager->createUser(); $user->{$setter_id}($username); $user->{$setter_token}($response->getAccessToken()); $user->setUsername($useremail); $user->setEmail($useremail); $user->setPassword($username); $user->setEnabled(true); $this->userManager->updateUser($user); return $user; } $user = $this->userManager->findUserByEmail($useremail); $serviceName = $response->getResourceOwner()->getName(); $setter = 'set' . ucfirst($serviceName) . 'AccessToken'; //update access token $user->{$setter}($response->getAccessToken()); return $user; }
/** * {@inheritDoc} */ public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $username = $response->getUsername(); $email = $response->getEmail(); $nickname = $response->getRealName(); //var_dump($email); die(); $user = $this->userManager->findUserByUsernameOrEmail($email); //$user = $this->userManager->findUserBy(array($this->getProperty($response) => $username)); //when the user is registrating if (null === $user) { $service = $response->getResourceOwner()->getName(); $setter = 'set' . ucfirst($service); $setter_id = $setter . 'Id'; $setter_token = $setter . 'AccessToken'; // create new user here $user = $this->userManager->createUser(); $user->{$setter_id}($username); $user->{$setter_token}($response->getAccessToken()); //I have set all requested data with the user's username //modify here with relevant data $user->setUsername($nickname); $user->setEmail($email); $user->setPlainPassword($username); $user->setEnabled(true); $this->userManager->updateUser($user); return $user; } //if user exists - go with the HWIOAuth way //$user = parent::loadUserByOAuthUserResponse($response); $serviceName = $response->getResourceOwner()->getName(); $setter = 'set' . ucfirst($serviceName) . 'AccessToken'; //update access token $user->{$setter}($response->getAccessToken()); return $user; }
/** * @param UserResponseInterface $response * @return mixed * @throws OAuthAwareException */ public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $tokenLoggedUser = $this->container->get('security.token_storage')->getToken(); $oauthServiceName = $response->getResourceOwner()->getName(); $oauthServiceUserId = $response->getUsername(); $oauthServiceAccessToken = $response->getAccessToken(); $user = $this->entityManager->getRepository('AppBundle:User')->findOneBy(array($oauthServiceName . '_id' => $oauthServiceUserId)); $setter = 'set' . ucfirst($oauthServiceName); $setter_id = $setter . 'Id'; $setter_token = $setter . 'AccessToken'; if (null === $user) { if (null === $tokenLoggedUser) { throw new AccountNotLinkedException(sprintf('Not linked "%s" account could be found', $oauthServiceName)); } $currentLoggedUser = $tokenLoggedUser->getUser(); if (in_array('ROLE_ADMIN', $currentLoggedUser->getRoles())) { $currentLoggedUser->{$setter_id}($oauthServiceUserId); $currentLoggedUser->{$setter_token}($oauthServiceAccessToken); $this->entityManager->persist($currentLoggedUser); $this->entityManager->flush(); $user = $this->entityManager->getRepository('AppBundle:User')->find($currentLoggedUser->getId()); return $user; } else { throw new OAuthAwareException(sprintf('Only users with role "ROLE_ADMIN" can link OAuth accounts.', $oauthServiceName)); } } else { $user->{$setter_token}($response->getAccessToken()); $this->entityManager->persist($user); $this->entityManager->flush(); return $user; } }
/** * {@inheritDoc} */ public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $username = $response->getUsername(); $user = $this->userManager->findUserBy(array('githubId' => $username)); if (!$user) { throw new AccountNotLinkedException(sprintf('No user with github username "%s" was found.', $username)); } if ($user->getGithubToken() !== $response->getAccessToken()) { $user->setGithubToken($response->getAccessToken()); $this->userManager->updateUser($user); } return $user; }
/** * {@inheritdoc} */ public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $userEmail = $response->getEmail(); $user = $this->userManager->findUserByEmail($userEmail); // if null just create new user and set it properties if (null === $user) { $userData = $response->getResponse(); $user = new User(); $user->setUsername($userData['formattedName']); $user->setPlainPassword(rand(1000000, 10000000)); //TODO:find a better option //TODO: add location, company name, .. $user->setEmail($response->getEmail()); $user->setEnabled(true); $this->userManager->updateUser($user); $this->em->flush(); return $user; } // else update access token of existing user $serviceName = $response->getResourceOwner()->getName(); $setter = 'set' . ucfirst($serviceName) . 'AccessToken'; $user->{$setter}($response->getAccessToken()); //update access token return $user; }
public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $name = $response->getRealName(); $email = $response->getEmail(); $clientId = $response->getUsername(); $token = $response->getAccessToken(); $user = $this->doctrine->getRepository('UserUserBundle:Users')->findOneByOAuthUser($clientId); /** @var Users $user */ if (!$user) { $service = $response->getResourceOwner()->getName(); $setter = 'set' . ucfirst($service); $setterId = $setter . "Id"; $setterToken = $setter . 'AccessToken'; $user = new Users(); $user->setRealname($name); $user->setUsername($email); $user->{$setterId}($clientId); $user->{$setterToken}($token); $user->setPassword(sha1($clientId)); $roles = $this->doctrine->getRepository('UserUserBundle:Roles')->findOneBy(['role' => 'ROLE_USER']); $user->addRole($roles); $this->doctrine->getManager()->persist($user); $this->doctrine->getManager()->flush(); $userId = $user->getId(); } else { $userId = $user->getId(); } if (!$userId) { throw new UsernameNotFoundException('Возникла проблема добавления или определения пользователя'); } return $this->loadUserByUsername($userId); }
/** * @param UserResponseInterface $response * @return User */ public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $username = $response->getUsername(); /** @var User $user */ $user = $this->userManager->findUserBy(['slackUserName' => $response->getUsername()]); if ($user === null) { $user = $this->userManager->createUser(); $user->setSlackUserName($username); $user->setSlackAccessToken($response->getAccessToken()); $user->setUsername($response->getNickname()); $user->setEmail($response->getEmail()); $user->setRealName($response->getRealName()); $user->setPassword($username); $user->setEnabled(true); $this->userManager->updateUser($user); $token = new Token($user); $this->tokenRepository->persist($token); $user->addToken($token); $this->userManager->updateUser($user); return $user; } $user = parent::loadUserByOAuthUserResponse($response); $user->setSlackAccessToken($response->getAccessToken()); $user->setRealName($response->getRealName()); $token = new Token($user); $this->tokenRepository->persist($token); $user->addToken($token); $this->userManager->updateUser($user); return $user; }
public function loadUserByOAuthUserResponse(UserResponseInterface $response) { // echa($response->getAccessToken()); // echa($response->getResponse(), __FILE__); // -- Load user's data from P4S $data = $response->getResponse(); if (null != $data && array_key_exists('status', $data) && ResponseHelper::OK == $data['status'] && array_key_exists('data', $data) && null != $data['data']) { $p4sId = $data['data']['id']; } else { throw new UsernameNotFoundException("Unable to load this user info"); } $result = $this->em->getRepository('Amisure\\P4SApiBundle\\Entity\\User\\SessionUser')->findOneBy(array('username' => $p4sId)); // - Create an account if (null == $result) { $user = $this->fillUser($data['data']); $this->createNewUser($user); } else { // $user = $result; $user = $this->fillUser($data['data']); $user->setId($result->getId()); } // -- Save access token $this->session->set('access_token', $response->getAccessToken()); return $user; }
public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $username = $response->getUsername(); $email = $response->getEmail(); $service = $response->getResourceOwner()->getName(); /** @var UserOauthAccount $connection */ $connection = $this->em->getRepository('OjsUserBundle:UserOauthAccount')->findOneBy(['providerId' => $username, 'provider' => $service]); if (!$connection && !empty($email)) { $userByEmail = $this->userManager->findUserByEmail($email); if ($userByEmail) { $connection = new UserOauthAccount(); $connection->setUser($userByEmail); $connection->setProvider($service); $connection->setProviderId($response->getUsername()); } } if (!$connection || $connection->getUser() === null) { $message = sprintf("User not found. Please register first and then connect the account from your profile.", $username); throw new AccountNotLinkedException($message); } $connection->setToken($response->getAccessToken()); $this->em->persist($connection); $this->em->flush(); return $connection->getUser(); }
/** * {@inheritdoc} */ public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $username = $response->getNickname(); $twitterId = $response->getUsername(); $accessToken = $response->getAccessToken(); $secretToken = $response->getTokenSecret(); $user = $this->userManager->findUserByUsername($username); //when the user is registrating if (is_null($user)) { // create new user here $user = $this->userManager->createUser(); $user->setUsername($username); $user->setAccessToken($accessToken); $user->setTwitterId($twitterId); $user->setSecretToken($secretToken); //I have set all requested data with the user's username //modify here with relevant data $user->setEmail($username); $user->setPlainPassword($username); $user->setEnabled(true); $this->userManager->updateUser($user); return $user; } //if user exists - go with the HWIOAuth way $user->setAccessToken($accessToken); $user->setSecretToken($secretToken); return $user; }
public function buildBasedOnOAuthResponse(UserResponseInterface $response) { $user = new UserImpl(); $user->setOAuthAccessToken($response->getAccessToken()); $user->setOAuthId($response->getUsername()); $user->setOAuthProviderClass(get_class($response->getResourceOwner())); $user->setUsername($response->getEmail()); return $user; }
/** * Create user from response * * @param UserResponseInterface $response * * @return User */ private function createUserFromResponse(UserResponseInterface $response) { /** @var User $user User */ $user = $this->userManager->createUser(); $user->setUsername($response->getUsername())->setFullName($response->getRealName())->setEmail($response->getEmail())->setEnabled(true)->setPlainPassword(uniqid())->setFacebookId($response->getUsername())->setFacebookAccessToken($response->getAccessToken()); $this->eventDispatcher->dispatch(AppEvents::FACEBOOK_USER_CONNECTED, new FacebookUserConnectedEvent($user)); $this->userManager->updateUser($user); return $user; }
/** * {@inheritdoc} */ public function loadUserByOAuthUserResponse(UserResponseInterface $response, $email = "") { $useremail = $response->getEmail(); if ($useremail == "") { $useremail = $email; } if ($useremail != "") { $username = $useremail; } else { $username = $response->getUsername(); } /** @var User $user */ $user = $this->userManager->findUserByUsernameOrEmail($username); $service = $response->getResourceOwner()->getName(); $setterID = $service . "Id"; $setter = 'set' . ucfirst($service); $setter_id = $setter . 'Id'; $setter_token = $setter . 'AccessToken'; $getter = 'get' . ucfirst($service); $getter_id = $getter . 'Id'; //when the user is registrating if (null === $user) { if ($this->userManager->findUserBy(array($setterID => $response->getUsername())) != null) { $user = $this->userManager->findUserBy(array($setterID => $response->getUsername())); return $user; } else { // create new user here $user = $this->userManager->createUser(); $user->{$setter_id}($username); $user->{$setter_token}($response->getAccessToken()); $user->setUsername($username); $user->setFullname($response->getRealName()); if ($response->getResourceOwner()->getName() == 'facebook') { $user->setPhoto('https://graph.facebook.com/' . $response->getUsername() . '/picture?type=large'); } else { $user->setPhoto($response->getProfilePicture()); } $user->setPassword($username); $user->setEnabled(true); if (filter_var($response->getEmail(), FILTER_VALIDATE_EMAIL)) { $user->setEmail($response->getEmail()); $user->setConfirmationToken(null); } else { $user->setEmail($username); } $this->userManager->updateUser($user); return $user; } } else { $user->{$setter_id}($response->getUsername()); $user->{$setter_token}($response->getAccessToken()); $this->userManager->updateUser($user); return $user; } }
/** * Loads the user by a given UserResponseInterface object. * * @param UserResponseInterface $response * * @return UserInterface * * @throws UsernameNotFoundException if the user is not found */ public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $em = $this->em; $type = $response->getResourceOwner()->getName(); $user = $em->getRepository('AppBundle:User')->findOneBy(['email' => $response->getEmail()]); if ($user === null) { $user = new User(); $user->setEmail($response->getEmail())->setFirstName($response->getFirstName() ?: $response->getUsername())->setLastName($response->getLastName() ?: $response->getRealname())->setIsActive(true); $em->persist($user); $em->flush(); } if ($type === 'facebook') { $user->setFacebookToken($response->getAccessToken())->setFacebookId($response->getUsername()); } if ($type === 'google') { $user->setGoogleToken($response->getAccessToken())->setGoogleId($response->getUsername()); } $em->flush(); return $user; }
/** * @param UserResponseInterface $response * @param $user */ private function linkUserToOAuthAccount(UserResponseInterface $response, UserInterface $user) { $username = $response->getUsername(); $service = $response->getResourceOwner()->getName(); $setter = 'set' . ucfirst($service); $setter_id = $setter . 'Id'; $setter_token = $setter . 'AccessToken'; // create new user here $user->{$setter_id}($username); $user->{$setter_token}($response->getAccessToken()); }
/** * {@inheritdoc} */ protected function updateUserByOAuthUserResponse(UserInterface $user, UserResponseInterface $response) { /** @var UserOAuthInterface $oauth */ $oauth = $this->oauthFactory->createNew(); $oauth->setIdentifier($response->getUsername()); $oauth->setProvider($response->getResourceOwner()->getName()); $oauth->setAccessToken($response->getAccessToken()); $oauth->setProfilePicture($response->getProfilePicture()); /* @var DoSUserInterface $user */ $user->addOAuthAccount($oauth); $this->userManager->persist($user); $this->userManager->flush(); return $user; }
public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $user = $this->userRepository->findOneBy(['spotifyId' => $response->getUsername()]); if (!$user instanceof SpotifyUser) { $user = new SpotifyUser($response->getUsername()); } $user->setSpotifyId($response->getUsername())->setDisplayName($response->getRealName())->setAccessToken($response->getAccessToken())->setAccessTokenExpires(time() + $response->getExpiresIn())->setRefreshToken($response->getRefreshToken())->setProfileUrl($response->getResponse()['href']); $responseHasImages = isset($response->getResponse()['images']) && is_array($response->getResponse()['images']); $responseImageExists = array_key_exists('url', $response->getResponse()['images'][0]); if ($responseHasImages && $responseImageExists) { $user->setImageUrl($response->getResponse()['images'][0]['url']); } $this->em->persist($user); $this->em->flush(); return $this->loadUserByUsername($user->getUsername()); }
public function handleResponse(UserResponseInterface $response, UserService $userService) { $fields = $response->getResponse(); $email = $fields['email']; $login = explode('@', $email)[0]; $user = $userService->findByGoogleLogin($login); if (null === $user) { throw new UsernameNotFoundException(); } $oAuthUser = new OAuthUser($user); $oAuthUser->addRole('ROLE_GOOGLE_USER'); $oAuthUser->setAccessToken($response->getAccessToken()); $oAuthUser->setRealName($fields['name']); $oAuthUser->setEmail($email); return $oAuthUser; }
public function loadUserByOAuthUserResponse(UserResponseInterface $response) { //data from facebook response // dump($response->getAccessToken(), $response->getRefreshToken()); // die(); $id = $response->getUsername(); $nickname = $response->getNickname(); $email = $response->getEmail(); //set data in session $this->session->set('id', $id); $this->session->set('email', $email); $this->session->set('access_token', $response->getAccessToken()); $this->session->set('refresh_token', $response->getRefreshToken()); /* //get user by fid $qb = $this->doctrine->getManager()->createQueryBuilder(); $qb ->select('u.id') ->from('AcmeDemoBundle:User', 'u') ->where('u.fid = :fid') ->setParameter('fid', $facebook_id) ->setMaxResults(1); $result = $qb->getQuery()->getResult(); //add to database if doesn't exists if ( !count($result) ) { $User = new User(); $User->setCreatedAt(new \DateTime()); $User->setNickname($nickname); $User->setRealname($realname); $User->setEmail($email); $User->setAvatar($avatar); $User->setFID($facebook_id); $em = $this->doctrine->getManager(); $em->persist($User); $id = $em->flush(); } else { $id = $result[0]['id']; } */ //@TODO: hmm : is admin if ($this->isUserAdmin($nickname)) { $this->session->set('is_admin', true); } //parent:: returned value return $this->loadUserByUsername($response->getNickname()); }
/** * @param UserResponseInterface $response * * @return \FOS\UserBundle\Model\UserInterface|UserInterface */ public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $data = $response->getResponse(); $username = $data['login']; $user = $this->userManager->findUserByUsername($username); //when the user is registrating if (null === $user) { $service = $response->getResourceOwner()->getName(); $setter = 'set' . ucfirst($service); $setterId = $setter . 'Id'; $setterToken = $setter . 'AccessToken'; // create new user here $user = $this->userManager->createUser(); $user->{$setterId}($data['id']); $user->{$setterToken}($response->getAccessToken()); unset($data['name']); unset($data['email']); if (isset($data['name'])) { $user->setRealName($data['name']); } if (isset($data['email'])) { $user->setEmail($data['email']); } //I have set all requested data with the user's username modify here with relevant data $user->setUsername($username); $user->setPlainPassword($data['id']); $user->setAvatarUrl($data['avatar_url']); $user->setGravatarId($data['gravatar_id']); $user->setEnabled(true); $this->userManager->updateUser($user); return $user; } //if user exists - go with the HWIOAuth way $user = parent::loadUserByOAuthUserResponse($response); $serviceName = $response->getResourceOwner()->getName(); $setter = 'set' . ucfirst($serviceName) . 'AccessToken'; //update access token $user->{$setter}($response->getAccessToken()); return $user; }
public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $google_id = $response->getUsername(); $email = $response->getEmail(); //Check if this Google user already exists in our app DB $qb = $this->doctrine->getManager()->createQueryBuilder(); $qb->select('u')->from('meetmeBundle\\Entity\\User', 'u')->where('u.googleId = :gid')->setParameter('gid', $google_id)->setMaxResults(1); $result = $qb->getQuery()->getResult(); //when the user is registrating if (!count($result)) { // $service = $response->getResourceOwner()->getName(); //// $setter = 'set'.ucfirst($service); //// $setter_id = $setter.'Id'; //// $setter_token = $setter.'AccessToken'; // create new user here $user = new User(); $user->setGoogleId($google_id); $user->setGoogleAccessToken($response->getAccessToken()); //I have set all requested data with the user's username //modify here with relevant data $user->setUsername($google_id); $user->setEmail($email); //Set some wild random pass since its irrelevant, this is Google login $factory = $this->container->get('security.encoder_factory'); $encoder = $factory->getEncoder($user); $password = $encoder->encodePassword(md5(uniqid()), $user->getSalt()); $user->setPassword($password); $user->setStatus(1); $em = $this->doctrine->getManager(); $em->persist($user); $em->flush(); return $user; } else { $user = $result[0]; /* return User */ } //set id $this->session->set('id', $user->getId()); return $this->loadUserByUsername($response->getUsername()); }
function it_should_create_new_user_when_none_was_found($userManager, $oauthRepository, UserInterface $user, UserResponseInterface $response, ResourceOwnerInterface $resourceOwner, UserOAuthInterface $oauth) { $resourceOwner->getName()->willReturn('google'); $response->getEmail()->willReturn(null); $response->getUsername()->willReturn('username'); $response->getNickname()->willReturn('user'); $response->getResourceOwner()->willReturn($resourceOwner); $response->getAccessToken()->willReturn('access_token'); $oauthRepository->findOneBy(array('provider' => 'google', 'identifier' => 'username'))->willReturn(null); $oauthRepository->createNew()->willReturn($oauth); $userManager->createUser()->willReturn($user); $oauth->setIdentifier('username'); $oauth->setProvider('google'); $oauth->setAccessToken('access_token'); $user->getUsername()->willReturn(null); $user->setUsername('user')->shouldBeCalled(); $user->setPlainPassword('2ff2dfe363')->shouldBeCalled(); $user->setEnabled(true)->shouldBeCalled(); $user->addOAuthAccount($oauth)->shouldBeCalled(); $userManager->updateUser($user)->shouldBeCalled(); $this->loadUserByOAuthUserResponse($response)->shouldReturn($user); }
/** * {@inheritdoc} */ public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $username = $response->getUsername(); $email = $response->getEmail(); $user = $this->userManager->findUserBy(array('email' => $email)); //when the user is registrating $service = $response->getResourceOwner()->getName(); $setter = 'set' . ucfirst($service); $setter_id = $setter . 'Id'; $setter_token = $setter . 'AccessToken'; if (null === $user) { // create new user here $user = $this->userManager->createUser(); $user->{$setter_id}($username); $user->{$setter_token}($response->getAccessToken()); //I have set all requested data with the user's username //modify here with relevant data $user->setUsername($response->getNickname()); $user->setEmail($email); $user->setPassword($username); $user->setEnabled(true); $this->userManager->updateUser($user); $event = new OAuthResponseEvent($user, $response); $this->eventDispatcher->dispatch(OesteveUserEvents::REGISTRATION_OAUTH_COMPLETED, $event); return $user; } $user->{$setter_id}($username); $this->userManager->updateUser($user); //if user exists - go with the HWIOAuth way $user = parent::loadUserByOAuthUserResponse($response); $serviceName = $response->getResourceOwner()->getName(); $setter = 'set' . ucfirst($serviceName) . 'AccessToken'; //update access token $user->{$setter}($response->getAccessToken()); return $user; }
/** * {@inheritdoc} */ public function loadUserByOAuthUserResponse(UserResponseInterface $response) { // First, check if it's an Azure User if (get_class($response->getResourceOwner()) != "HWI\\Bundle\\OAuthBundle\\OAuth\\ResourceOwner\\AzureResourceOwner") { throw new UnsupportedUserException("Can not load a user by " . get_class($response->getResourceOwner()) . "."); } // Check if this user exists $user = $this->userManager->findUserByEmail($response->getEmail()); // Load groups ids $groups = $this->entityManager->createQueryBuilder()->select("azureRole.azureGid")->from("BdEMainBundle:AzureRole", 'azureRole')->getQuery()->getArrayResult(); $request = ['groupIds' => []]; foreach ($groups as $group) { $request['groupIds'][] = $group['azureGid']; } // Load groups for this user $client = new Curl(); $client->setTimeout(20000); $client = new Browser($client); $uid = $response->getResponse()['oid']; $uri = "https://graph.windows.net" . "/" . $this->tenant . "/me/checkMemberGroups?api-version=1.6"; $r = $client->post($uri, array("Authorization: Bearer " . $response->getAccessToken() . "", "Content-Type: application/json", "Accept: application/json"), json_encode($request)); $r = json_decode($r->getContent()); $groups = $r->value; $roleRepo = $this->entityManager->getRepository("BdEMainBundle:AzureRole"); /** @var AzureRole[] $azureRoles */ $azureRoles = $roleRepo->createQueryBuilder('azureRole')->where('azureRole.azureGid IN (?1)')->setParameter(1, $groups)->getQuery()->getResult(); /** @var Role[] $roles */ $roles = array(); foreach ($azureRoles as $azureRole) { $roles = array_merge($roles, $azureRole->getRoles()); } $roles = array_unique($roles); if (sizeof($roles) == 0) { // Try to get if it's a SuperAdmin $uri = "https://graph.windows.net" . "/" . $this->tenant . "/me/memberOf?api-version=1.6"; $r = $client->get($uri, array("authorization: Bearer " . $response->getAccessToken())); $userRoles = json_decode($r->getContent()); if (!property_exists($userRoles, 'value')) { throw new UsernameNotFoundException(sprintf("Impossible to log you !", $response->getRealName())); } $userRoles = $userRoles->value; foreach ($userRoles as $userRole) { if ($userRole->objectType == 'Role') { if ($userRole->displayName == "Company Administrator" && strpos($response->getEmail(), $this->tenant) !== false) { // We found an Admin ! $roles[] = new Role("ROLE_SUPER_ADMIN"); break; } } } if (count($roles) == 0) { $this->flashBag->add("error", $response->getEmail() . " ne peut pas se connecter à cette application"); throw new UsernameNotFoundException(sprintf("User '%s' has no power here!", $response->getRealName())); } } /** @var User $user */ if ($user == null) { $user = $this->userManager->createUser(); } $user->setRoles($roles); $user->setEmail($response->getEmail()); $user->setEmailCanonical($response->getEmail()); $user->setEnabled(true); $user->setUsername($response->getEmail()); $user->setPlainPassword($response->getAccessToken()); $user->setAzureAccessToken($response->getAccessToken()); $user->setAzureRenewAccessToken($response->getRefreshToken()); $this->userManager->updateUser($user); return $user; }
/** * {@inheritdoc} */ public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $user = new WebHomeUser($response->getNickname(), null, $response->getFirstName(), $response->getLastName(), $response->getLocale(), $response->getAccessToken(), $response->getRefreshToken()); $user->initRolesAndApplications($response->getRoles()); return $user; }
/** * Attach OAuth sign-in provider account to existing user. * * @param UserInterface $user * @param UserResponseInterface $response * * @return UserInterface */ private function updateUserByOAuthUserResponse(UserInterface $user, UserResponseInterface $response) { $oauth = $this->oauthFactory->createNew(); $oauth->setIdentifier($response->getUsername()); $oauth->setProvider($response->getResourceOwner()->getName()); $oauth->setAccessToken($response->getAccessToken()); $oauth->setRefreshToken($response->getRefreshToken()); /* @var $user SyliusUserInterface */ $user->addOAuthAccount($oauth); $this->userManager->persist($user); $this->userManager->flush(); return $user; }
/** * {@inheritDoc} */ public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $rawResponse = $response->getResponse(); $username = $response->getUsername(); $screenName = $response->getNickname(); $service = $response->getResourceOwner()->getName(); $setter = 'set' . ucfirst($service); $setter_id = $setter . 'Id'; $setter_token = $setter . 'AccessToken'; $setter_username = $setter . 'Username'; $newUser = false; $user = $this->userManager->findUserBy(array("{$service}Id" => $username)); if (null === $user) { switch ($service) { case 'twitter': $email = $this->session->get('twitter.email'); if (!$email) { throw new MissingEmailException(); } else { $this->session->remove('twitter.email'); } $defaultUsername = "******"; break; case 'google': $email = $rawResponse['email']; $defaultUsername = $email; break; default: $email = $rawResponse['email']; $defaultUsername = $email; break; } $newUser = true; $user = $this->userManager->createUser(); $user->{$setter_id}($username); $user->{$setter_token}($response->getAccessToken()); $user->{$setter_username}($screenName); $fullName = explode(' ', $response->getRealName(), 2); if (isset($fullName[0][1]) && $fullName[0][1] != '') { $user->setFirstName($fullName[0]); } if (isset($fullName[1][1]) && $fullName[1][1] != '') { $user->setSurname($fullName[1]); } if (!UsernameValidator::isUsernameValid($screenName)) { $screenName = UsernameValidator::getValidUsername(); } $availableUsername = $this->userManager->getNextAvailableUsername($screenName, 10, $defaultUsername); $user->setUsername($availableUsername); $user->setEmail($email); $user->setPassword(''); $user->setEnabled(true); $this->userManager->updateCanonicalFields($user); $form = $this->formFactory->createForm(); $form->setData($user); $request = $this->container->get('request'); $eventResponse = new \Symfony\Component\HttpFoundation\RedirectResponse('/'); $event = new FormEvent($form, $request); if ($newUser) { $this->dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event); } $this->userManager->updateUser($user); if ($newUser) { $this->dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $eventResponse)); } return $user; } $user = parent::loadUserByOAuthUserResponse($response); $serviceName = $response->getResourceOwner()->getName(); $setter = 'set' . ucfirst($serviceName) . 'AccessToken'; $user->{$setter}($response->getAccessToken()); return $user; }
function it_should_create_new_user_when_none_was_found($userManager, FactoryInterface $customerFactory, FactoryInterface $userFactory, FactoryInterface $oauthFactory, RepositoryInterface $oauthRepository, CustomerInterface $customer, ShopUserInterface $user, UserResponseInterface $response, ResourceOwnerInterface $resourceOwner, UserOAuthInterface $oauth) { $resourceOwner->getName()->willReturn('google'); $response->getEmail()->willReturn(null); $response->getUsername()->willReturn('username'); $response->getNickname()->willReturn('user'); $response->getRealName()->willReturn('Name'); $response->getResourceOwner()->willReturn($resourceOwner); $response->getAccessToken()->willReturn('access_token'); $response->getRefreshToken()->willReturn('refresh_token'); $oauthRepository->findOneBy(['provider' => 'google', 'identifier' => 'username'])->willReturn(null); $oauthFactory->createNew()->willReturn($oauth); $userFactory->createNew()->willReturn($user); $customerFactory->createNew()->willReturn($customer); $customer->setFirstName('Name')->shouldBeCalled(); $oauth->setIdentifier('username'); $oauth->setProvider('google'); $oauth->setAccessToken('access_token'); $oauth->setRefreshToken('refresh_token'); $user->setCustomer($customer)->shouldBeCalled(); $user->getUsername()->willReturn(null); $user->setUsername('user')->shouldBeCalled(); $user->setPlainPassword('2ff2dfe363')->shouldBeCalled(); $user->setEnabled(true)->shouldBeCalled(); $user->addOAuthAccount($oauth)->shouldBeCalled(); $userManager->persist($user)->shouldBeCalled(); $userManager->flush()->shouldBeCalled(); $this->loadUserByOAuthUserResponse($response)->shouldReturn($user); }