allfree-springboot-backend / src / main / java / com / allfree / allfreespringbackend / auth / controller / AuthController.java
AuthController.java
Raw
package com.allfree.allfreespringbackend.auth.controller;

import com.allfree.allfreespringbackend.auth.dto.LoginRequestDTO;
import com.allfree.allfreespringbackend.auth.dto.LoginResponseDTO;
import com.allfree.allfreespringbackend.auth.repository.RoleRepository;
import com.allfree.allfreespringbackend.auth.security.Credentials;
import com.allfree.allfreespringbackend.auth.security.JwtUtil;
import com.allfree.allfreespringbackend.auth.security.UserDetailsImpl;
import com.allfree.allfreespringbackend.auth.security.UsernameAndPasswordAuthentication;
import com.allfree.allfreespringbackend.common.dto.CommonResponseDTO;
import com.allfree.allfreespringbackend.repository.UserRepository;
import com.allfree.allfreespringbackend.service.UserService;
import com.allfree.allfreespringbackend.user.dto.NewUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
public class AuthController {

	@Autowired
	AuthenticationManager authenticationManager;

	@Autowired
	UserService userService;

	@Autowired
	UserRepository userRepository;

	@Autowired
	RoleRepository roleRepository;

	@Autowired
	PasswordEncoder encoder;

	@Autowired
	JwtUtil jwtUtil;

	@PostMapping("/login")
	public ResponseEntity<LoginResponseDTO> authenticateUser(@RequestBody LoginRequestDTO loginRequest) {

		var credentials = new Credentials();
		credentials.setUsername(loginRequest.getUsername());
		credentials.setPassword(loginRequest.getPassword());

		var usernameAndPasswordAuth = new UsernameAndPasswordAuthentication();
		usernameAndPasswordAuth.setCredentials(credentials);

		Authentication authentication = authenticationManager.authenticate(usernameAndPasswordAuth);

		SecurityContextHolder.getContext().setAuthentication(authentication);
		String jwt = jwtUtil.generateJwtToken(authentication);
		UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();

		List<String> roles = userDetails.getAuthorities().stream()
				.map(GrantedAuthority::getAuthority)
				.collect(Collectors.toList());

		return ResponseEntity.ok(LoginResponseDTO.fromUserDetailsImpl(userDetails, jwt));

	}

	@PostMapping("/register")
	public ResponseEntity<?> registerUser(@RequestBody NewUserDTO newUserDTO) throws Exception {

		if (userRepository.existsByUsername(newUserDTO.getUsername())) {
			return ResponseEntity
					.badRequest()
					.body(new CommonResponseDTO("Error: Username-ul ales exista deja !"));
		}

		if (userRepository.existsByEmail(newUserDTO.getEmail())) {
			return ResponseEntity
					.badRequest()
					.body(new CommonResponseDTO("Error: Emailul ales exista deja !"));
		}
		userService.saveUserFromDTO(newUserDTO);

		return ResponseEntity.ok(new CommonResponseDTO("Userul " + newUserDTO.getUsername() + " salvat cu succes"));

	}

}