AuthorizationController.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package org.example.sweater.controller;
  2. import jakarta.servlet.http.HttpServletRequest;
  3. import org.example.sweater.domain.Role;
  4. import org.example.sweater.domain.User;
  5. import org.example.sweater.repos.UsersRepository;
  6. import org.springframework.security.web.csrf.CsrfToken;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.ui.Model;
  9. import org.springframework.web.bind.annotation.GetMapping;
  10. import org.springframework.web.bind.annotation.ModelAttribute;
  11. import org.springframework.web.bind.annotation.PostMapping;
  12. import java.util.Collections;
  13. import java.util.Map;
  14. @Controller
  15. public class AuthorizationController {
  16. public AuthorizationController(UsersRepository usersRepository) {
  17. this.usersRepository = usersRepository;
  18. }
  19. private final UsersRepository usersRepository;
  20. @GetMapping("/login")
  21. public String login() {
  22. return "login";
  23. }
  24. @GetMapping("/registration")
  25. public String registration() {
  26. return "registration";
  27. }
  28. @PostMapping("/registration")
  29. public String addUser(User user, Map<String, Object> model) {
  30. User userFromStorage = usersRepository.findByUsername(user.getUsername());
  31. if (userFromStorage != null) {
  32. model.put("message", "User exists!");
  33. return "registration";
  34. }
  35. user.setActive(true);
  36. user.setRoles(Collections.singleton(Role.USER));
  37. usersRepository.save(user);
  38. return "redirect:/login";
  39. }
  40. }