@RequestMapping(value = "/register", method = RequestMethod.POST)
  public String registerUserAccount(
      @ModelAttribute("user") UserDto accountDto,
      BindingResult result,
      HttpServletRequest request,
      Errors errors,
      Model model) {

    // Let's manually check if password and other fields are empty
    if (accountDto.getUsername().equals("")) {
      model.addAttribute("viewErrMsg", "Field 'Username' cannot be empty!");
      return "register";
    }

    if (accountDto.getPassword().equals("")) {
      model.addAttribute("viewErrMsg", "Field 'Password' cannot be empty!");
      // return new ModelAndView("register",
      return "register";
    }

    if (accountDto.getMatchingPassword().equals("")) {
      model.addAttribute("viewErrMsg", "Field 'Matching password' cannot be empty!");
      return "register";
    }

    if (!accountDto.getPassword().equals(accountDto.getMatchingPassword())) {
      model.addAttribute("viewErrMsg", "Passwords do not match!");
      return "register";
    }

    Users user = new Users();
    if (!result.hasErrors()) {
      user = createUserAccount(accountDto, result);
    }
    if (user == null) {

      model.addAttribute("viewErrMsg", "User not created! There is a user with such name!");
      return "register";
    }

    if (result.hasErrors()) {

      model.addAttribute("viewErrMsg", "Unknown error!");
      return "register";
    } else {

      // I added this from stackoverflow example
      authenticateUserAndSetSession(user, request);

      model.addAttribute("username", user.getusername());
      model.addAttribute("viewMsg", user.getusername() + " successfully registered!");
      return "settings";
    }
  }
  private void authenticateUserAndSetSession(Users user, HttpServletRequest request) {
    String username = user.getusername();
    String password = user.getPassword();
    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(username, password);

    // generate session if one doesn't exist
    request.getSession();

    token.setDetails(new WebAuthenticationDetails(request));
    Authentication authenticatedUser = authenticationManager.authenticate(token);

    SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
  }
  private Users getNewUser() {
    Users user = new Users();
    user.setEnabled(true);
    user.setPassword("1");
    user.setUsername("testuser");

    List<Usersauthorities> rolesList = new ArrayList<>();

    Usersauthorities checkRoleUser = new Usersauthorities(user.getUsername(), "ROLE_USER", user, 2);

    if (!rolesList.contains(checkRoleUser)) {
      rolesList.add(checkRoleUser);
    }
    user.setAuthorities(rolesList);

    return user;
  }