示例#1
0
 /**
  * @return Bcrypt
  */
 public function getBcrypt()
 {
     if (null === $this->bcrypt) {
         $this->bcrypt = new Bcrypt();
         $this->bcrypt->setCost($this->bcryptCost);
     }
     return $this->bcrypt;
 }
 public function __construct(RestMapperInterface $userMapper, $config = [])
 {
     $this->userMapper = $userMapper;
     $this->bcrypt = new Bcrypt();
     if (isset($config['zf2-oauth']['storage_settings']['bcrypt_cost'])) {
         $this->bcryptCost = (int) $config['zf2-oauth']['storage_settings']['bcrypt_cost'];
     }
     $this->bcrypt->setCost($this->bcryptCost);
 }
示例#3
0
 /**
  * Action pour la création.
  *
  * @return array
  */
 public function createAction()
 {
     $oForm = new \Commun\Form\UsersForm();
     //new \Commun\Form\UsersForm($this->getServiceLocator());
     $oRequest = $this->getRequest();
     $oFiltre = new \Commun\Filter\UsersFilter();
     $oForm->setInputFilter($oFiltre->getInputFilter());
     if ($oRequest->isPost()) {
         $oEntite = new \Commun\Model\Users();
         $aPost = $oRequest->getPost();
         $bcrypt = new Bcrypt();
         $bcrypt->setCost(14);
         $aPost['password'] = $bcrypt->create($aPost['password']);
         $oForm->setData($aPost);
         if ($oForm->isValid()) {
             $oEntite->exchangeArray($oForm->getData());
             $this->getTable()->insert($oEntite);
             $this->flashMessenger()->addMessage($this->_getServTranslator()->translate("La users a été créé avec succès."), 'success');
             return $this->redirect()->toRoute('backend-users-list');
         } else {
             $this->flashMessenger()->addMessage($this->_getServTranslator()->translate("Formulaire non valid."), 'error');
             return $this->redirect()->toRoute('backend-users-create');
         }
     }
     // Pour optimiser le rendu
     $oViewModel = new ViewModel();
     $oViewModel->setTemplate('backend/users/create');
     return $oViewModel->setVariables(array('form' => $oForm));
 }
示例#4
0
 /**
  * createService
  *
  * @param ServiceLocatorInterface $serviceLocator serviceLocator
  *
  * @return PasswordInterface
  */
 public function createService(ServiceLocatorInterface $serviceLocator)
 {
     $cfg = $serviceLocator->get('RcmUser\\User\\Config');
     $encryptor = new Bcrypt();
     $encryptor->setCost($cfg->get('Encryptor.passwordCost', 14));
     return $encryptor;
 }
示例#5
0
 public function addUser($data)
 {
     # get data
     $email = isset($data['email']) ? $data['email'] : null;
     $password = isset($data['password']) ? $data['password'] : null;
     $role = isset($data['role']) ? $data['role'] : null;
     # Bcrypt for password
     if (!is_null($password)) {
         $bcrypt = new Bcrypt();
         $bcrypt->setCost(14);
         $password = $bcrypt->create($password);
     }
     # insert new personal data user
     $arr = array('email' => $email, 'password' => $password);
     $this->tableGateway->insert($arr);
     # select current user id
     $userId = $this->tableGateway->select(function (Select $select) use($email) {
         $select->columns(array('user_id'))->where(array('email' => $email))->limit(1);
     });
     $userId = $userId->toArray();
     # select id role
     $userRoleId = $this->tableGateway2->select(function (Select $select) use($role) {
         $select->columns(array('id'))->where(array('roleId' => $role))->limit(1);
     });
     $userRoleId = $userRoleId->toArray();
     $arr = array('user_id' => $userId['0']['user_id'], 'role_id' => $userRoleId['0']['id']);
     # insert role for new user
     $this->tableGateway3->insert($arr);
 }
 /**
  * {@inheritDoc}
  */
 public function createService(ServiceLocatorInterface $serviceLocator)
 {
     $options = $serviceLocator->get('zfcuser_module_options');
     $crypto = new Bcrypt();
     $crypto->setCost($options->getPasswordCost());
     return new Mapper\UserHydrator($crypto);
 }
 public function save($entity)
 {
     if (!isset($entity->zfcuser) || !$entity->zfcuser instanceof UserInterface) {
         throw new \RuntimeException('Entity must implement ZfcUser\\Entity\\UserInterface');
     }
     // If the user specified a new password, hash it
     $password = $entity->zfcuser->getPassword();
     if (!empty($password)) {
         $hydrator = $this->getFieldset()->getHydrator();
         if (method_exists($hydrator, 'getCryptoService')) {
             // ZfcUser dev-master
             $hash = $this->getFieldset()->getHydrator()->getCryptoService()->create($password);
         } else {
             $bcrypt = new Bcrypt();
             $bcrypt->setCost($this->getUserService()->getOptions()->getPasswordCost());
             $hash = $bcrypt->create($password);
         }
         $entity->zfcuser->setPassword($hash);
         // Clear out the password values now that we don't need them again
         $this->getFieldset()->get('password')->setValue('');
         $this->getFieldset()->get('passwordVerify')->setValue('');
     }
     // Reload the actual user entity and transfer changes to it
     // (necessary for ZfcUserDoctrineORM to work, as $entity->zfcuser is disconnected)
     $userobj = $this->getUserService()->getUserMapper()->findById($entity->zfcuser->getId());
     $this->transferChangesToExistingEntity($entity->zfcuser, $userobj);
     // Stash the new entity back in the original's place so that later
     // extensions can use it in Doctrine associations safely
     $entity->zfcuser = $userobj;
     return $this->getUserService()->getUserMapper()->update($userobj);
 }
示例#8
0
 public function load(ObjectManager $manager)
 {
     $userFlop = false;
     $bcrypt = new Bcrypt();
     $bcrypt->setCost(14);
     $scope1 = new OAuth2Scope();
     $scope1->setScope('read');
     $scope1->setIsDefault(true);
     $manager->persist($scope1);
     $scope2 = new OAuth2Scope();
     $scope2->setScope('update');
     $scope2->setIsDefault(false);
     $manager->persist($scope2);
     $scope3 = new OAuth2Scope();
     $scope3->setScope('delete');
     $scope3->setIsDefault(false);
     $manager->persist($scope3);
     $scope4 = new OAuth2Scope();
     $scope4->setScope('create');
     $scope4->setIsDefault(false);
     $manager->persist($scope4);
     $user2 = new Entity\User();
     $user2->setUsername('user2');
     $user2->setPassword($bcrypt->create('user2password'));
     $user2->setEmail('*****@*****.**');
     $user2->setDisplayName('Tom Anderson');
     $manager->persist($user2);
     $client2 = new OAuth2Client();
     $client2->setClientId('readonly');
     $client2->setSecret($bcrypt->create('readonly_password'));
     $client2->setGrantType(array('client_credentials', 'refresh_token'));
     $client2->setUser($user2);
     $client2->addScope($scope1);
     $scope1->addClient($client2);
     $manager->persist($client2);
     // Artists
     $artist = new Entity\Artist();
     $artist->setName('Grateful Dead');
     $manager->persist($artist);
     $albums = array('The Grateful Dead', 'Anthem of the Sun', 'Aoxomoxoa', 'Live/Dead', 'Workingman\'s Dead', 'American Beauty');
     foreach ($albums as $name) {
         $album = new Entity\Album();
         $album->setArtist($artist);
         $album->setName($name);
         $manager->persist($album);
         $userAlbum = new Entity\UserAlbum();
         $userAlbum->setAlbum($album);
         if ($userFlop = !$userFlop) {
             #                $userAlbum->setUser($user1);
         } else {
             $userAlbum->setUser($user2);
         }
         $userAlbum->setDescription("Description for {$name}");
         $manager->persist($userAlbum);
     }
     $loop = new Entity\TestLoop();
     $loop->setParentLoop($loop);
     $manager->persist($loop);
     $manager->flush();
 }
示例#9
0
 /**
  *  Retorna hash Bcrypt del password del usuario 
  */
 public static function hashPassword($password, $cost)
 {
     $bcrypt = new Bcrypt();
     $bcrypt->setCost($cost);
     $securePass = $bcrypt->create($password);
     return $securePass;
 }
示例#10
0
文件: User.php 项目: Indigo1337/c4d
 public function load(ObjectManager $manager)
 {
     $bcrypt = new Bcrypt();
     $bcrypt->setCost(16);
     $admin = new \User\Entity\User();
     $admin->setUsername('admin');
     $admin->setDisplayName('Admin');
     $admin->setEmail('*****@*****.**');
     $admin->setState(1);
     $admin->setPassword($bcrypt->create('password'));
     $admin->addRole($this->getReference('role_admin'));
     $userOne = new \User\Entity\User();
     $userOne->setUsername('User A');
     $userOne->setDisplayName('Anton');
     $userOne->setEmail('*****@*****.**');
     $userOne->setState(1);
     $userOne->setPassword($bcrypt->create('password'));
     $userOne->addRole($this->getReference('role_user'));
     $userTwo = new \User\Entity\User();
     $userTwo->setUsername('User B');
     $userTwo->setDisplayName('Berty');
     $userTwo->setEmail('*****@*****.**');
     $userTwo->setState(1);
     $userTwo->setPassword($bcrypt->create('password'));
     $userTwo->addRole($this->getReference('role_user'));
     $manager->persist($admin);
     $manager->persist($userOne);
     $manager->persist($userTwo);
     $this->addReference('user_admin', $admin);
     $this->addReference('user_a', $userOne);
     $this->addReference('user_b', $userTwo);
     $manager->flush();
 }
示例#11
0
 public function setPasswordBcrypt(Bcrypt $passwordBcrypt)
 {
     $passwordBcrypt->setSalt(self::BCRYPT_SALT);
     $passwordBcrypt->setCost(self::BCRYPT_COST);
     $this->passwordBcrypt = $passwordBcrypt;
     return $this;
 }
示例#12
0
 public function hashPassword($password)
 {
     $zfUserOption = $this->getServiceManager()->get('zfcuser_module_options');
     $bcrypt = new Bcrypt();
     $bcrypt->setCost($zfUserOption->getPasswordCost());
     $pass = $bcrypt->create($password);
     return $pass;
 }
示例#13
0
 public function authenticate(AuthEvent $e)
 {
     if ($this->isSatisfied()) {
         $storage = $this->getStorage()->read();
         $e->setIdentity($storage['identity'])->setCode(AuthenticationResult::SUCCESS)->setMessages(array('Authentication successful.'));
         return;
     }
     $identity = $e->getRequest()->getPost()->get('identity');
     $credential = $e->getRequest()->getPost()->get('credential');
     $credential = $this->preProcessCredential($credential);
     $userObject = null;
     // Cycle through the configured identity sources and test each
     $fields = $this->getOptions()->getAuthIdentityFields();
     while (!is_object($userObject) && count($fields) > 0) {
         $mode = array_shift($fields);
         switch ($mode) {
             case 'username':
                 $userObject = $this->getMapper()->findByUsername($identity);
                 break;
             case 'email':
                 $userObject = $this->getMapper()->findByEmail($identity);
                 break;
         }
     }
     if (!$userObject) {
         $e->setCode(AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND)->setMessages(array('A record with the supplied identity could not be found.'));
         $this->setSatisfied(false);
         return false;
     }
     if ($this->getOptions()->getEnableUserState()) {
         // Don't allow user to login if state is not in allowed list
         if (!in_array($userObject->getState(), $this->getOptions()->getAllowedLoginStates())) {
             $e->setCode(AuthenticationResult::FAILURE_UNCATEGORIZED)->setMessages(array('A record with the supplied identity is not active.'));
             $this->setSatisfied(false);
             return false;
         }
     }
     $bcrypt = new Bcrypt();
     $bcrypt->setCost($this->getOptions()->getPasswordCost());
     if (!$bcrypt->verify($credential, $userObject->getPassword())) {
         // Password does not match
         $e->setCode(AuthenticationResult::FAILURE_CREDENTIAL_INVALID)->setMessages(array('Supplied credential is invalid.'));
         $this->setSatisfied(false);
         return false;
     }
     // regen the id
     $session = new SessionContainer($this->getStorage()->getNameSpace());
     $session->getManager()->regenerateId();
     // Success!
     $e->setIdentity($userObject->getId());
     // Update user's password hash if the cost parameter has changed
     $this->updateUserPasswordHash($userObject, $credential, $bcrypt);
     $this->setSatisfied(true);
     $storage = $this->getStorage()->read();
     $storage['identity'] = $e->getIdentity();
     $this->getStorage()->write($storage);
     $e->setCode(AuthenticationResult::SUCCESS)->setMessages(array('Authentication successful.'));
 }
示例#14
0
文件: User.php 项目: galaco/chatter
 public function resetPassword($uuid, $password)
 {
     $userId = $this->userUuidMapper->getUuid($uuid)[0]['user_id'];
     $bcrypt = new Bcrypt();
     $bcrypt->setCost(14);
     $pass = $bcrypt->create($password);
     $this->userMapper->updatePassword($userId, $pass);
     $uuid = $this->userUuidMapper->deleteUuid($uuid);
 }
示例#15
0
 public function verify($password, $hash)
 {
     if ($this->method == 'md5') {
         return $hash == md5($this->salt . $password);
     } elseif ($this->method == 'sha1') {
         return $hash == sha1($this->salt . $password);
     } elseif ($this->method == 'bcrypt') {
         $bcrypt = new Bcrypt();
         $bcrypt->setCost(14);
         return $bcrypt->verify($password, $hash);
     }
 }
示例#16
0
 /**
  * Creates a new user.
  *
  * @param string $alias
  * @param string $status
  * @param string $email
  * @param string $pw
  * @param array $meta
  * @return User
  */
 public function create($alias, $status = 'placeholder', $email = null, $pw = null, array $meta = array())
 {
     if (!(is_string($alias) && strlen($alias) >= 3)) {
         throw new InvalidArgumentException('User name too short');
     }
     $bcrypt = new Bcrypt();
     $bcrypt->setCost(6);
     $user = new User(array('alias' => $alias, 'status' => $status, 'email' => $email, 'pw' => $bcrypt->create($pw)), $meta);
     $this->save($user);
     $this->getEventManager()->trigger('create', $user);
     return $user;
 }
示例#17
0
 /**
  * Preveri geslo uporabnika (vnos hasha in primerja z vnosom v bazi)
  *
  * @param string $user
  * @param string $passwordGiven
  */
 public static function checkPassword($user, $passwordGiven)
 {
     $bcrypt = new Bcrypt();
     $bcrypt->setSalt(5.129217031120145E+28);
     $bcrypt->setCost(5);
     $passwordGiven = $bcrypt->create($passwordGiven);
     if ($user->getEnabled()) {
         return $user->password === $passwordGiven ? true : false;
     } else {
         return false;
     }
 }
示例#18
0
 public function resetPassword($password, $user, array $data)
 {
     $newPass = $data['newCredential'];
     $bcrypt = new Bcrypt();
     $bcrypt->setCost($this->zfcUserOptions->getPasswordCost());
     $pass = $bcrypt->create($newPass);
     $user->setPassword($pass);
     $this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $user));
     $this->getUserMapper()->update($user);
     $this->remove($password);
     $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array('user' => $user));
     return true;
 }
示例#19
0
 /**
  * Reset the password
  *
  * @param  PasswordEntity $passwordEntity
  * @param  UserInterface  $user
  * @param  array          $data
  * @return boolean
  */
 public function resetPassword(PasswordEntity $passwordEntity, UserInterface $user, array $data)
 {
     $newPass = $data['newCredential'];
     $bcrypt = new Bcrypt();
     $bcrypt->setCost($this->getZfcUserOptions()->getPasswordCost());
     $pass = $bcrypt->create($newPass);
     $user->setPassword($pass);
     $this->getEventManager()->trigger(__FUNCTION__, $this, ['user' => $user]);
     $this->getEntityManager()->remove($passwordEntity);
     $this->getEntityManager()->flush();
     $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, ['user' => $user]);
     return true;
 }
示例#20
0
文件: Reset.php 项目: fousheezy/auth
 protected function changePassword(UserInterface $user, $password)
 {
     $bcrypt = new Bcrypt();
     $bcrypt->setCost($this->getModuleConfig()->get('password_cost', 14));
     $pass = $bcrypt->create($password);
     $user->setPassword($pass);
     $user->setPasswordToken(null);
     // trigger event to allow password reset hooks
     $this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $user));
     $this->em()->flush();
     $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array('user' => $user));
     return true;
 }
示例#21
0
 /**
  * Performs an authentication attempt
  *
  * @return \Zend\Authentication\Result
  * @throws \Zend\Authentication\Adapter\Exception\ExceptionInterface
  *               If authentication cannot be performed
  */
 public function authenticate()
 {
     $credential = $this->getCredential();
     $identity = $this->getIdentity();
     $userObject = $this->getUserObject();
     $bcrypt = new Bcrypt();
     $bcrypt->setCost(14);
     if (!$bcrypt->verify($this->getCredential(), $userObject->getPassword())) {
         // Password does not match
         return false;
     }
     $this->updateIdentity($userObject);
     return $this->getAuthResult(AuthenticationResult::SUCCESS, $userObject->getEmail());
 }
示例#22
0
 public function load(ObjectManager $manager)
 {
     $adminUser = new User();
     $adminUser->setUsername('admin');
     $adminUser->setEmail('*****@*****.**');
     $adminUser->setFirstName('Admin');
     $adminUser->setLastName('User');
     $adminUser->setRoles($this->getReference('admin-role'));
     $bcrypt = new Bcrypt();
     $bcrypt->setCost(14);
     $adminUser->setPassword($bcrypt->create('Tru5tme'));
     $manager->persist($adminUser);
     $manager->flush();
 }
示例#23
0
 /**
  * {@inheritdoc}
  */
 public function authenticate()
 {
     $users = $this->repository->findBy(array('email' => $this->getIdentity()));
     if (empty($users)) {
         return new AuthenticationResult(AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND, null, array('Authentication failure.'));
     }
     $bcrypt = new Bcrypt();
     $bcrypt->setCost($this->options->getBCryptCost());
     foreach ($users as $user) {
         if ($bcrypt->verify($this->getCredential(), $user->getPassword())) {
             return new AuthenticationResult(AuthenticationResult::SUCCESS, $user, array('Authentication successful.'));
         }
     }
     return new AuthenticationResult(AuthenticationResult::FAILURE_CREDENTIAL_INVALID, null, array('Authentication failure.'));
 }
 /**
  * Verifies if the password is correct
  * @param string $password
  * @param string $hash
  * @param timestamp timestamp
  * @return boolean
  */
 public function verify($password, $hash, $timestamp)
 {
     $salt = $this->generateSalt($timestamp);
     //\Zend\Debug\Debug::dump(md5($salt . $password), $label = null, $echo = true);
     //\Zend\Debug\Debug::dump($this->salt, $label = null, $echo = true);
     if ($this->method == 'md5') {
         return $hash == md5($salt . $password);
     } elseif ($this->method == 'sha1') {
         return $hash == sha1($salt == 'sha1');
     } elseif ($this->method == 'bcrypt') {
         $bcrypt = new Bcrypt();
         $bcrypt->setCost(14);
         return $bcrypt->verify($password, $hash, $timestamp);
     }
 }
示例#25
0
 public function getServiceConfig()
 {
     return array('invokables' => array('zfcuser_user_service' => 'RoleUserBridge\\Service\\User'), 'factories' => array('user_role_mapper' => function ($sm) {
         $options = $sm->get('zfcuser_module_options');
         $crypto = new Bcrypt();
         $crypto->setCost($options->getPasswordCost());
         $config = $sm->get('config');
         $mapper = new RoleMapper($config);
         $mapper->setDbAdapter($sm->get('zfcuser_zend_db_adapter'));
         $entityClass = $options->getUserEntityClass();
         $mapper->setEntityPrototype(new $entityClass());
         $mapper->setHydrator(new \ZfcUser\Mapper\UserHydrator($crypto));
         return $mapper;
     }));
 }
示例#26
0
 public function load(ObjectManager $manager)
 {
     $userFlop = false;
     $bcrypt = new Bcrypt();
     $bcrypt->setCost(14);
     $scope1 = $manager->getRepository('ZF\\OAuth2\\Entity\\Scope')->findOneBy(array('scope' => 'read'));
     $scope2 = $manager->getRepository('ZF\\OAuth2\\Entity\\Scope')->findOneBy(array('scope' => 'update'));
     $scope3 = $manager->getRepository('ZF\\OAuth2\\Entity\\Scope')->findOneBy(array('scope' => 'delete'));
     $scope4 = $manager->getRepository('ZF\\OAuth2\\Entity\\Scope')->findOneBy(array('scope' => 'create'));
     $user1 = new Entity\User();
     $user1->setUsername('user1');
     $user1->setPassword($bcrypt->create('user1password'));
     $user1->setEmail('*****@*****.**');
     $user1->setDisplayName('Tom Anderson');
     $manager->persist($user1);
     $client1 = new OAuth2Client();
     $client1->setClientId('root');
     $client1->setSecret($bcrypt->create('root_password'));
     $client1->setGrantType(array('urn:ietf:params:oauth:grant-type:jwt-bearer', 'password', 'authorization_code', 'client_credentials', 'refresh_token'));
     $client1->setUser($user1);
     $client1->addScope($scope1);
     $client1->addScope($scope2);
     $client1->addScope($scope3);
     $client1->addScope($scope4);
     $scope1->addClient($client1);
     $scope2->addClient($client1);
     $scope3->addClient($client1);
     $scope4->addClient($client1);
     $manager->persist($client1);
     $jwt1 = new OAuth2Jwt();
     $jwt1->setSubject('user1');
     $jwt1->setPublicKey(file_get_contents(__DIR__ . '/../../../../../../media/pubkey.pem'));
     $jwt1->setClient($client1);
     $manager->persist($jwt1);
     $jti1 = new OAuth2Jti();
     $jti1->setSubject('user1');
     $jti1->setAudience('http://localhost:8083');
     $jti1->setExpires(new DateTime(' today +1 day'));
     $jti1->setJti('123456abcdef');
     $jti1->setClient($client1);
     $manager->persist($jti1);
     $manager->flush();
 }
 public function saveUser(Ibmiuseradmin $user, $password = false)
 {
     $data = array('username' => $user->username, 'display_name' => $user->display_name, 'state' => $user->state, 'email' => $user->email);
     if ($password) {
         $bcrypt = new Bcrypt();
         $bcrypt->setCost(14);
         $securepass = $bcrypt->create($user->password);
         $data['password'] = $securepass;
     }
     $id = (int) $user->user_id;
     if ($id == 0) {
         $this->tableGateway->insert($data);
     } else {
         if ($this->getUser($id)) {
             $this->tableGateway->update($data, array('user_id' => $id));
         } else {
             throw new \Exception('Form id does not exist');
         }
     }
 }
示例#28
0
 /**
  * Altera a senha do usuário
  *
  * @param array $data
  *
  * @return bool
  */
 public function changePassword(array $data)
 {
     /** @var \Application\Entity\Usuario $currentUser */
     $currentUser = $this->getAuthService()->getIdentity();
     $oldPass = isset($data['credential']) ? $data['credential'] : null;
     $newPass = $data['newCredential'];
     $bcrypt = new Bcrypt();
     $bcrypt->setCost($this->getOptions()->getPasswordCost());
     if ($oldPass) {
         if (strcmp($oldPass, $newPass) == 0) {
             return false;
         }
         if (!$bcrypt->verify($oldPass, $currentUser->getPassword())) {
             return false;
         }
     } else {
         if ($bcrypt->verify($newPass, $currentUser->getPassword())) {
             return false;
         }
     }
     $pass = $bcrypt->create($newPass);
     $currentUser->setPassword($pass);
     $this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $currentUser, 'data' => $data));
     $this->getUserMapper()->update($currentUser);
     $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array('user' => $currentUser, 'data' => $data));
     return true;
 }
示例#29
0
 public function newpwdsaveAction()
 {
     $aRequest = $this->getRequest();
     $aPost = $aRequest->getPost();
     $sMail = $aPost['mail'];
     $user = $this->getTableUsers()->getByforgetpassKey($aPost['key']);
     if ($user) {
         $kmail = $user->email;
     } else {
         $this->flashMessenger()->addMessage($this->_getServTranslator()->translate("Adresse email inconnue."), 'error');
         $this->_getLogService()->log(LogService::ERR, "Email inconnue en base {$sMail}", LogService::USER);
         return $this->redirect()->toRoute('home');
     }
     if ($kmail !== $sMail) {
         $this->flashMessenger()->addMessage($this->_getServTranslator()->translate("Adresse email ne correspond pas avec votre demande."), 'error');
         $this->_getLogService()->log(LogService::ERR, "Email different de key {$sMail}", LogService::USER);
         return $this->redirect()->toRoute('forgetpass', array('action' => 'refactorpassword', 'key' => $aPost['key']));
     } elseif (strlen($aPost['password']) < 6) {
         $this->flashMessenger()->addMessage($this->_getServTranslator()->translate("Le mdp doit contenir un minimum de 8 caracteres."), 'error');
         $this->_getLogService()->log(LogService::ERR, "mdp trop court. {$sMail}", LogService::USER);
         return $this->redirect()->toRoute('forgetpass', array('action' => 'refactorpassword', 'key' => $aPost['key']));
     } elseif ($aPost['password'] !== $aPost['passwordconfirm']) {
         $this->flashMessenger()->addMessage($this->_getServTranslator()->translate("Les deux mots de passe ne corresponde pas."), 'error');
         $this->_getLogService()->log(LogService::ERR, "password different {$sMail}", LogService::USER);
         return $this->redirect()->toRoute('forgetpass', array('action' => 'refactorpassword', 'key' => $aPost['key']));
     } else {
         $bcrypt = new Bcrypt();
         $bcrypt->setCost(14);
         $hash = $bcrypt->create($aPost['password']);
         $this->getTableUsers()->updatepwd($hash, $sMail);
         $this->flashMessenger()->addMessage($this->_getServTranslator()->translate("Votre mot de passe a été mis à jour."), 'succes');
         $this->_getLogService()->log(LogService::ERR, "Mot de passe modifié pour {$sMail}", LogService::USER);
         return $this->redirect()->toRoute('home');
     }
 }
 public function updateAction()
 {
     $applicationConfig = $this->getServiceLocator()->get('config');
     $config = $applicationConfig['zf-oauth2-doctrine']['default'];
     $console = $this->getServiceLocator()->get('console');
     $objectManager = $this->getServiceLocator()->get($config['object_manager']);
     // Make sure that we are running in a console and the user has not tricked our
     // application into running this action from a public web server.
     $request = $this->getRequest();
     if (!$request instanceof ConsoleRequest) {
         throw new RuntimeException('You can only use this action from a console.');
     }
     $clientEntity = $objectManager->getRepository($config['mapping']['Client']['entity'])->find($this->getRequest()->getParam('id'));
     if (!$clientEntity) {
         $console->write("Client not found", Color::RED);
         return;
     }
     // Get the User
     while (true) {
         if ($clientEntity->getUser()) {
             $console->write("Current Value: " . $clientEntity->getUser()->getId() . "\n", Color::CYAN);
         } else {
             $console->write("Current Value: none\n", Color::CYAN);
         }
         $userId = Prompt\Line::prompt("User ID.  Not required. ? for list: ", true, 255);
         if ($userId == '?') {
             $users = $objectManager->getRepository($config['mapping']['User']['entity'])->findAll();
             foreach ($users as $user) {
                 $console->write($user->getId() . "\t" . $user->getEmail() . "\n", Color::CYAN);
             }
             continue;
         }
         if ($userId) {
             $user = $objectManager->getRepository($config['mapping']['User']['entity'])->find($userId);
             if (!$user) {
                 $console->write("User ID {$userId} not found.\n", Color::RED);
                 continue;
             }
             $clientEntity->setUser($user);
         }
         break;
     }
     // Get the client id
     $clientId = '';
     while (!$clientId) {
         $console->write("Current Value: " . $clientEntity->getClientId() . "\n", Color::CYAN);
         $clientId = Prompt\Line::prompt("Client ID: ", false, 255);
         $client = $objectManager->getRepository($config['mapping']['Client']['entity'])->findOneBy(array('clientId' => $clientId));
         if ($client && $client->getId() !== $clientEntity->getId()) {
             $console->write('Client ID ' . $clientId . ' already exists', Color::RED);
             $clientId = '';
         }
     }
     $clientEntity->setClientId($clientId);
     // Get the client secret
     $secret = '';
     $secretVerify = false;
     while ($secret !== $secretVerify) {
         $secretPrompt = new Prompt\Password("Secret: ");
         $secret = $secretPrompt->show();
         $secretPrompt = new Prompt\Password("Verify Secret: ");
         $secretVerify = $secretPrompt->show();
         if ($secret !== $secretVerify) {
             $console->write("Password verification does not match.  Please try again.\n", Color::YELLOW);
             continue;
         }
         $bcrypt = new Bcrypt();
         $bcrypt->setCost(14);
         $clientEntity->setSecret($bcrypt->create($secret));
     }
     // Get the Redirect URI
     $console->write("Current Value: " . $clientEntity->getRedirectUri() . "\n", Color::CYAN);
     $redirectUri = Prompt\Line::prompt("Redirect URI.  Not required: ", true, 255);
     $clientEntity->setRedirectUri($redirectUri);
     // Get Grant Type(s)
     $console->write("Current Value: " . implode(',', $clientEntity->getGrantType()) . "\n", Color::CYAN);
     $console->write("Default Grant Types\n", Color::YELLOW);
     $console->write("authorization_code\n", Color::CYAN);
     $console->write("access_token\n", Color::CYAN);
     $console->write("refresh_token\n", Color::CYAN);
     $console->write("urn:ietf:params:oauth:grant-type:jwt-bearer\n", Color::CYAN);
     $grantType = Prompt\Line::prompt("Grant Types, comma delimited.  Not required: ", true, 255);
     $clientEntity->setGrantType(explode(',', $grantType));
     // Add scope(s)
     $clientScopes = new ArrayCollection();
     while (true) {
         if (sizeof($clientEntity->getScope())) {
             $console->write("Current Scope(s)\n", Color::YELLOW);
             foreach ($clientEntity->getScope() as $scope) {
                 $console->write($scope->getScope() . "\n", Color::CYAN);
             }
         }
         $scopeArray = $objectManager->getRepository($config['mapping']['Scope']['entity'])->findBy(array(), array('id' => 'ASC'));
         $scopes = new ArrayCollection();
         foreach ($scopeArray as $scope) {
             if (!$clientScopes->contains($scope)) {
                 $scopes->add($scope);
             }
         }
         $options = array(0 => 'Done Selecting Scopes');
         foreach ($scopes as $scope) {
             $options[$scope->getId()] = $scope->getScope();
         }
         if (!$options) {
             $console->write("No Scopes exist.\n", Color::RED);
             break;
         }
         if (sizeof($clientScopes)) {
             $console->write("Selected Scopes\n", Color::YELLOW);
             foreach ($clientScopes as $scope) {
                 $console->write($scope->getScope() . "\n", Color::CYAN);
             }
         }
         $answer = Prompt\Select::prompt('Select Scope(s): ', $options, false, false);
         if (!$answer) {
             foreach ($clientEntity->getScope() as $scope) {
                 $scope->removeClient($clientEntity);
                 $clientEntity->removeScope($scope);
             }
             foreach ($clientScopes as $scope) {
                 $scope->addClient($clientEntity);
                 $clientEntity->addScope($scope);
             }
             break;
         } else {
             foreach ($scopes as $scope) {
                 if ($scope->getId() == $answer) {
                     $clientScopes->add($scope);
                     echo "{$answer} selected\n";
                     break;
                 }
             }
         }
     }
     $objectManager->flush();
     $console->write("Client updated\n", Color::GREEN);
 }