Create password.

@return JsonResponse
@Route("/password", name="users_password")
@Method("GET")
@ApiDoc(
description="Create password"
)
968611
public function passwordAction()
    {
        $minLength = $this->container->getParameter('phlexible_user.password.min_length');

        $generator = new PasswordGenerator();
        $password = $generator->create($minLength, PasswordGenerator::TYPE_UNPRONOUNCABLE);

        return new JsonResponse(
            [
                'password' => $password,
                'success' => true,
            ]
        );
    }
276230
public function postCreate()
	{
		$response = array(
			"method" => "create",
			"success" => false,
			"user" => "",
			"error_code" => 0,
			"error_message" => ""
		);

		try {
		    AuthorizerHelper::can(UserValidator::USER_CAN_SAVE);

            $data = json_decode(file_get_contents("php://input"));
            if (empty($data)) {
                $data = (object) $_POST;
            }

            $userModel = new User();

            // Check required fields
            $requiredParams = array('email', 'name', 'role', 'password');
            $params = (array) $data;
            foreach ($requiredParams as $param){
                if (empty($params[$param])) {
                    throw new \Exception(ucfirst($param) .' is required.');
                }
            }

            // Check Dupe email [ER-155]
            if(!empty($data->email)) {
                if (false === $userModel->isEmailUnique($data->email)) {
                    throw new \Exception("The email you entered already exists.");
                }
            }

            $userId = $userModel->save($data);

            if (empty($userId)) {
                throw  new \Exception('Could not create new user.');
            }
            $user = $userModel->getById($userId);
            $output = array('id'       => $user->getId(),
                            'email'    => $user->getEmail(),
                            'role'     => $this->getRoleInfo($user),
                            'name'     => $user->getName(),
                            'last_login' => $user->getLastLogin(),
                            'gateway_customer_id'=> $user->getGatewayCustomerId()
            );

			$response['user'] = $output;
			$response['success'] = true;
			$this->setStatusCode(200);
		} catch (\Exception $e) {
			$response['error_message'] = $e->getMessage();
			$response['error_code'] = $e->getCode();
		}

		$this->setContent($response);
	}
1284583
public function login()
    {
        // grab credentials from the request
        $credentials = Input::only('email', 'password');

        try {
            // attempt to verify the credentials and create a token for the user
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json(arrayView('phpsoft.users::errors/authenticate', [
                    'error' => 'Invalid Credentials.'
                ]), 401);
            }
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return response()->json(arrayView('phpsoft.users::errors/authenticate', [
                'error' => 'Could not create token.'
            ]), 500);
        }

        // all good so return the token
        return response()->json(arrayView('phpsoft.users::tokens/show', compact('token')));
    }
1082953
public function newPasswordAction($hash)
    {
        $user = $this->userManager->getByResetPasswordHash($hash);
        $form = $this->formFactory->create(FormFactory::TYPE_USER_RESET_PWD, array(), $user);
        $form->handleRequest($this->request);

        if ($form->isValid()) {
            $data = $form->getData();
            $plainPassword = $data->getPlainPassword();
            $user->setPlainPassword($plainPassword);
            $this->userManager->activateUser($user);
            $this->om->persist($user);
            $this->om->flush();
            $this->request->getSession()
                ->getFlashBag()
                ->add('warning', $this->translator->trans('password_ok', array(), 'platform'));

            return new RedirectResponse($this->router->generate('claro_security_login'));
        }

        return array(
            'hash' => $hash,
            'form' => $form->createView()
        );
    }
1707
public function store()
    {
        $password = Str::random();

        $input = array_merge(Binput::only(['first_name', 'last_name', 'email']), [
            'password'     => $password,
            'activated'    => true,
            'activated_at' => new DateTime(),
        ]);

        $rules = UserRepository::rules(array_keys($input));
        $rules['password'] = 'required|min:6';

        $val = UserRepository::validate($input, $rules, true);
        if ($val->fails()) {
            return Redirect::route('users.create')->withInput()->withErrors($val->errors());
        }

        try {
            $user = UserRepository::create($input);

            $groups = GroupRepository::index();
            foreach ($groups as $group) {
                if (Binput::get('group_'.$group->id) === 'on') {
                    $user->addGroup($group);
                }
            }

            $mail = [
                'url'      => URL::to(Config::get('credentials.home', '/')),
                'password' => $password,
                'email'    => $user->getLogin(),
                'subject'  => Config::get('app.name').' - New Account Information',
            ];

            Mail::queue('credentials::emails.newuser', $mail, function ($message) use ($mail) {
                $message->to($mail['email'])->subject($mail['subject']);
            });

            return Redirect::route('users.show', ['users' => $user->id])
                ->with('success', 'The user has been created successfully. Their password has been emailed to them.');
        } catch (UserExistsException $e) {
            return Redirect::route('users.create')->withInput()->withErrors($val->errors())
                ->with('error', 'That email address is taken.');
        }
    }
891211
public function resetPasswordAction(Request $request)
    {
        $widget = $request->isXmlHttpRequest();

        $passwordResetToken = $this->getPasswordResetToken($request->query->get('token'));

        $form = $this->getSecurityFormFactory()->createPasswordResetForm($passwordResetToken)->handleRequest($request);

        if (!$form->isSubmitted()) {
            return new Response($this->getSecurityFormRenderer()->renderPasswordResetForm($form, $widget));
        }

        $successMessage = 'security.action.reset_password.success';

        if (!$this->getSecurityFormHandler()->handlePasswordResetForm($form, !$widget, $successMessage)) {
            $html = $this->getSecurityFormRenderer()->renderPasswordResetForm($form, $widget);

            return $widget
                ? new AjaxResponse($html, false, FlashNotifierInterface::MESSAGE_FORM_ERROR)
                : new Response($html);
        }

        $url = $this->generateUrl($this->getParameter('darvin_user.already_logged_in_redirect_route'));

        return $widget
            ? new AjaxResponse('', true, $successMessage, [], $url)
            : $this->redirect($url);
    }
683860
public function createUser()
    {
        if ($this->getIsNewRecord() == false) {
            throw new \RuntimeException('Calling "' . __CLASS__ . '::' . __METHOD__ . '" on existing user');
        }
        $this->password = $this->password == null ? PasswordHelper::generate(8) : $this->password;
        $this->trigger(self::BEFORE_CREATE);
        if (!$this->save()) {
            return false;
        }
        $this->trigger(self::AFTER_CREATE);
        return true;
    }
444694
public function setPasswordAction()
    {
        $userId = $this->params()->fromRoute('userId', null);
        $token = $this->params()->fromRoute('token', null);

        if ($userId === null || $token === null) {
            return $this->notFoundAction();
        }

        $user = $this->getUserMapper()->findById($userId);

        if (!$user) {
            return $this->notFoundAction();
        }

        $record = $this->getUserRegistrationMapper()->findByUser($user);

        if (!$record ||  !$this->userRegistrationService->isTokenValid($user, $token, $record)) {
            // Invalid Token, Lets surprise the attacker
            return $this->notFoundAction();
        }

        if ($record->isResponded()) {
            // old link, password is already set by the user
            return $this->redirectToPostVerificationRoute();
        }

        $form = $this->getServiceLocator()->get('HtUserRegistration\SetPasswordForm');

        if ($this->getRequest()->isPost()) {
            $form->setData($this->getRequest()->getPost());
            if ($form->isValid()) {
                $this->userRegistrationService->setPassword($form->getData(), $record);

                return $this->redirectToPostVerificationRoute();
            }
        }

        return array(
            'user' => $user,
            'form' => $form
        );
    }
274803
protected function makePasswordGrant()
    {
        $grant = new PasswordGrant(
            $this->app->make(Bridge\UserRepository::class),
            $this->app->make(Bridge\RefreshTokenRepository::class)
        );

        $grant->setRefreshTokenTTL(Passport::refreshTokensExpireIn());

        return $grant;
    }
696524
public static function authenticate()
    {
        //if there is no username or password, fail
        if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
            return null;
        }

        // With a valid user and password, check the password is correct
        $data = [
            'Email' => $_SERVER['PHP_AUTH_USER'],
            'Password' => $_SERVER['PHP_AUTH_PW'],
        ];
        $request = Controller::curr()->getRequest();
        $authenticators = Security::singleton()->getApplicableAuthenticators(Authenticator::LOGIN);
        $member = null;
        foreach ($authenticators as $authenticator) {
            $member = $authenticator->authenticate($data, $request);
            if ($member) {
                break;
            }
        }
        return $member;
    }
1145103
public function request(Request $request)
    {
        $user = User::whereEmail($request->email)->firstOrFail();
        $user->sendResetPasswordNotification($this->broker()->createToken($user), $request);

        return response()->json('Password request successful', 200);
    }
319
public function login($username, $password)
	{
		$response = $this->http->get($this->getUrl('oauth2/access_token'), array(
			'grant_type'	=>	'password ',
			'username'		=>	$username,
			'password'		=>	$password,
			'client_id'		=>	$this->appid,
			'client_secret'	=>	$this->appSecret,
		));
		$this->result = $response->json(true);
		if(!isset($this->result['error_code']))
		{
			return $this->accessToken = $this->result['access_token'];
		}
		else
		{
			throw new ApiException(isset($this->result['error']) ? $this->result['error'] : '', $this->result['error_code']);
		}
	}
19591
def create_user(self, username, password, name, email):
        """"""
        method = 'POST'
        endpoint = '/rest/v1/users/{}'.format(self.client.sauce_username)
        body = json.dumps({'username': username, 'password': password,
                           'name': name, 'email': email, })
        return self.client.request(method, endpoint, body)
427215
public function resetPasswordAction(Request $request)
    {
        $groups = $this->decodeIdsString($request, Group::class);
        $this->om->startFlushSuite();
        $i = 0;

        foreach ($groups as $group) {
            foreach ($group->getUsers() as $user) {
                $this->container->get('claroline.manager.user_manager')->sendResetPassword($user);
                ++$i;

                if (0 === $i % 200) {
                    $this->om->forceFlush();
                }
            }
        }

        $this->om->endFlushSuite();

        return new JsonResponse();
    }
212115
protected function createComponentPasswordForm(): Form
	{
		$form = $this->formFactory->create();
		$form->setAjaxRequest();

		$form->addPassword('oldPassword', 'cms.user.oldPassword')
			->setRequired();

		$form->addPassword('password', 'cms.user.newPassword')
			->setRequired()
			->addRule(Form::MIN_LENGTH, null, $this->minPasswordLength);
		$form->addPassword('passwordVerify', 'cms.user.passwordVerify')
			->setRequired()
			->addRule(Form::EQUAL, null, $form['password']);

		$form->addProtection();

		$form->addSubmit('save', 'form.save');

		$form->onSuccess[] = [$this, 'passwordFormSucceeded'];

		return $form;
	}
710200
public function generatePasswordAction(Request $request)
    {
        $context = $this->loadContext($request);
        $resourceName = $this->config->getResourceName();
        /** @var \Ekyna\Bundle\UserBundle\Model\UserInterface $resource */
        $resource = $context->getResource($resourceName);

        $this->isGranted('EDIT', $resource);

        if (in_array('ROLE_SUPER_ADMIN', $resource->getGroup()->getRoles())) {
            throw new AccessDeniedHttpException();
        }

        $this->get('fos_user.user_manager')->generatePassword($resource);
        $password = $resource->getPlainPassword();

        $event = new UserEvent($resource);
        $event
            ->addMessage(new ResourceMessage(
                sprintf('Generated password : "%s".', $password),
                ResourceMessage::TYPE_INFO
            ))
            ->addData('password', $password)
        ;

        // TODO use ResourceManager
        $this->getOperator()->update($event);
        $event->toFlashes($this->getFlashBag());

        return $this->redirect($this->generateResourcePath($resource));
    }
1157143
public function password()
    {
        $this->setData('formTitle', __("Change password"));
        if ($this->getServiceLocator()->get(ApplicationService::SERVICE_ID)->isDemo()) {
            $this->setData('myForm', __('Unable to change passwords in demo mode'));
        } else {
            $myFormContainer = new tao_actions_form_UserPassword();
            $myForm = $myFormContainer->getForm();
            if($myForm->isSubmited()){
                if($myForm->isValid()){
                    $user = $this->getUserService()->getCurrentUser();
                    $this->getServiceLocator()->get(tao_models_classes_UserService::SERVICE_ID)
                        ->setPassword($user, $myForm->getValue('newpassword'));
                    $this->setData('message', __('Password changed'));
                }
            }
            $this->setData('myForm', $myForm->render());
        }

        $this->setView('form/settings_user.tpl');
    }