How to update user data in Principal when changing his login?

378 views Asked by At

I made a page with editing user information, where it is possible to change the login. When I change it and return to the user profile, I get an error that Account is null. Found out the reason. When changing the login, Principal's username remains the same as it was before the login change. I can't figure out how you can update Principal's username without logging out.

My AccountController:

    @GetMapping("/settings")
    public String showAccountSettings(Principal principal, Model model) {
        Account account = accountRepository.findByLogin(principal.getName());
        model.addAttribute("account", account);

        return "settings";
    }

    @PostMapping("/settings/apply")
    public String applyChangesInAccount(Principal principal, Account account) {
        Account updAccount = accountRepository.findByLogin(principal.getName());

        updAccount.getAccountInfo().setEmail(account.getAccountInfo().getEmail());
        updAccount.getAccountInfo().setPhone(account.getAccountInfo().getPhone());
        updAccount.setLogin(account.getLogin());

        accountRepository.save(updAccount);

        return "redirect:/";
    }
1

There are 1 answers

0
swapyonubuntu On

Assuming you are using spring security,

Post your sucessful backend db calls,

You can do this with,

SecurityContextHolder.getContext().setAuthentication(newAuth);

Refer: https://stackoverflow.com/a/30674697/1811348