ohctechv3/.svn/pristine/be/beb12f8efc2b009331fe7ec7b724685d77396769.svn-base
2024-10-28 15:03:36 +05:30

249 lines
10 KiB
Plaintext

package com.healthcare.ohctech.service.impl;
import com.healthcare.ohctech.dto.LoginDto;
import com.healthcare.ohctech.dto.LoginResponseDto;
import com.healthcare.ohctech.dto.RegisterDto;
import com.healthcare.ohctech.dto.UserDto;
import com.healthcare.ohctech.entity.OhcType;
import com.healthcare.ohctech.entity.RefreshToken;
import com.healthcare.ohctech.entity.Role;
import com.healthcare.ohctech.entity.User;
import com.healthcare.ohctech.repository.OhcTypeRepo;
import com.healthcare.ohctech.repository.RefreshTokenRepo;
import com.healthcare.ohctech.repository.RoleRepo;
import com.healthcare.ohctech.repository.UserRepo;
import com.healthcare.ohctech.service.AuthService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class AuthServiceImpl implements AuthService {
private final UserRepo userRepo;
private final JwtEncoder jwtEncoder;
private final PasswordEncoder passwordEncoder;
private final AuthenticationManager authenticationManager;
private final RefreshTokenRepo refreshTokenRepo;
private final RoleRepo roleRepo;
private final OhcTypeRepo ohcTypeRepo;
@Value("${expiration_time}")
private Long expirationTime;
@Value("${refresh_token_expiration_time}")
private Long refreshExpirationTime;
public AuthServiceImpl(PasswordEncoder passwordEncoder, UserRepo userRepo, JwtEncoder jwtEncoder, RefreshTokenRepo refreshTokenRepo,
AuthenticationManager authenticationManager, RoleRepo roleRepo, OhcTypeRepo ohcTypeRepo) {
this.passwordEncoder = passwordEncoder;
this.userRepo = userRepo;
this.jwtEncoder = jwtEncoder;
this.refreshTokenRepo = refreshTokenRepo;
this.authenticationManager = authenticationManager;
this.roleRepo = roleRepo;
this.ohcTypeRepo = ohcTypeRepo;
}
public LoginResponseDto login(LoginDto loginDto) {
try {
Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginDto.username(),
loginDto.password()));
var user = userRepo.findByusername(loginDto.username()).orElseThrow();
System.out.println("USER IS: " + user);
String token = createToken(authenticate);
createRefreshToken(authenticate);
String name = authenticate.getName();
Long userId = userRepo.findByusername(name).get().getId();
return new LoginResponseDto(token, userId);
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
private String createToken(Authentication authentication) {
JwtClaimsSet jwtClaimsSet = JwtClaimsSet.builder()
.issuer("self")
.issuedAt(Instant.now())
.expiresAt(Instant.now().plusMillis(expirationTime))
.subject(authentication.getName())
.claim("scope", createScope(authentication))
.build();
JwtEncoderParameters parameters = JwtEncoderParameters.from(jwtClaimsSet);
String tokenValue = jwtEncoder.encode(parameters).getTokenValue();
return tokenValue;
}
private void createRefreshToken(Authentication authentication) {
JwtClaimsSet jwtClaimsSet = JwtClaimsSet.builder()
.issuer("self")
.issuedAt(Instant.now())
.expiresAt(Instant.now().plusMillis(refreshExpirationTime))
.subject(authentication.getName())
.claim("scope", createScope(authentication))
.build();
JwtEncoderParameters parameters = JwtEncoderParameters.from(jwtClaimsSet);
String tokenValue = jwtEncoder.encode(parameters).getTokenValue();
//saving inside db for user
User user = userRepo.findByusername(authentication.getName()).get();
RefreshToken presentRefreshToken = user.getRefreshToken();
if (presentRefreshToken != null && !presentRefreshToken.getExpirationTimeInMillis().isBefore(Instant.now())) {
return;
}
// if(presentRefreshToken != null) {
// refreshTokenRepo.delete(user.getRefreshToken());
// }
if (presentRefreshToken != null) {
presentRefreshToken.setToken(tokenValue);
presentRefreshToken.setExpirationTimeInMillis(Instant.now().plusMillis(refreshExpirationTime));
presentRefreshToken.setUser(user);
refreshTokenRepo.save(presentRefreshToken);
return;
}
RefreshToken refreshToken = new RefreshToken();
refreshToken.setUser(user);
refreshToken.setToken(tokenValue);
refreshToken.setExpirationTimeInMillis(Instant.now().plusMillis(refreshExpirationTime));
refreshTokenRepo.save(refreshToken);
}
private String createScope(Authentication authentication) {
return authentication.getAuthorities().stream()
.map(a -> a.getAuthority())
.collect(Collectors.joining(" "));
}
public String getTokenByRefreshToken(Integer userId) {
Optional<User> optionalUser = userRepo.findById((long) userId);
if (optionalUser.isPresent()) {
User user = optionalUser.get();
RefreshToken refreshToken = user.getRefreshToken();
if (refreshToken != null && !refreshToken.getExpirationTimeInMillis().isBefore(Instant.now())) {
// Create an authentication object using the username associated with the refresh token
Authentication authentication = new UsernamePasswordAuthenticationToken(user.getUsername(), null);
// Generate a new access token using the refresh token's user information
return createToken(authentication);
}
}
return null;
}
public void register(RegisterDto registerEmpDto) {
try {
User user = new User();
user.setUsername(registerEmpDto.username().trim());
user.setPassword(passwordEncoder.encode(registerEmpDto.password()));
user.setAccountNonLocked(true);
user.setEnabled(true);
user.setAccountNonExpired(true);
user.setCredentialsNonExpired(true);
//get roles from db;
if (registerEmpDto.roles() != null) {
Set<Role> roles = registerEmpDto.roles()
.stream()
.map(roleId -> roleRepo.findById(Long.valueOf(roleId)).orElse(null))
.filter(role -> role != null)
.collect(Collectors.toSet());
user.setRoles(roles);
}
if (registerEmpDto.ohcTypes() != null) {
//get ohc from db;
Set<OhcType> ohcTypes = registerEmpDto.ohcTypes()
.stream()
.map(ohcId -> ohcTypeRepo.findById(Long.valueOf(ohcId)).orElse(null))
.filter(ohcType -> ohcType != null)
.collect(Collectors.toSet());
user.setOhcTypes(ohcTypes);
}
userRepo.save(user);
} catch (Exception ex) {
throw new RuntimeException(ex.getMessage());
}
}
public void updateUser(String username, String newPassword, RegisterDto registerDto) {
Optional<User> optionalUser = userRepo.findByusername(username);
if (optionalUser.isPresent()) {
User user = optionalUser.get();
// Update user details
if (registerDto != null) {
user.setUsername(registerDto.username().trim());
user.setAccountNonLocked(true);
user.setEnabled(true);
user.setAccountNonExpired(true);
user.setCredentialsNonExpired(true);
// Update roles from DB if provided in the RegisterDto
if (registerDto.roles() != null) {
Set<Role> roles = registerDto.roles()
.stream()
.map(roleId -> roleRepo.findById(Long.valueOf(roleId)).orElse(null))
.filter(role -> role != null)
.collect(Collectors.toSet());
user.setRoles(roles);
}
// Update OHC types from DB if provided in the RegisterDto
if (registerDto.ohcTypes() != null) {
Set<OhcType> ohcTypes = registerDto.ohcTypes()
.stream()
.map(ohcId -> ohcTypeRepo.findById(Long.valueOf(ohcId)).orElse(null))
.filter(ohcType -> ohcType != null)
.collect(Collectors.toSet());
user.setOhcTypes(ohcTypes);
}
}
// Update password if newPassword is provided
if (newPassword != null && !newPassword.isEmpty()) {
user.setPassword(passwordEncoder.encode(newPassword));
}
userRepo.save(user);
} else {
throw new RuntimeException("User not found with username or email: " + username);
}
}
public void deleteUser(String username) {
User user = userRepo.findByusername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found with username or email: " + username));
userRepo.delete(user);
}
}