Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.nailitback.controller;
- import com.example.nailitback.types.ERole;
- import com.example.nailitback.jwt.JwtUtils;
- import com.example.nailitback.model.Role;
- import com.example.nailitback.model.User;
- import com.example.nailitback.payload.request.LoginRequest;
- import com.example.nailitback.payload.request.SignupRequest;
- import com.example.nailitback.payload.response.JwtResponse;
- import com.example.nailitback.payload.response.MessageResponse;
- import com.example.nailitback.repository.RoleRepository;
- import com.example.nailitback.repository.UserRepository;
- import com.example.nailitback.security.UserDetailsImpl;
- import com.twilio.Twilio;
- import com.twilio.rest.api.v2010.account.Message;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.http.HttpStatus;
- import org.springframework.http.ResponseEntity;
- import org.springframework.security.authentication.AuthenticationManager;
- import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.context.SecurityContextHolder;
- import org.springframework.security.core.userdetails.UsernameNotFoundException;
- import org.springframework.security.crypto.password.PasswordEncoder;
- import org.springframework.web.bind.annotation.*;
- import javax.validation.Valid;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Optional;
- import java.util.Set;
- import java.util.stream.Collectors;
- @CrossOrigin(origins = "*", maxAge = 3600)
- @RestController
- @RequestMapping("/auth")
- public class AuthController {
- @Value("${twilio.account.sid}")
- public String ACCOUNT_SID;
- @Value("${twilio.account.authtoken}")
- public String AUTH_TOKEN;
- @Value("${twilio.account.phonenumber}")
- public String TWILIO_NUMBER;
- private AuthenticationManager authenticationManager;
- private UserRepository userRepository;
- private RoleRepository roleRepository;
- private PasswordEncoder encoder;
- private JwtUtils jwtUtils;
- private Integer randomCode;
- private User userChangingPassword;
- public AuthController(AuthenticationManager authenticationManager,
- UserRepository userRepository,
- RoleRepository roleRepository,
- PasswordEncoder encoder,
- JwtUtils jwtUtils) {
- this.authenticationManager = authenticationManager;
- this.roleRepository = roleRepository;
- this.userRepository = userRepository;
- this.encoder = encoder;
- this.jwtUtils = jwtUtils;
- }
- @PostMapping("/signin")
- public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
- Authentication authentication = authenticationManager.authenticate(
- new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
- SecurityContextHolder.getContext().setAuthentication(authentication);
- String jwt = jwtUtils.generateJwtToken(authentication);
- UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
- List<String> roles = userDetails.getAuthorities().stream()
- .map(GrantedAuthority::getAuthority)
- .collect(Collectors.toList());
- return ResponseEntity.ok(new JwtResponse(jwt,
- userDetails.getId(),
- userDetails.getUsername(),
- userDetails.getName(),
- roles));
- }
- @PostMapping("/resetPassword")
- public ResponseEntity resetPassword(@RequestParam("phone_number") String phoneNumber) {
- if (Boolean.FALSE.equals(userRepository.existsByUsername(phoneNumber))) {
- return ResponseEntity
- .badRequest()
- .body(new MessageResponse("Error: This user doesn't exist"));
- }
- randomCode = 1000 + (int) (Math.random() * 9999);
- Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
- userChangingPassword = userRepository.findByUsername(phoneNumber).orElseThrow();
- Message.creator(
- new com.twilio.type.PhoneNumber(userChangingPassword.getUsername()),
- new com.twilio.type.PhoneNumber(TWILIO_NUMBER),
- "Код:" + randomCode + " Подтвердите свой аккаунт для смены пароля"
- ).create();
- return new ResponseEntity(HttpStatus.OK);
- }
- @PostMapping("/changePassword")
- public ResponseEntity changePassword(@RequestParam("code") Integer code,
- @RequestParam("new_password") String newPassword) {
- if (!code.equals(randomCode)) {
- return ResponseEntity
- .badRequest()
- .body(new MessageResponse("Error: Invalid code"));
- }
- userChangingPassword.setPassword(encoder.encode(newPassword));
- userRepository.save(userChangingPassword);
- return ResponseEntity.ok(new MessageResponse("Password changed successfully!"));
- }
- @PostMapping("/signup")
- public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
- if (Boolean.TRUE.equals(userRepository.existsByUsername(signUpRequest.getUsername()))) {
- return ResponseEntity
- .badRequest()
- .body(new MessageResponse("Error: Username is already taken!"));
- }
- if (Boolean.TRUE.equals(userRepository.existsByName(signUpRequest.getName()))) {
- return ResponseEntity
- .badRequest()
- .body(new MessageResponse("Error: Name is already in use!"));
- }
- // Create new user's account
- User user = new User(signUpRequest.getUsername(),
- signUpRequest.getName(),
- encoder.encode(signUpRequest.getPassword()));
- Set<String> strRoles = signUpRequest.getRole();
- Set<Role> roles = new HashSet<>();
- if (strRoles == null) {
- Role userRole = roleRepository.findByName(ERole.ROLE_USER)
- .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
- roles.add(userRole);
- } else {
- strRoles.forEach(role -> {
- switch (role) {
- case "admin" -> {
- Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
- .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
- roles.add(adminRole);
- }
- case "mod" -> {
- Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
- .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
- roles.add(modRole);
- }
- default -> {
- Role userRole = roleRepository.findByName(ERole.ROLE_USER)
- .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
- roles.add(userRole);
- }
- }
- });
- }
- user.setRoles(roles);
- userRepository.save(user);
- return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement