Change account email address.

@return \Illuminate\Http\RedirectResponse
545802
public function changeEmail(Request $request)
    {
        $this->validate(
            $request,
            [
                'email' => 'required|email',
            ]
        );

        if ($request->input('email') == Auth::user()->email) {
            return redirect()->back()->withErrors([
                'email' => trans('mustard::account.email_same'),
            ]);
        }

        if (User::findByEmail($request->input('email'))) {
            return redirect()->back()->withErrors([
                'email' => trans('mustard::account.email_exists'),
            ]);
        }

        // Notify the old email
        Auth::user()->sendEmail(
            trans('mustard::account.email_changed'),
            'mustard::emails.account.email-changed',
            ['new_email' => $request->input('email')]
        );

        Auth::user()->email = $request->input('email');

        if (method_exists('unverify', Auth::user())) {
            Auth::user()->unverify();
        }

        Auth::user()->save();

        return redirect()->back()->withStatus(trans('mustard::account.email_changed'));
    }
321537
public function postReset()
    {
        $input = Binput::only('email');

        $val = UserRepository::validate($input, array_keys($input));
        if ($val->fails()) {
            return Redirect::route('account.reset')->withInput()->withErrors($val->errors());
        }

        $this->throttler->hit();

        try {
            $user = Credentials::getUserProvider()->findByLogin($input['email']);

            $code = $user->getResetPasswordCode();

            $mail = [
                'link'    => URL::route('account.password', ['id'    => $user->id, 'code'    => $code]),
                'email'   => $user->getLogin(),
                'subject' => Config::get('app.name').' - Password Reset Confirmation',
            ];

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

            return Redirect::route('account.reset')
                ->with('success', 'Check your email for password reset information.');
        } catch (UserNotFoundException $e) {
            return Redirect::route('account.reset')
                ->with('error', 'That user does not exist.');
        }
    }
49518
public function changeUserEmail($uid, $newEmail): UserRecord
    {
        return $this->updateUser($uid, Request\UpdateUser::new()->withEmail($newEmail));
    }
133250
public function setToField() {

        // get the mapped recipient (valid because $this->isInboundEmailToEmailAddressMapToUser() is already done)
        $mappedRoutes = config('lasallecmsmailgun.inbound_map_mailgun_routes_with_user_email_address');

        foreach ($mappedRoutes as $route => $user) {

            // if "from" email address is the same as the route specified in the config...
            if ($this->request->input('recipient') == $route) {
                $userEmailAddress = $user;
            }
        }

        return $this->userRepository->findUserNameByEmail($userEmailAddress);
    }
1077529
public function resetPasswordAction()
    {
        if($user = $this->identity()) {
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }
    
        $user = new User;
        $form = $this->getUserFormHelper()->createUserForm($user, 'ResetPassword');
        $message = null;
        if($this->getRequest()->isPost()) {
            $form->setValidationGroup('csrf', 'captcha');
            $form->setData($this->getRequest()->getPost());
            if($form->isValid()) {
                $data = $form->getData();
                $usernameOrEmail = $this->params()->fromPost('usernameOrEmail');
                $entityManager = $this->getEntityManager();
                $user = $entityManager->createQuery("SELECT u FROM CsnUser\Entity\User u WHERE u.email = '$usernameOrEmail' OR u.username = '$usernameOrEmail'")->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT);
                $user = $user[0];
    
                if(isset($user)) {
                    try {
                        $user->setRegistrationToken(md5(uniqid(mt_rand(), true)));
                        $fullLink = $this->getBaseUrl() . $this->url()->fromRoute('user-register', array( 'action' => 'confirm-email-change-password', 'id' => $user->getRegistrationToken()));
                        $this->sendEmail(
                                $user->getEmail(),
                                $this->getTranslatorHelper()->translate('Please, confirm your request to change password!'),
                                sprintf($this->getTranslatorHelper()->translate('Hi, %s. Please, follow this link %s to confirm your request to change password.'), $user->getUsername(), $fullLink)
                        );
                        $entityManager->persist($user);
                        $entityManager->flush();
    
                        $viewModel = new ViewModel(array(
                            'email' => $user->getEmail(),
                            'navMenu' => $this->getOptions()->getNavMenu()
                        ));
    
                        $viewModel->setTemplate('csn-user/registration/password-change-success');
                        return $viewModel;
                    } catch (\Exception $e) {
                        return $this->getServiceLocator()->get('csnuser_error_view')->createErrorView(
                                $this->getTranslatorHelper()->translate('Something went wrong when trying to send activation email! Please, try again later.'),
                                $e,
                                $this->getOptions()->getDisplayExceptions(),
                                $this->getOptions()->getNavMenu()
                        );
                    }
                } else {
                    $message = 'The username or email is not valid!';
                }
            }
        }
    
        return new ViewModel(array('form' => $form, 'navMenu' => $this->getOptions()->getNavMenu(), 'message' => $message));
    }
385661
public function switchAction()
    {
        $lang = $this->getEvent()->getRouteMatch()->getParam('lang');
        $context = $this->getEvent()->getRouteMatch()->getParam('area');
        $redirect = (!empty($this->getEvent()->getRouteMatch()->getParam('redirect')))? urldecode($this->getEvent()->getRouteMatch()->getParam('redirect')) : '/'.$lang;

        $cookie = new \Zend\Http\Header\SetCookie('pg_locale_'.$context, $lang, time() + 60*60*24*365, '/');
        $this->getResponse()->getHeaders()->addHeader($cookie);

        return $this->redirect()->toUrl($redirect);
    }
145324
public function sendEmailAction()
    {
        $email = $this->container->get('request')->request->get('email');

        /**
         * @var $user UserInterface
         */
        $user = $this->container->get('fos_user.user_manager')->findUserByEmail($email);

        if (null === $user) {
            return $this->container->get('templating')->renderResponse(
                'FOSUserBundle:Resetting:request.html.'.$this->getEngine(),
                array('invalid_email' => $email)
            );
        }

        $code = $this->resetEmail($user);
        switch ($code) {
            case self::RESET_EMAIL_ALREADY_SENT:
                return $this->container->get('templating')->renderResponse(
                    'FOSUserBundle:Resetting:passwordAlreadyRequested.html.'.$this->getEngine()
                );
                break;
            case self::RESET_EMAIL_OK:
                return new RedirectResponse(
                    $this->container->get('router')->generate('fos_user_resetting_check_email')
                );
                break;
        }
    }
1238786
public function changeImportPositionAction()
    {
        $authResponse  = $this->checkAuth([AdminResources::IMPORT], [], [AccessManager::UPDATE]);
        if ($authResponse !== null) {
            return $authResponse;
        }

        $query = $this->getRequest()->query;

        $this->dispatch(
            TheliaEvents::IMPORT_CHANGE_POSITION,
            new UpdatePositionEvent(
                $query->get('id'),
                $this->matchPositionMode($query->get('mode')),
                $query->get('value')
            )
        );

        return $this->generateRedirectFromRoute('import.list');
    }
207591
public function setEmail($email): User
    {
        if ($this->email !== $email) {
            $this->email = $email;

            DB::table('user')
                ->where('user_id', '=', $this->user_id)
                ->update([
                    'email' => $email,
                ]);
        }

        return $this;
    }
475948
public function confirmEmailChangePasswordAction()
    {
      $token = $this->params()->fromRoute('id');
      try {
        $entityManager = $this->getEntityManager();
        if($token !== '' && $user = $entityManager->getRepository('CsnUser\Entity\User')->findOneBy(array('registrationToken' => $token))) {
          $user->setRegistrationToken(md5(uniqid(mt_rand(), true)));
          $password = $this->generatePassword();
          $user->setPassword(UserCredentialsService::encryptPassword($password));
          $email = $user->getEmail();
          $fullLink = $this->getBaseUrl() . $this->url()->fromRoute('user-index', array( 'action' => 'login'));
          $this->sendEmail(
              $user->getEmail(),
              'Your password has been changed!',
              sprintf($this->getTranslatorHelper()->translate('Hello again %s. Your new password is: %s. Please, follow this link %s to log in with your new password.'), $user->getUsername(), $password, $fullLink)
              
          );          
          $entityManager->persist($user);
          $entityManager->flush();
    
          $viewModel = new ViewModel(array(
              'email' => $email,
              'navMenu' => $this->getOptions()->getNavMenu()
          ));
          return $viewModel;
        } else {
          return $this->redirect()->toRoute('user-index');
        }
      } catch (\Exception $e) {
        return $this->getServiceLocator()->get('csnuser_error_view')->createErrorView(
            $this->getTranslatorHelper()->translate('An error occured during the confirmation of your password change! Please, try again later.'),
            $e,
            $this->getOptions()->getDisplayExceptions(),
            $this->getOptions()->getNavMenu()
        );
      }
    }
1066515
public function actionCancel()
    {
        /** @var \amnah\yii2\user\models\User $user */
        /** @var \amnah\yii2\user\models\UserToken $userToken */

        // find userToken of type email change
        $user = Yii::$app->user->identity;
        $userToken = $this->module->model("UserToken");
        $userToken = $userToken::findByUser($user->id, $userToken::TYPE_EMAIL_CHANGE);
        if ($userToken) {
            $userToken->delete();
            Yii::$app->session->setFlash("Cancel-success", Yii::t("user", "Email change cancelled"));
        }

        return $this->redirect(["/user/account"]);
    }
1263898
@POST
  @Path("{id}/email")
  @RolesAllowed({"ROLE_ADMIN"})
  public Response changeEmail(@PathParam("id") Long userId, EmailRequest request) {
    checkNotNull(userId);
    checkEmailFormat(request.getEmail());

    boolean isSuccess = userService.changeEmailAddress(userId, request.getEmail());
    return isSuccess ? Response.noContent().build() : Response.status(Response.Status.BAD_REQUEST).build();
  }
599872
protected function defaultEmailChange()
    {
        $this->user->unconfirmed_email = $this->email;
        /** @var UserToken $token */
        $token = new UserToken(['user_id' => $this->user->id, 'type' => UserToken::TYPE_CONFIRM_NEW_EMAIL]);
        $token->save(false);
        Yii::$app->sendMail($this->user->unconfirmed_email, Yii::t('yuncms', 'Confirm email change on {0}', Yii::$app->name), 'user/reconfirmation', ['user' => $this->user, 'token' => $token]);
        Yii::$app->session->setFlash('info', Yii::t('yuncms', 'A confirmation message has been sent to your new email address'));
    }
28589
public function setEmail($email)
    {
        $email = is_null($email) ? '' : $email;
        parent::setEmail($email);
        $this->setUsername($email);

        return $this;
    }
1292275
def send_username_changed_email(self, user):
        """"""

        # Verify config settings
        if not self.user_manager.USER_ENABLE_EMAIL: return
        if not self.user_manager.USER_SEND_USERNAME_CHANGED_EMAIL: return

        # Notification emails are sent to the user's primary email address
        user_or_user_email_object = self.user_manager.db_manager.get_primary_user_email_object(user)
        email = user_or_user_email_object.email

        # Render email from templates and send it via the configured EmailAdapter
        self._render_and_send_email(
            email,
            user,
            self.user_manager.USER_USERNAME_CHANGED_EMAIL_TEMPLATE,
        )
1253953
public function changepasswordAction()
    {
        // if the user isn't logged in, we can't change password
        if (!$this->zfcUserAuthentication()->hasIdentity()) {
            // redirect to the login redirect route
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }

        $form = $this->getChangePasswordForm();
        $prg = $this->prg(static::ROUTE_CHANGEPASSWD);

        $fm = $this->flashMessenger()->setNamespace('change-password')->getMessages();
        if (isset($fm[0])) {
            $status = $fm[0];
        } else {
            $status = null;
        }

        if ($prg instanceof Response) {
            return $prg;
        } elseif ($prg === false) {
            return array(
                'status' => $status,
                'changePasswordForm' => $form,
            );
        }

        $form->setData($prg);

        if (!$form->isValid()) {
            return array(
                'status' => false,
                'changePasswordForm' => $form,
            );
        }

        if (!$this->getUserService()->changePassword($form->getData())) {
            return array(
                'status' => false,
                'changePasswordForm' => $form,
            );
        }

        $this->flashMessenger()->setNamespace('change-password')->addMessage(true);
        return $this->redirect()->toRoute(static::ROUTE_CHANGEPASSWD);
    }
938922
public function update($id)
    {
        $input = Binput::only(['first_name', 'last_name', 'email']);

        $val = UserRepository::validate($input, array_keys($input));
        if ($val->fails()) {
            return Redirect::route('users.edit', ['users' => $id])
                ->withInput()->withErrors($val->errors());
        }

        $user = UserRepository::find($id);
        $this->checkUser($user);

        $email = $user['email'];

        $user->update($input);

        $groups = GroupRepository::index();

        $changed = false;

        foreach ($groups as $group) {
            if ($user->inGroup($group)) {
                if (Binput::get('group_'.$group->id) !== 'on') {
                    $user->removeGroup($group);
                    $changed = true;
                }
            } else {
                if (Binput::get('group_'.$group->id) === 'on') {
                    $user->addGroup($group);
                    $changed = true;
                }
            }
        }

        if ($email !== $input['email']) {
            $mail = [
                'old'     => $email,
                'new'     => $input['email'],
                'url'     => URL::to(Config::get('credentials.home', '/')),
                'subject' => Config::get('app.name').' - New Email Information',
            ];

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

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

        if ($changed) {
            $mail = [
                'url'     => URL::to(Config::get('credentials.home', '/')),
                'email'   => $input['email'],
                'subject' => Config::get('app.name').' - Group Membership Changes',
            ];

            Mail::queue('credentials::emails.groups', $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 updated successfully.');
    }