Advertisement
marrruuuuuuuu

Auth Controller(nailit)

May 26th, 2022
643
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.47 KB | None | 0 0
  1. package com.example.nailitback.controller;
  2.  
  3. import com.example.nailitback.types.ERole;
  4. import com.example.nailitback.jwt.JwtUtils;
  5. import com.example.nailitback.model.Role;
  6. import com.example.nailitback.model.User;
  7. import com.example.nailitback.payload.request.LoginRequest;
  8. import com.example.nailitback.payload.request.SignupRequest;
  9. import com.example.nailitback.payload.response.JwtResponse;
  10. import com.example.nailitback.payload.response.MessageResponse;
  11. import com.example.nailitback.repository.RoleRepository;
  12. import com.example.nailitback.repository.UserRepository;
  13. import com.example.nailitback.security.UserDetailsImpl;
  14. import com.twilio.Twilio;
  15. import com.twilio.rest.api.v2010.account.Message;
  16. import org.springframework.beans.factory.annotation.Value;
  17. import org.springframework.http.HttpStatus;
  18. import org.springframework.http.ResponseEntity;
  19. import org.springframework.security.authentication.AuthenticationManager;
  20. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  21. import org.springframework.security.core.Authentication;
  22. import org.springframework.security.core.GrantedAuthority;
  23. import org.springframework.security.core.context.SecurityContextHolder;
  24. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  25. import org.springframework.security.crypto.password.PasswordEncoder;
  26. import org.springframework.web.bind.annotation.*;
  27.  
  28. import javax.validation.Valid;
  29. import java.util.HashSet;
  30. import java.util.List;
  31. import java.util.Optional;
  32. import java.util.Set;
  33. import java.util.stream.Collectors;
  34.  
  35. @CrossOrigin(origins = "*", maxAge = 3600)
  36. @RestController
  37. @RequestMapping("/auth")
  38. public class AuthController {
  39.  
  40.     @Value("${twilio.account.sid}")
  41.     public String ACCOUNT_SID;
  42.  
  43.     @Value("${twilio.account.authtoken}")
  44.     public String AUTH_TOKEN;
  45.  
  46.     @Value("${twilio.account.phonenumber}")
  47.     public String TWILIO_NUMBER;
  48.  
  49.     private AuthenticationManager authenticationManager;
  50.     private UserRepository userRepository;
  51.     private RoleRepository roleRepository;
  52.     private PasswordEncoder encoder;
  53.     private JwtUtils jwtUtils;
  54.  
  55.     private Integer randomCode;
  56.     private User userChangingPassword;
  57.  
  58.     public AuthController(AuthenticationManager authenticationManager,
  59.                           UserRepository userRepository,
  60.                           RoleRepository roleRepository,
  61.                           PasswordEncoder encoder,
  62.                           JwtUtils jwtUtils) {
  63.         this.authenticationManager = authenticationManager;
  64.         this.roleRepository = roleRepository;
  65.         this.userRepository = userRepository;
  66.         this.encoder = encoder;
  67.         this.jwtUtils = jwtUtils;
  68.     }
  69.  
  70.     @PostMapping("/signin")
  71.     public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
  72.         Authentication authentication = authenticationManager.authenticate(
  73.                 new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
  74.         SecurityContextHolder.getContext().setAuthentication(authentication);
  75.         String jwt = jwtUtils.generateJwtToken(authentication);
  76.  
  77.         UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
  78.         List<String> roles = userDetails.getAuthorities().stream()
  79.                 .map(GrantedAuthority::getAuthority)
  80.                 .collect(Collectors.toList());
  81.         return ResponseEntity.ok(new JwtResponse(jwt,
  82.                 userDetails.getId(),
  83.                 userDetails.getUsername(),
  84.                 userDetails.getName(),
  85.                 roles));
  86.     }
  87.  
  88.     @PostMapping("/resetPassword")
  89.     public ResponseEntity resetPassword(@RequestParam("phone_number") String phoneNumber) {
  90.         if (Boolean.FALSE.equals(userRepository.existsByUsername(phoneNumber))) {
  91.             return ResponseEntity
  92.                     .badRequest()
  93.                     .body(new MessageResponse("Error: This user doesn't exist"));
  94.         }
  95.         randomCode = 1000 + (int) (Math.random() * 9999);
  96.         Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
  97.         userChangingPassword = userRepository.findByUsername(phoneNumber).orElseThrow();
  98.         Message.creator(
  99.                 new com.twilio.type.PhoneNumber(userChangingPassword.getUsername()),
  100.                 new com.twilio.type.PhoneNumber(TWILIO_NUMBER),
  101.                 "Код:" + randomCode + " Подтвердите свой аккаунт для смены пароля"
  102.         ).create();
  103.         return new ResponseEntity(HttpStatus.OK);
  104.     }
  105.  
  106.     @PostMapping("/changePassword")
  107.     public ResponseEntity changePassword(@RequestParam("code") Integer code,
  108.                                          @RequestParam("new_password") String newPassword) {
  109.         if (!code.equals(randomCode)) {
  110.             return ResponseEntity
  111.                     .badRequest()
  112.                     .body(new MessageResponse("Error: Invalid code"));
  113.         }
  114.         userChangingPassword.setPassword(encoder.encode(newPassword));
  115.         userRepository.save(userChangingPassword);
  116.         return ResponseEntity.ok(new MessageResponse("Password changed successfully!"));
  117.     }
  118.  
  119.     @PostMapping("/signup")
  120.     public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
  121.         if (Boolean.TRUE.equals(userRepository.existsByUsername(signUpRequest.getUsername()))) {
  122.             return ResponseEntity
  123.                     .badRequest()
  124.                     .body(new MessageResponse("Error: Username is already taken!"));
  125.         }
  126.         if (Boolean.TRUE.equals(userRepository.existsByName(signUpRequest.getName()))) {
  127.             return ResponseEntity
  128.                     .badRequest()
  129.                     .body(new MessageResponse("Error: Name is already in use!"));
  130.         }
  131.         // Create new user's account
  132.         User user = new User(signUpRequest.getUsername(),
  133.                 signUpRequest.getName(),
  134.                 encoder.encode(signUpRequest.getPassword()));
  135.         Set<String> strRoles = signUpRequest.getRole();
  136.         Set<Role> roles = new HashSet<>();
  137.         if (strRoles == null) {
  138.             Role userRole = roleRepository.findByName(ERole.ROLE_USER)
  139.                     .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
  140.             roles.add(userRole);
  141.         } else {
  142.             strRoles.forEach(role -> {
  143.                 switch (role) {
  144.                     case "admin" -> {
  145.                         Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
  146.                                 .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
  147.                         roles.add(adminRole);
  148.                     }
  149.                     case "mod" -> {
  150.                         Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
  151.                                 .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
  152.                         roles.add(modRole);
  153.                     }
  154.                     default -> {
  155.                         Role userRole = roleRepository.findByName(ERole.ROLE_USER)
  156.                                 .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
  157.                         roles.add(userRole);
  158.                     }
  159.                 }
  160.             });
  161.         }
  162.         user.setRoles(roles);
  163.         userRepository.save(user);
  164.         return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
  165.     }
  166. }
  167.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement