/**
  * @param Request $request
  *
  * @return \Symfony\Component\HttpFoundation\RedirectResponse
  */
 public function registerAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $user = new User();
     $form = $this->createFormBuilder($user, ['attr' => ['class' => 'form-inline']])->add('username', 'text', ['label' => 'Имя', 'attr' => ['class' => 'form-control']])->add('useremail', 'email', ['label' => 'E-Mail', 'attr' => ['class' => 'form-control']])->add('password', 'password', ['label' => 'Пароль', 'attr' => ['class' => 'form-control']])->add('save', 'submit', ['label' => 'Зарегистрироваться', 'attr' => ['class' => 'btn btn-primary']])->getForm();
     $form->handleRequest($request);
     if ($form->isSubmitted()) {
         $formData = $request->get('form');
         $role = new Role();
         $role->setName('ROLE_ADMIN');
         $em->persist($role);
         $user->setUserName($formData['username']);
         $user->setUserEmail($formData['useremail']);
         $user->setSalt(md5(time()));
         $user->setCreatedAt();
         $user->setStatus(1);
         $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
         $password = $encoder->encodePassword($formData['password'], $user->getSalt());
         $user->setPassword($password);
         $user->getUserRoles()->add($role);
         $item = new Item();
         $item->setUsername('system');
         $item->setUserEmail('*****@*****.**');
         $item->setMessage(sprintf('Приветствуем нового пользователя %s', $formData['username']));
         $item->setCreatedAt();
         $em->persist($user);
         $em->persist($item);
         $em->flush();
         return $this->redirectToRoute('jaya_test_web_homepage');
     } else {
         return $this->render('JayaTestWebBundle:Security:register.html.twig', ['form' => $form->createView()]);
     }
 }
Example #2
1
 public function newUserAction(Request $request, Application $app)
 {
     $form = $app['form.factory']->createBuilder('form')->add('forename', 'text', array('required' => false, 'attr' => array('class' => 'form-control')))->add('surname', 'text', array('required' => true, 'attr' => array('class' => 'form-control')))->add('address1', 'text', array('required' => false, 'attr' => array('class' => 'form-control')))->add('address2', 'text', array('required' => false, 'attr' => array('class' => 'form-control')))->add('address3', 'text', array('required' => false, 'attr' => array('class' => 'form-control')))->add('town', 'text', array('required' => false, 'attr' => array('class' => 'form-control')))->add('county', 'text', array('required' => false, 'attr' => array('class' => 'form-control')))->add('email', 'email', array('required' => true, 'attr' => array('class' => 'form-control')))->add('postcode', 'text', array('required' => false, 'attr' => array('class' => 'form-control')))->add('password', 'password', array('required' => true, 'attr' => array('class' => 'form-control')))->add('roles', 'choice', array('choices' => array('ROLE_USER' => 'ROLE_USER', 'ROLE_ADMIN' => 'ROLE_ADMIN'), 'required' => true, 'attr' => array('class' => 'form-control')))->add('submit', 'submit', array('attr' => array('class' => 'form-control')))->getForm();
     $form->handleRequest($request);
     if ($form->isValid()) {
         $data = $form->getData();
         $email = $data['email'];
         $result = $app['db']->fetchAll("SELECT * FROM user WHERE email = '{$email}'");
         // checks to see if email exists
         if ($result) {
             // if the email exists
             $status = "I'm afraid that email address is already on the system";
             return $app['twig']->render('newuser.twig', array('status' => $status, 'form' => $form->createView()));
         } else {
             $password = $data['password'];
             $encoder = new MessageDigestPasswordEncoder();
             $password = $encoder->encodePassword($password, '');
             $app['db']->insert('user', array('password' => $password, 'forename' => $data['forename'], 'surname' => $data['surname'], 'address1' => $data['address1'], 'address2' => $data['address2'], 'address3' => $data['address3'], 'town' => $data['town'], 'county' => $data['county'], 'email' => $data['email'], 'postcode' => $data['postcode'], 'roles' => $data['roles'], 'verified' => "1"));
             $email = $data['email'];
             $newresult = $app['db']->fetchAll("SELECT usercode FROM user WHERE email = '{$email}'");
             foreach ($newresult as $shownewresult) {
                 $newusercode = $shownewresult['usercode'];
                 return $app->redirect("/users/{$newusercode}");
             }
             return $app['twig']->render('newuser.twig', array('status' => $status, 'form' => $form->createView()));
         }
     }
     return $app['twig']->render('newuser.twig', array('form' => $form->createView()));
 }
Example #3
0
 public function load(ObjectManager $manager)
 {
     $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
     $admin = new User();
     $admin->setUsername('messi');
     // On cré un salt pour amélioré la sécurité
     $admin->setPassword($encoder->encodePassword('admin', $admin->getSalt()));
     $admin->setEmail('*****@*****.**');
     $admin->setRoles(array('ROLE_ADMIN'));
     $admin->setEnabled(true);
     $user = new User();
     $user->setUsername('louis');
     // On cré un salt pour amélioré la sécurité
     $user->setPassword($encoder->encodePassword('michel', $user->getSalt()));
     $user->setEmail('*****@*****.**');
     $user->setRoles(array('ROLE_AUTEUR'));
     $user->setEnabled(true);
     $validPassword = $encoder->isPasswordValid($user->getPassword(), 'michel', $user->getSalt());
     if ($validPassword) {
         $manager->persist($admin);
         $manager->persist($user);
     }
     // On déclenche l'enregistrement
     $manager->flush();
 }
Example #4
0
 public function load(ObjectManager $manager)
 {
     $role = new Role();
     $role->setName('IS_AUTHENTICATED_ANONYMOUSLY');
     $manager->persist($role);
     $manager->flush();
     $role = new Role();
     $role->setName('ROLE_USER');
     $manager->persist($role);
     $manager->flush();
     $role = new Role();
     $role->setName('ROLE_ADMIN');
     $manager->persist($role);
     $manager->flush();
     $user = new User();
     $user->setEmail('test-1');
     $user->setSalt(md5(time()));
     $user->setIsActive(true);
     $user->getUserRoles()->add($role);
     $encoder = new MessageDigestPasswordEncoder('sha1', true, 10);
     $password = $encoder->encodePassword('admin', $user->getSalt());
     $user->setPassword($password);
     $manager->persist($user);
     $manager->flush();
 }
 public function testGetEncoderConfiguredForConcreteClassWithClassName()
 {
     $factory = new EncoderFactory(array('Symfony\\Component\\Security\\Tests\\Core\\Encoder\\SomeUser' => new MessageDigestPasswordEncoder('sha1')));
     $encoder = $factory->getEncoder('Symfony\\Component\\Security\\Tests\\Core\\Encoder\\SomeChildUser');
     $expectedEncoder = new MessageDigestPasswordEncoder('sha1');
     $this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', ''));
 }
 public function resetPasswordAction(Request $request)
 {
     $token = urldecode($request->get('token'));
     $passwordResetService = $this->get('buggl_main.password_reset_service');
     if (!$passwordResetService->validateToken($token)) {
         return new RedirectResponse($this->generateUrl('buggl_password_reset_invalid'));
     }
     $form = $this->createFormBuilder()->add('email', 'email', array('constraints' => new Email(array('message' => 'Not a valid email address.'))))->add('password', 'repeated', array('type' => 'password', 'options' => array('max_length' => 20), 'invalid_message' => 'Passwords did not match!'))->getForm();
     if ($request->getMethod() == 'POST') {
         $form->bindRequest($request);
         if ($form->isValid()) {
             $data = $form->getData();
             if ($passwordResetService->matchEmails($token, $data['email'])) {
                 $encoder = new MessageDigestPasswordEncoder();
                 $data['password'] = $encoder->encodePassword($data['password'], '');
                 $constants = $this->get('buggl_main.constants');
                 $user = $passwordResetService->updatePassword($data, $constants->get('LOCAL_AUTHOR'));
                 $passwordResetService->invalidatePasswordResetInfo($token);
                 $token = new UsernamePasswordToken($user, null, $user->getFireWall(), $user->getRoles());
                 $this->get('security.context')->setToken($token);
                 try {
                     $request = $this->container->get('request')->getSession()->set('_security_secured_area', serialize($token));
                 } catch (InactiveScopeException $e) {
                 }
                 return new RedirectResponse($this->generateUrl('local_author_dashboard'));
             } else {
                 $form->get('email')->addError(new FormError('The email address does not match the email you used to request password reset.'));
             }
         }
     }
     return $this->render('BugglMainBundle:Frontend/PasswordReset:passwordReset.html.twig', array('form' => $form->createView()));
 }
Example #7
0
 /**
  * @Route("/admin-login", name="admin-login")
  * @Template()
  */
 public function loginAction()
 {
     // создание пользователя
     $manager = $this->getDoctrine()->getManager();
     $user = new User();
     $user->setUsername('admin');
     $user->setSalt(md5(time()));
     $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
     $password = $encoder->encodePassword('admin', $user->getSalt());
     $user->setPassword($password);
     $user->setRoles('ROLE_OPERATOR');
     $user->setLastName('admin');
     $user->setFirstName('admin');
     $user->setSurName('admin');
     $user->setPhone('+79161111111');
     //
     $manager->persist($user);
     $manager->flush($user);
     if ($this->get('request')->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
         $error = $this->get('request')->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
     } else {
         $error = $this->get('request')->getSession()->get(SecurityContext::AUTHENTICATION_ERROR);
     }
     $pages = $this->getDoctrine()->getRepository('AppBundle:Page')->findAll();
     return array('error' => $error, 'pages' => $pages);
 }
 /**
  * @Route("/register")
  * @Method({"POST"})
  */
 public function registerAction()
 {
     $em = $this->getDoctrine()->getManager();
     $user = new User();
     $form = $this->createForm(new UserType(), $user);
     $jsonData = json_decode($this->getRequest()->getContent(), true);
     $form->bind($jsonData);
     if ($form->isValid()) {
         if ($em->getRepository('TodoBundle:User')->findOneBy(array('username' => $user->getUsername()))) {
             return $this->jsonResponse(array('code' => '2101', 'message' => 'username already used.'), 400);
         }
         $passencoder = new MessageDigestPasswordEncoder();
         $user->setPassword($passencoder->encodePassword($user->getPassword(), 'salt'));
         $em->persist($user);
         $em->flush();
         $response = new Response();
         $response->setStatusCode(201);
         return $response;
     } else {
         $messages = array();
         foreach ($form as $field) {
             if ($field->getErrors()) {
                 //$errors['']
                 foreach ($field->getErrors() as $error) {
                     $messages[$field->getName()] = $error->getMessage();
                 }
             }
         }
         return $this->jsonResponse(array('code' => '2100', 'message' => 'Invalid user form.', 'errors' => $messages), 400);
     }
 }
Example #9
0
 /**
  * Saves the user to the database.
  *
  * @param \MusicBox\Entity\User $user
  */
 public function save($user)
 {
     $userData = array('username' => $user->getUsername(), 'mail' => $user->getMail(), 'role' => $user->getRole());
     // If the password was changed, re-encrypt it.
     if (strlen($user->getPassword()) != 88) {
         $userData['salt'] = uniqid(mt_rand());
         $userData['password'] = $this->encoder->encodePassword($user->getPassword(), $userData['salt']);
     }
     if ($user->getId()) {
         // If a new image was uploaded, make sure the filename gets set.
         $newFile = $this->handleFileUpload($user);
         if ($newFile) {
             $userData['image'] = $user->getImage();
         }
         $this->db->update('users', $userData, array('user_id' => $user->getId()));
     } else {
         // The user is new, note the creation timestamp.
         $userData['created_at'] = time();
         $this->db->insert('users', $userData);
         // Get the id of the newly created user and set it on the entity.
         $id = $this->db->lastInsertId();
         $user->setId($id);
         // If a new image was uploaded, update the user with the new
         // filename.
         $newFile = $this->handleFileUpload($user);
         if ($newFile) {
             $newData = array('image' => $user->getImage());
             $this->db->update('users', $newData, array('user_id' => $id));
         }
     }
 }
 public function testGetEncoderWithService()
 {
     $factory = new EncoderFactory(array('Symfony\\Component\\Security\\Core\\User\\UserInterface' => new MessageDigestPasswordEncoder('sha1')));
     $encoder = $factory->getEncoder($this->getMock('Symfony\\Component\\Security\\Core\\User\\UserInterface'));
     $expectedEncoder = new MessageDigestPasswordEncoder('sha1');
     $this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', ''));
 }
Example #11
0
 public function register($username, $password, array $roles, $avatar)
 {
     $encoder = new MessageDigestPasswordEncoder();
     // FIXME use salt
     $salt = null;
     $this->db->insert('users', array('username' => $username, 'password' => $encoder->encodePassword($password, $salt), 'roles' => implode(',', $roles), 'avatar' => $avatar));
     // FIXME a little brutal ;-)
     return $this->loadUserByUsername($username);
 }
 /**
  * @covers FOS\UserBundle\Security\Encoder\EncoderFactory::getEncoder
  * @covers FOS\UserBundle\Security\Encoder\EncoderFactory::createFosEncoder
  */
 public function testGetEncoderWithUserAccount()
 {
     $factory = new EncoderFactory('Symfony\\Component\\Security\\Core\\Encoder\\MessageDigestPasswordEncoder', false, 1, $this->getMock('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface'));
     $userAccount = $this->getMock('FOS\\UserBundle\\Model\\UserInterface');
     $userAccount->expects($this->once())->method('getAlgorithm')->will($this->returnValue('sha512'));
     $encoder = $factory->getEncoder($userAccount);
     $expectedEncoder = new MessageDigestPasswordEncoder('sha512', false, 1);
     $this->assertEquals($expectedEncoder->encodePassword('foo', 'bar'), $encoder->encodePassword('foo', 'bar'));
 }
Example #13
0
 public function load(ObjectManager $manager)
 {
     // Liste des noms de catégorie à ajouter
     $role_employe = new Role("ROLE_EMPLOYE");
     $manager->persist($role_employe);
     $manager->flush();
     $role_gestionnaire = new Role("ROLE_GESTIONNAIRE");
     $manager->persist($role_gestionnaire);
     $manager->flush();
     $role_admin = new Role("ROLE_ADMIN");
     $manager->persist($role_admin);
     $manager->flush();
     $role_superadmin = new Role("ROLE_SUPER_ADMIN");
     $manager->persist($role_superadmin);
     $manager->flush();
     $user = new User();
     $user->setNom("Njomo Rostand");
     $user->setVilleResidence("Yaounde");
     $user->setNoPieceIdent("123456789");
     $user->setPoste("Stagiare");
     $user->setUsername("rostand");
     $user->setSalt(md5(time()));
     $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
     $password = $encoder->encodePassword('rostand', $user->getSalt());
     $user->setPassword($password);
     $user->addRole($role_employe);
     $manager->persist($user);
     $manager->flush();
     $user = new User();
     $user->setNom("Marlone NJ");
     $user->setVilleResidence("Douala");
     $user->setNoPieceIdent("9874563210");
     $user->setPoste("Gestionnaire de credit");
     $user->setUsername("marlone");
     $user->setSalt(md5(time()));
     $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
     $password = $encoder->encodePassword('marlone', $user->getSalt());
     $user->setPassword($password);
     $user->addRole($role_gestionnaire);
     $manager->persist($user);
     $manager->flush();
     $user = new User();
     $user->setNom("Rostand  Nj");
     $user->setVilleResidence("Buea");
     $user->setNoPieceIdent("123456789");
     $user->setPoste("Dj internationnal");
     $user->setUsername("rostandnj");
     $user->setSalt(md5(time()));
     $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
     $password = $encoder->encodePassword('rostandnj', $user->getSalt());
     $user->setPassword($password);
     $user->addRole($role_admin);
     $manager->persist($user);
     $manager->flush();
 }
Example #14
0
 public function saveUser(Users $user, ObjectManager $manager)
 {
     $user->setSalt(md5(time()));
     // шифрует и устанавливает пароль для пользователя,
     // эти настройки совпадают с конфигурационными файлами
     $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
     $password = $encoder->encodePassword($user->getPassword(), $user->getSalt());
     $user->setPassword($password);
     $manager->persist($user);
     $manager->flush();
 }
Example #15
0
 public function indexAction(Request $request, Application $app)
 {
     $params = array('password' => null, 'encodedPassword' => null);
     if ($password = $request->getSession()->get('password', null)) {
         $params['password'] = $password;
         $encoder = new MessageDigestPasswordEncoder();
         $params['encodedPassword'] = $encoder->encodePassword($password, '');
         $request->getSession()->remove('password');
     }
     return $app['twig']->render('admin/dashboard.twig', $params);
 }
Example #16
0
 public function load(ObjectManager $manager)
 {
     $admin = new User(array('ROLE_ADMIN'));
     $admin->setName('admin');
     $admin->setEmail('*****@*****.**');
     $admin->setSalt(md5(time()));
     $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
     $password = $encoder->encodePassword('123456', $admin->getSalt());
     $admin->setPassword($password);
     $manager->persist($admin);
     $manager->flush();
 }
 /**
  * @dataProvider userProvider
  *
  * @param UserInterface $user
  * @param               $secret
  * @param string        $salt
  */
 public function testOverridesLogic(UserInterface $user, $secret, $salt = '')
 {
     $this->userProvider->expects($this->exactly(2))->method('loadUserByUsername')->will($this->returnValue($user));
     $nonce = base64_encode(uniqid(self::TEST_NONCE));
     $time = date('Y-m-d H:i:s');
     $digest = $this->encoder->encodePassword(sprintf('%s%s%s', base64_decode($nonce), $time, $secret), $salt);
     $token = new Token();
     $token->setAttribute('digest', $digest);
     $token->setAttribute('nonce', $nonce);
     $token->setAttribute('created', $time);
     $this->provider->authenticate($token);
 }
 public function load(ObjectManager $manager)
 {
     $user = new \Liip\FooBundle\Entity\User();
     $user->setName('foo bar');
     $user->setEmail('*****@*****.**');
     // Set according to your security context settings
     $encoder = new MessageDigestPasswordEncoder('sha1', true, 3);
     $user->setPassword($encoder->encodePassword('12341234', $user->getSalt()));
     $user->setAlgorithm('sha1');
     $user->setEnabled(true);
     $user->setConfirmationToken(null);
     $manager->persist($user);
     $manager->flush();
 }
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln('checking');
     $encoder = new MessageDigestPasswordEncoder();
     $entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
     $result = $entityManager->getRepository('BugglMainBundle:AdminUsers')->findOneBy(array('username' => $input->getArgument('username'), 'password' => $encoder->encodePassword($input->getArgument('password'), '')));
     if (!is_null($result)) {
         $password = $encoder->encodePassword($input->getArgument('newPassword'), '');
         $result->setPassword($password);
         $entityManager->flush();
         $output->writeln('password updated');
     } else {
         $output->writeln('failed!');
     }
 }
 public function indexAction(Request $request)
 {
     $sobiratel = $this->getUser();
     $form = $this->createForm(new RegistrationType(), $sobiratel);
     if ($request->getMethod() == 'POST') {
         $form->handleRequest($request);
         $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
         $password = $encoder->encodePassword($sobiratel->getPassword(), $sobiratel->getSalt());
         $sobiratel->setPassword($password);
         if ($form->isValid()) {
             $em->flush();
         }
     }
     return $this->render('DialectBundle:Security:registration.html.twig', array('form' => $form->createView(), 'flag' => 'sobiratel'));
 }
Example #21
0
 /**
  * @param string $raw
  * @param string $salt
  * @return string
  */
 public function encodePassword($raw, $salt)
 {
     switch ($this->method) {
         case 'none':
             $defaultEncoder = new PlaintextPasswordEncoder();
             break;
         case 'bcrypt':
             $defaultEncoder = new BCryptPasswordEncoder(4);
             break;
         case 'sha1':
         case 'md5':
             $defaultEncoder = new MessageDigestPasswordEncoder($this->method, false, 1);
             break;
     }
     return $defaultEncoder->encodePassword($raw, $salt);
 }
 /**
  * Digest
  * @param string $token
  * @param string $uid
  * @param string $key
  * @param string $roles
  * @return string
  */
 function digest($token, $uid, $key, $roles)
 {
     $token = str_replace("&=&", "/", $token);
     $key = str_replace("&=&", "/", $key);
     $uid = str_replace("&=&", "/", $uid);
     $roles = str_replace("&=&", "/", $roles);
     $digest = new MessageDigestPasswordEncoder();
     $privatekey = $digest->encodePassword($this->getParameter('api_domain'), $token);
     if (strlen($privatekey) > 32) {
         $privatekey = substr($privatekey, 0, 32);
     }
     $this->setKey($privatekey);
     $data[] = $this->decrypt($uid);
     $data[] = $this->decrypt($key);
     $data[] = (array) $this->decrypt($roles);
     return $data;
 }
 /**
  * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationException
  */
 public function testGetSecret()
 {
     $noApiKeyUser = $this->getMock('Oro\\Bundle\\UserBundle\\Entity\\User');
     $noApiKeyUser->expects(static::exactly(2))->method('getApiKeys')->will(static::returnValue(new ArrayCollection()));
     $noApiKeyUser->expects(static::never())->method('getPassword');
     $noApiKeyUser->expects(static::never())->method('getSalt');
     $noApiKeyUser->expects(static::any())->method('getRoles')->will(static::returnValue([]));
     $this->userProvider->expects(static::exactly(2))->method('loadUserByUsername')->will(static::returnValue($noApiKeyUser));
     $nonce = base64_encode(uniqid(self::TEST_NONCE));
     $time = date('Y-m-d H:i:s');
     $digest = $this->encoder->encodePassword(sprintf('%s%s%s', base64_decode($nonce), $time, ''), '');
     $token = new Token();
     $token->setAttribute('digest', $digest);
     $token->setAttribute('nonce', $nonce);
     $token->setAttribute('created', $time);
     $this->provider->authenticate($token);
 }
Example #24
0
 public function save(User $user)
 {
     $data = ['id' => $user->getId(), 'firstname' => $user->getFirstname(), 'surname' => $user->getSurname(), 'email' => $user->getEmail()];
     if (strlen($user->getPassword()) != 88) {
         $data['salt'] = uniqid(mt_rand());
         $data['password'] = $this->encoder->encodePassword($user->getPassword(), $data['salt']);
     }
     if ($user->getId()) {
         $this->db->update('users', $data, ['id' => $user->getId()]);
     } else {
         $data['c_date'] = date('Y-m-d H:i:s');
         $this->db->insert('users', $data);
         $user->setCDate($data['c_date']);
         $id = $this->db->lastInsertId();
         $user->setId($id)->setSalt($data['salt'])->setPassword($data['password']);
     }
 }
Example #25
0
 public function saveUserAction(Request $request)
 {
     var_dump($request->get('username'));
     die;
     $data = $request->request->all();
     $user = new Users();
     $form = $this->createForm(new UsersType(), $user);
     $form->submit($data);
     $user->setSalt(md5(time()));
     $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
     $password = $encoder->encodePassword($user->getPassword(), $user->getSalt());
     $user->setPassword($password);
     $em = $this->getDoctrine()->getManager();
     $em->persist($user);
     $em->flush();
     $users = $this->getDoctrine()->getRepository('AppBundle:Users')->findAll();
     return $this->render('admin2/admin.html.twig', array('users' => $users));
 }
 public function registrationAction(Request $request)
 {
     $error_message = "";
     $roles = array('ROLE_USER');
     $user = new User($roles);
     $form = $this->createFormBuilder($user)->add('password', 'password')->add('email', 'email')->add('register', 'submit')->getForm();
     $form->handleRequest($request);
     // TODO if password empty - generate password
     $em = $this->getDoctrine()->getManager();
     if ($form->isValid()) {
         // TODO валидация на уникальность емейла
         $redis = $this->container->get('pdl.phpredis.twitter');
         $email = $form['email']->getData();
         $salt = md5(time());
         $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
         $password = $encoder->encodePassword($form['password']->getData(), $user->getSalt());
         $data = ['salt' => $salt, 'password' => $password, 'roles' => $user->getRoles()];
         $redis->hMset('user:'******'email']->getData());
                     $user->setSalt(md5(time()));
                     $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
                     $password = $encoder->encodePassword($form['password']->getData(), $user->getSalt());
                     $user->setPassword($password);
         
                     $em->persist($user);
                     $em->flush();*/
         // send email with login-password
         /*            $site_mail = $this->container->getParameter('admin_email');
                     $message = \Swift_Message::newInstance()
                         ->setSubject('Регистрация')
                         ->setFrom($site_mail)
                         ->setTo($user->getEmail())
                         ->setBody(
                             $this->renderView(
                                 'VGUserBundle:Security:register.email.txt.twig',
                                 array('login' => $user->getEmail(), 'password'=>$form['password']->getData())
                             )
                         )
                     ;
                     $this->get('mailer')->send($message);*/
         return $this->redirect($this->generateUrl('login_path'));
     }
     return $this->render('VGUserBundle:Security:registration.html.twig', array('form' => $form->createView(), 'error_message' => $error_message));
 }
Example #27
0
 public function load($manager)
 {
     // create the ROLE_ADMIN role
     $role = new Role();
     $role->setName('ROLE_ADMIN');
     $manager->persist($role);
     // create a user
     $user = new User();
     $user->setFirstName('John');
     $user->setLastName('Doe');
     $user->setEmail('*****@*****.**');
     $user->setUsername('john.doe');
     $user->setSalt(md5(time()));
     // encode and set the password for the user,
     // these settings match our config
     $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
     $password = $encoder->encodePassword('admin', $user->getSalt());
     $user->setPassword($password);
     $user->getUserRoles()->add($role);
     $manager->persist($user);
     // create the tags
     $tag1 = new Tag();
     $tag1->setName('lorem');
     $manager->persist($tag1);
     $tag2 = new Tag();
     $tag2->setName('ipsum');
     $manager->persist($tag2);
     $cat1 = new Category();
     $cat1->setName('Programming');
     $manager->persist($cat1);
     // create 10 posts
     $tags = array($tag1, $tag2);
     for ($i = 0; $i < 10; ++$i) {
         $post = new Post();
         $post->setCategory($cat1);
         $post->setUser($user);
         $post->setTitle('Lorem Ipsum Dolor Sit Amet ' . $i);
         $post->setSlug('lorem-ipsum-dolor-sit-amet ' . $i);
         $post->setContent('Proin auctor augue enim? Integer adipiscing dolor odio proin? ' . 'In placerat arcu, turpis turpis et rhoncus? Et integer nascetur ' . 'arcu! Turpis scelerisque tincidunt proin mauris, dignissim duis ' . 'enim, ac sagittis auctor eu, ut penatibus nunc rhoncus magna ' . 'dignissim ut elementum est non! Urna scelerisque auctor, massa ' . 'turpis parturient, nisi, in tristique amet, lectus montes. ' . 'Facilisis, nunc? Diam ac, urna sed, sit magna turpis turpis ' . 'tincidunt porta. Tincidunt porta vut dis adipiscing phasellus, ' . 'a habitasse vut proin vel habitasse cras placerat, auctor, massa ' . 'ridiculus adipiscing ac duis a porta? Pulvinar in scelerisque, ' . 'adipiscing, arcu integer lorem odio est pellentesque adipiscing ' . 'velit. A, et porta, eros pulvinar! Nisi turpis mattis lundium ac ' . 'non nunc phasellus penatibus ut magna rhoncus dolor, lundium ultrices.');
         $post->getTags()->add($tags[rand(0, 1)]);
         $manager->persist($post);
     }
     $manager->flush();
 }
Example #28
0
 public function create($form, $param)
 {
     $error = null;
     // $member = new User2();
     $member = new User2();
     $em = $this->container->get('doctrine')->getManager();
     $repo = $em->getRepository('Bundles\\StoreBundle\\Entity\\User2');
     $checkLogin = $repo->findOneBy(array('username' => $form->get('username')->getData()));
     if (isset($param['ref'])) {
         $refferal = $repo->findOneBy(array('referralCode' => $param['ref']));
         if (!$refferal) {
             $error = 'Not correct ref code.Please dont input this field or input correct data';
             return $error;
         }
     }
     if (isset($checkLogin)) {
         $error = 'Уже существует такой пользователь';
         return $error;
     }
     if (strlen($form->get('password')->getData()) < 6) {
         $error = 'Не слишком короткий пароль мин 6 символов';
         return $error;
     }
     if (!preg_match("/^([a-zA-Zа-яА-Я]]+|[^0-9]+)\$/i", $form->get('firstname')->getData())) {
         $error = 'Можно вводить только числа и только слова';
         return $error;
     }
     $email = $form->get('email')->getData();
     // создание пользователя
     $member->setEmail($email)->setUsername(trim($form->get('username')->getData()))->setFirstname(trim($form->get('firstname')->getData()))->setLastname(trim($form->get('lastname')->getData()))->setSalt(md5(time()))->setStatus($param['status']);
     // шифрует и устанавливает пароль для пользователя,
     // эти настройки совпадают с конфигурационными файлами
     $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);
     $password = $encoder->encodePassword($form->get('password')->getData(), $member->getSalt());
     $member->setPassword($password);
     $em->persist($member);
     if (isset($refferal)) {
         $ref = new Stat();
         $ref->setRefId($refferal->getId());
         $ref->setUser2($member);
         $em->persist($ref);
     }
     $em->flush();
 }
Example #29
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $username = $input->getArgument('username');
     $password = $input->getArgument('password');
     $hosts = $input->getArgument('hosts');
     $passwordGenerator = new MessageDigestPasswordEncoder();
     $salt = "";
     $encodePassword = $passwordGenerator->encodePassword($password, $salt);
     $filename = __DIR__ . '/../../../config/parameters.yml';
     $yaml = Yaml::parse($filename);
     $users = isset($yaml['secure']['users']) ? $yaml['secure']['users'] : array();
     if ($hosts) {
         if ($hosts == "") {
             $hosts = ".*";
         }
         preg_match("/" . $hosts . "/", "my test string for regexp");
         if (preg_last_error() != PREG_NO_ERROR) {
             $output->writeln("<error>Wrong regular expression! Code " . preg_last_error() . "</error>");
             return;
         }
         $users[$username] = array('password' => $encodePassword, 'hosts' => $hosts);
     } else {
         $users[$username] = array('password' => $encodePassword);
     }
     $newYaml = array();
     //copy other sections
     foreach ($yaml as $key => $section) {
         if ($key != 'secure') {
             $newYaml[$key] = $section;
         }
     }
     $newYaml['secure'] = array('enable' => isset($yaml['secure']['enable']) ? $yaml['secure']['enable'] : true, 'users' => $users);
     $dumper = new Dumper();
     $newFile = $dumper->dump($newYaml, 5);
     $oldFilename = $filename . '~' . substr(md5(rand()), 0, 5);
     if (!copy($filename, $oldFilename)) {
         $output->writeln("<error>Error during the backup configuration file</error>");
     } else {
         $output->writeln("<info>Old configuration has been saved to file {$oldFilename}</info>");
         file_put_contents($filename, $newFile);
         $output->writeln("<info>The configuration file is updated successfully</info>");
     }
 }
Example #30
0
 public function newCustomer(Request $request, Application $app)
 {
     if (!$request->get('forename')) {
         return $app->redirect('/');
     } else {
         $forename = $request->get('forename');
         $surname = $request->get('surname');
         $password = $request->get('password');
         $email = $request->get('email');
         //   $checkbox = $request->get('checkbox');
         $result = $app['db']->fetchAll("SELECT * FROM user WHERE email = '{$email}'");
         // checks to see if email exists
         if ($result) {
             // if the email exists
             $data = array('usercode' => "EMAILHERE");
             // sets it to email here, so it throws an error to user
         } else {
             $encoder = new MessageDigestPasswordEncoder();
             $password = $encoder->encodePassword($password, '');
             $app['db']->insert('user', array('forename' => $forename, 'surname' => $surname, 'password' => $password, 'email' => $email));
             $result = $app['db']->fetchAll("SELECT * FROM user WHERE email = '{$email}'");
             foreach ($result as $row) {
                 $usercode = $row['usercode'];
                 $points = $row['points'];
                 if ($points == 1) {
                     $plural = "point";
                 } else {
                     $plural = "points";
                 }
             }
             $data = array("email" => "{$email}", "password" => "{$password}", "forename" => "{$forename}", "surname" => "{$surname}", "usercode" => "{$usercode}", "points" => "{$points}", "plural" => "{$plural}");
             $encodeusercode = $app['passwordencoder']->encodePassword($usercode, '');
             $encodeusercode = str_replace('+', 'ASD20', $encodeusercode);
             $encodeusercode = str_replace('_', 'ASD5F', $encodeusercode);
             $encodeusercode = str_replace('.', 'ASD2E', $encodeusercode);
             $encodeusercode = str_replace('-', 'ASD2D', $encodeusercode);
             $encodeusercode = str_replace('/', 'ASD2G', $encodeusercode);
             $message = \Swift_Message::newInstance()->setSubject('Welcome to The Durrant App')->setFrom(array('*****@*****.**'))->setTo(array("{$email}"))->setBody("Welcome to the Durrant App")->addPart("<html>\n                                <body>\n                                <p>Dear {$forename} {$surname}</p>Thank you for registering with the Durrant App</p>\n                                <p>Please quote this email address or usercode: {$usercode} to the Receptionist when acquiring points.</p>\n                                <p>Could you please click this link to confirm your membership</p>\n                                <a href = 'http://adstuff.esy.es/verifyemail?name={$encodeusercode}'>http://app.durrant.iwsclients.co.uk/verifyemail?name={$encodeusercode}</a>\n                                <p>Regards Durrant House Hotel</p>\n                                <p>Please Ensure that you continue to receive the quality information from us that you enjoy by adding us to your contact list</p>\n                                </body>\n                                </html>", 'text/html');
             $app['mailer']->send($message);
         }
     }
     return json_encode($data);
 }