updated code mohd arham
This commit is contained in:
@@ -10,6 +10,7 @@ import org.springframework.security.core.userdetails.UserDetailsService;
|
|||||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import com.billpaymentservice.bbps.entites.UserEntity;
|
||||||
import com.billpaymentservice.bbps.entites.UsersDetails;
|
import com.billpaymentservice.bbps.entites.UsersDetails;
|
||||||
import com.billpaymentservice.bbps.repository.UsersDetailsRepository;
|
import com.billpaymentservice.bbps.repository.UsersDetailsRepository;
|
||||||
|
|
||||||
@@ -22,13 +23,11 @@ public class CustomUserDetailsService implements UserDetailsService {
|
|||||||
@Override
|
@Override
|
||||||
public UserDetails loadUserByUsername(String userMobNo) throws UsernameNotFoundException {
|
public UserDetails loadUserByUsername(String userMobNo) throws UsernameNotFoundException {
|
||||||
|
|
||||||
String normalizedEmail = userMobNo;
|
Optional<UserEntity> adminOptional = userRepo.findByMobile(userMobNo);
|
||||||
|
|
||||||
Optional<UsersDetails> adminOptional = userRepo.findByUserMobNo(normalizedEmail);
|
|
||||||
|
|
||||||
if (adminOptional.isPresent()) {
|
if (adminOptional.isPresent()) {
|
||||||
UsersDetails user = adminOptional.get();
|
UserEntity user = adminOptional.get();
|
||||||
return new User(user.getUserEmailId(), user.getUserMobNo(), new ArrayList<>());
|
return new User(user.getMobile(), user.getName(), new ArrayList<>());
|
||||||
} else {
|
} else {
|
||||||
throw new UsernameNotFoundException("User not found with MobNo: " + userMobNo);
|
throw new UsernameNotFoundException("User not found with MobNo: " + userMobNo);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package com.billpaymentservice.bbps.config;
|
|||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
import org.springframework.security.core.userdetails.UserDetails;
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
@@ -19,11 +18,14 @@ import jakarta.servlet.http.HttpServletResponse;
|
|||||||
@Component
|
@Component
|
||||||
public class JwtFilter extends OncePerRequestFilter {
|
public class JwtFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
@Autowired
|
private final JwtUtil jwtUtil;
|
||||||
private JwtUtil jwtUtil;
|
|
||||||
|
|
||||||
@Autowired
|
private final CustomUserDetailsService userDetailsService;
|
||||||
private CustomUserDetailsService userDetailsService;
|
|
||||||
|
public JwtFilter(JwtUtil jwtUtil, CustomUserDetailsService userDetailsService) {
|
||||||
|
this.jwtUtil = jwtUtil;
|
||||||
|
this.userDetailsService = userDetailsService;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||||
@@ -31,13 +33,13 @@ public class JwtFilter extends OncePerRequestFilter {
|
|||||||
|
|
||||||
final String authorizationHeader = request.getHeader("Authentication");
|
final String authorizationHeader = request.getHeader("Authentication");
|
||||||
|
|
||||||
String email = null;
|
String mobileNo = null;
|
||||||
String jwt = null;
|
String jwt = null;
|
||||||
|
|
||||||
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
|
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
|
||||||
jwt = authorizationHeader.substring(7);
|
jwt = authorizationHeader.substring(7);
|
||||||
try {
|
try {
|
||||||
email = jwtUtil.extractUsername(jwt);
|
mobileNo = jwtUtil.extractUsername(jwt);
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
System.out.println("unable to get jwt tokken");
|
System.out.println("unable to get jwt tokken");
|
||||||
} catch (ExpiredJwtException e) {
|
} catch (ExpiredJwtException e) {
|
||||||
@@ -47,11 +49,10 @@ public class JwtFilter extends OncePerRequestFilter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (email != null && SecurityContextHolder.getContext().getAuthentication() == null) {
|
if (mobileNo != null && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||||
|
|
||||||
UserDetails userDetails = this.userDetailsService.loadUserByUsername(email);
|
UserDetails userDetails = this.userDetailsService.loadUserByUsername(mobileNo);
|
||||||
|
|
||||||
|
|
||||||
if (jwtUtil.validateToken(jwt, userDetails)) {
|
if (jwtUtil.validateToken(jwt, userDetails)) {
|
||||||
|
|
||||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
|
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
|
||||||
@@ -60,7 +61,7 @@ public class JwtFilter extends OncePerRequestFilter {
|
|||||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
System.out.println("JWT Filter: Token validation failed for user - " + email);
|
System.out.println("JWT Filter: Token validation failed for user - " + mobileNo);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import org.springframework.beans.factory.annotation.Value;
|
|||||||
import org.springframework.security.core.userdetails.UserDetails;
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import com.billpaymentservice.bbps.util.BBPSConstant;
|
||||||
|
|
||||||
import io.jsonwebtoken.Claims;
|
import io.jsonwebtoken.Claims;
|
||||||
import io.jsonwebtoken.Jwts;
|
import io.jsonwebtoken.Jwts;
|
||||||
import io.jsonwebtoken.SignatureAlgorithm;
|
import io.jsonwebtoken.SignatureAlgorithm;
|
||||||
@@ -22,22 +24,23 @@ public class JwtUtil {
|
|||||||
@Value("${jwt.secret}")
|
@Value("${jwt.secret}")
|
||||||
private String secret;
|
private String secret;
|
||||||
|
|
||||||
|
private final Map<String, Date> tokenBlacklist = new HashMap<>();
|
||||||
|
|
||||||
private Key getSigningKey() {
|
private Key getSigningKey() {
|
||||||
byte[] keyBytes = Decoders.BASE64.decode(secret);
|
byte[] keyBytes = Decoders.BASE64.decode(secret);
|
||||||
return Keys.hmacShaKeyFor(keyBytes);
|
return Keys.hmacShaKeyFor(keyBytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Access Token - 2 Hours
|
public String generateToken(String username, String mid) {
|
||||||
private final long jwtExpirationInMs = 1000 * 60 * 60 * 2; // 2 hours
|
Map<String, Object> claims = new HashMap<>();
|
||||||
|
claims.put("mid", mid);
|
||||||
// Refresh Token - 7 Days
|
claims.put("expiryTime", new Date(System.currentTimeMillis() + BBPSConstant.JWT_EXPIRATION_MS).toString());
|
||||||
private final long refreshExpirationDateInMs = 1000L * 60 * 60 * 24 * 7; // 7 days
|
return createToken(claims, username.toUpperCase());
|
||||||
|
}
|
||||||
private final Map<String, Date> tokenBlacklist = new HashMap<>();
|
|
||||||
|
|
||||||
public String doGenerateRefreshToken(Map<String, Object> claims, String subject) {
|
public String doGenerateRefreshToken(Map<String, Object> claims, String subject) {
|
||||||
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
|
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
|
||||||
.setExpiration(new Date(System.currentTimeMillis() + refreshExpirationDateInMs))
|
.setExpiration(new Date(System.currentTimeMillis() + BBPSConstant.REFRESH_EXPIRATION_MS))
|
||||||
.signWith(getSigningKey(), SignatureAlgorithm.HS512).compact();
|
.signWith(getSigningKey(), SignatureAlgorithm.HS512).compact();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,28 +65,28 @@ public class JwtUtil {
|
|||||||
return extractExpiration(token).before(new Date());
|
return extractExpiration(token).before(new Date());
|
||||||
}
|
}
|
||||||
|
|
||||||
public String generateToken(String username, String mid) {
|
private String createToken(Map<String, Object> claims, String subject) {
|
||||||
Map<String, Object> claims = new HashMap<>();
|
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
|
||||||
claims.put("mid", mid);
|
.setExpiration(new Date(System.currentTimeMillis() + BBPSConstant.JWT_EXPIRATION_MS))
|
||||||
claims.put("expiryTime", new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10).toString());
|
.signWith(getSigningKey(), SignatureAlgorithm.HS512).compact();
|
||||||
return createToken(claims, username.toUpperCase());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private String createToken(Map<String, Object> claims, String subject) {
|
private String createToken1(Map<String, Object> claims,String subject) {
|
||||||
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
|
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
|
||||||
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
|
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
|
||||||
.signWith(getSigningKey(), SignatureAlgorithm.HS512).compact();
|
.signWith(getSigningKey(), SignatureAlgorithm.HS512).compact();
|
||||||
}
|
}
|
||||||
|
|
||||||
private String createToken1(String subject) {
|
// public Boolean validateToken(String token, UserDetails userDetails) {
|
||||||
return Jwts.builder().setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
|
// final String username = extractUsername(token);
|
||||||
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
|
// return true;
|
||||||
.signWith(getSigningKey(), SignatureAlgorithm.HS512).compact();
|
// }
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean validateToken(String token, UserDetails userDetails) {
|
public Boolean validateToken(String token, UserDetails userDetails) {
|
||||||
final String username = extractUsername(token);
|
final String mobileNo = extractUsername(token);
|
||||||
return true;
|
// System.out.println("Extracted mobileNo from token: " + mobileNo );
|
||||||
|
// System.out.println("Username from UserDetails: " + userDetails.getUsername());
|
||||||
|
return (mobileNo .equals(userDetails.getUsername()) && !isTokenExpired(token));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void invalidateToken(String token) {
|
public void invalidateToken(String token) {
|
||||||
@@ -96,7 +99,9 @@ public class JwtUtil {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String generateToken(String mobileNo) {
|
public String generateToken(String mobileNo) {
|
||||||
return createToken1(mobileNo);
|
Map<String, Object> claims = new HashMap<>();
|
||||||
|
claims.put("mobileNo", mobileNo);
|
||||||
|
return createToken1(claims,mobileNo);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,7 @@ package com.billpaymentservice.bbps.config;
|
|||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.ComponentScan;
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.http.HttpMethod;
|
import org.springframework.http.HttpMethod;
|
||||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
@@ -20,11 +18,14 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
|||||||
@EnableWebSecurity
|
@EnableWebSecurity
|
||||||
public class SecurityConfig {
|
public class SecurityConfig {
|
||||||
|
|
||||||
@Autowired
|
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
|
||||||
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
|
|
||||||
|
|
||||||
@Autowired
|
private final JwtFilter jwtFilter;
|
||||||
private JwtFilter jwtFilter;
|
|
||||||
|
public SecurityConfig(JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint, JwtFilter jwtFilter) {
|
||||||
|
this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint;
|
||||||
|
this.jwtFilter = jwtFilter;
|
||||||
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||||
@@ -32,13 +33,13 @@ public class SecurityConfig {
|
|||||||
http.csrf(csrf -> csrf.disable()).cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
http.csrf(csrf -> csrf.disable()).cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||||
.authorizeHttpRequests(auth -> auth
|
.authorizeHttpRequests(auth -> auth
|
||||||
.requestMatchers("/auth/**",
|
.requestMatchers("/auth/**",
|
||||||
"/v3/api-docs/**",
|
"/v3/api-docs/**",
|
||||||
"/swagger-ui/**",
|
"/swagger-ui/**",
|
||||||
"/swagger-ui.html",
|
"/swagger-ui.html",
|
||||||
"/swagger-resources/**",
|
"/swagger-resources/**",
|
||||||
"/webjars/**",
|
"/webjars/**",
|
||||||
"/error")
|
"/error")
|
||||||
.permitAll().requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() // <-- Correct way
|
.permitAll().requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
|
||||||
.anyRequest().authenticated())
|
.anyRequest().authenticated())
|
||||||
.exceptionHandling(ex -> ex.authenticationEntryPoint(jwtAuthenticationEntryPoint))
|
.exceptionHandling(ex -> ex.authenticationEntryPoint(jwtAuthenticationEntryPoint))
|
||||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
|
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
|
||||||
|
|||||||
@@ -25,32 +25,32 @@ import lombok.extern.slf4j.Slf4j;
|
|||||||
@Slf4j
|
@Slf4j
|
||||||
public class AuthController {
|
public class AuthController {
|
||||||
|
|
||||||
private final AuthService authService;
|
private final AuthService authService;
|
||||||
|
|
||||||
public AuthController(AuthService authService) {
|
public AuthController(AuthService authService) {
|
||||||
this.authService = authService;
|
this.authService = authService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping(value = "/sendOtp", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
|
@PostMapping(value = "/sendOtp", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||||
public ResponseEntity<OtpSendResponse> sendOtp(@Validated @RequestBody LoginRequest request) {
|
public ResponseEntity<OtpSendResponse> sendOtp(@Validated @RequestBody LoginRequest request) {
|
||||||
log.info("Received sendOtp request for mobile: {}", request.getMobile());
|
log.info("Received sendOtp request for mobile: {}", request.getMobile());
|
||||||
OtpSendResponse resp = authService.sendOtp(request);
|
OtpSendResponse resp = authService.sendOtp(request);
|
||||||
return ResponseEntity.ok(resp);
|
return ResponseEntity.ok(resp);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping(value = "/verifyOtp", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
|
@PostMapping(value = "/verifyOtp", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||||
public ResponseEntity<AuthResponses> verifyOtp(@Validated @RequestBody VerifyOtpRequest request) {
|
public ResponseEntity<AuthResponses> verifyOtp(@Validated @RequestBody VerifyOtpRequest request) {
|
||||||
AuthResponses resp = authService.verifyOtp(request);
|
AuthResponses resp = authService.verifyOtp(request);
|
||||||
return ResponseEntity.ok(resp);
|
return ResponseEntity.ok(resp);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping(value = "/register", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
|
@PostMapping(value = "/register", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||||
public ResponseEntity<AuthResponse> register(@Validated @RequestBody RegisterRequest request) {
|
public ResponseEntity<AuthResponse> register(@Validated @RequestBody RegisterRequest request) {
|
||||||
AuthResponse resp = authService.registerUser(request);
|
AuthResponse resp = authService.registerUser(request);
|
||||||
return ResponseEntity.ok(resp);
|
return ResponseEntity.ok(resp);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/loginWithoutDecryption")
|
@PostMapping("/loginWithoutDecryption")
|
||||||
public ResponseEntity<AuthResponses> login(@RequestBody LoginRequest loginRequest) {
|
public ResponseEntity<AuthResponses> login(@RequestBody LoginRequest loginRequest) {
|
||||||
try {
|
try {
|
||||||
AuthResponses authResponse = authService.authenticateUser(loginRequest);
|
AuthResponses authResponse = authService.authenticateUser(loginRequest);
|
||||||
@@ -60,5 +60,5 @@ public class AuthController {
|
|||||||
.message("An unexpected error occurred").statusCode(500).build());
|
.message("An unexpected error occurred").statusCode(500).build());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -19,5 +19,5 @@ public class UserDetailsDTO {
|
|||||||
|
|
||||||
private String userName;
|
private String userName;
|
||||||
|
|
||||||
private String userAge;
|
private int userAge;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,11 +5,11 @@ import java.util.Optional;
|
|||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
import com.billpaymentservice.bbps.entites.UsersDetails;
|
import com.billpaymentservice.bbps.entites.UserEntity;
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
public interface UsersDetailsRepository extends JpaRepository<UsersDetails, Long> {
|
public interface UsersDetailsRepository extends JpaRepository<UserEntity, Long> {
|
||||||
|
|
||||||
Optional<UsersDetails> findByUserMobNo(String userMobNo);
|
Optional<UserEntity> findByMobile(String userMobNo);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ import com.billpaymentservice.bbps.dto.auth.UserDto;
|
|||||||
import com.billpaymentservice.bbps.dto.auth.VerifyOtpRequest;
|
import com.billpaymentservice.bbps.dto.auth.VerifyOtpRequest;
|
||||||
import com.billpaymentservice.bbps.dto.response.AuthResponses;
|
import com.billpaymentservice.bbps.dto.response.AuthResponses;
|
||||||
import com.billpaymentservice.bbps.entites.UserEntity;
|
import com.billpaymentservice.bbps.entites.UserEntity;
|
||||||
import com.billpaymentservice.bbps.entites.UsersDetails;
|
|
||||||
import com.billpaymentservice.bbps.repository.UserRepository;
|
import com.billpaymentservice.bbps.repository.UserRepository;
|
||||||
import com.billpaymentservice.bbps.repository.UsersDetailsRepository;
|
import com.billpaymentservice.bbps.repository.UsersDetailsRepository;
|
||||||
import com.billpaymentservice.bbps.service.AuthService;
|
import com.billpaymentservice.bbps.service.AuthService;
|
||||||
@@ -37,14 +36,13 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
|
|
||||||
private final JwtUtil jwtUtil;
|
private final JwtUtil jwtUtil;
|
||||||
|
|
||||||
@Autowired
|
|
||||||
public AuthServiceImpl(UserRepository userRepository, OtpClient otpClient, Helper helper,
|
public AuthServiceImpl(UserRepository userRepository, OtpClient otpClient, Helper helper,
|
||||||
UsersDetailsRepository userRepo, JwtUtil jwtUtil) {
|
UsersDetailsRepository userRepo, JwtUtil jwtUtil) {
|
||||||
this.userRepository = userRepository;
|
this.userRepository = userRepository;
|
||||||
this.otpClient = otpClient;
|
this.otpClient = otpClient;
|
||||||
this.helper = helper;
|
this.helper = helper;
|
||||||
this.userRepo=userRepo;
|
this.userRepo = userRepo;
|
||||||
this.jwtUtil=jwtUtil;
|
this.jwtUtil = jwtUtil;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -63,28 +61,26 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
@Override
|
@Override
|
||||||
public AuthResponses verifyOtp(VerifyOtpRequest request) {
|
public AuthResponses verifyOtp(VerifyOtpRequest request) {
|
||||||
boolean ok = otpClient.verifyOtp(request.getMobile(), request.getOtp());
|
boolean ok = otpClient.verifyOtp(request.getMobile(), request.getOtp());
|
||||||
LOGGER.info("OTP STATUS"+ ok);
|
LOGGER.info("OTP STATUS" + ok);
|
||||||
if (ok) {
|
if (ok) {
|
||||||
return new AuthResponses("","Invalid OTP","Failed", 401, null);
|
return new AuthResponses("", "Invalid OTP", "Failed", 401, null);
|
||||||
}
|
}
|
||||||
String mobileNo = request.getMobile();
|
String mobileNo = request.getMobile();
|
||||||
try {
|
try {
|
||||||
|
|
||||||
|
|
||||||
Optional<UsersDetails> byAdminEmail = userRepo.findByUserMobNo(mobileNo);
|
Optional<UserEntity> byAdminEmail = userRepo.findByMobile(mobileNo);
|
||||||
|
|
||||||
if (byAdminEmail.isPresent()) {
|
if (byAdminEmail.isPresent()) {
|
||||||
UsersDetails user = byAdminEmail.get();
|
UserEntity user = byAdminEmail.get();
|
||||||
String token = jwtUtil.generateToken(user.getUserMobNo());
|
String token = jwtUtil.generateToken(user.getMobile());
|
||||||
|
|
||||||
LOGGER.info("Generated JWT token for mobileNo: " + mobileNo);
|
LOGGER.info("Generated JWT token for mobileNo: " + mobileNo);
|
||||||
|
|
||||||
Object userDetailsDTO = null;
|
Object userDetailsDTO = null;
|
||||||
|
|
||||||
if (user != null) {
|
if (user != null) {
|
||||||
userDetailsDTO = UserDetailsDTO.builder().id(user.getId()).userEmailId(user.getUserEmailId())
|
userDetailsDTO = UserDetailsDTO.builder().id(user.getId()).userEmailId(user.getEmail())
|
||||||
.userMobNo(user.getUserMobNo()).userName(user.getUserName()).userAge(user.getUserAge())
|
.userMobNo(user.getMobile()).userName(user.getName()).userAge(user.getAge()).build();
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
return new AuthResponses(token, "Success", "Login Done", 200, userDetailsDTO);
|
return new AuthResponses(token, "Success", "Login Done", 200, userDetailsDTO);
|
||||||
} else {
|
} else {
|
||||||
@@ -92,8 +88,8 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
System.out.println("Error occurred during login for mobile no: " + mobileNo
|
System.out.println(
|
||||||
+ " Exception: " + ex.getMessage());
|
"Error occurred during login for mobile no: " + mobileNo + " Exception: " + ex.getMessage());
|
||||||
|
|
||||||
return AuthResponses.builder().status("Unauthorized").message("Authentication failed: " + ex.getMessage())
|
return AuthResponses.builder().status("Unauthorized").message("Authentication failed: " + ex.getMessage())
|
||||||
.statusCode(401).build();
|
.statusCode(401).build();
|
||||||
@@ -137,20 +133,19 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
try {
|
try {
|
||||||
String mobileNo = loginRequest.getMobile();
|
String mobileNo = loginRequest.getMobile();
|
||||||
|
|
||||||
Optional<UsersDetails> byAdminEmail = userRepo.findByUserMobNo(mobileNo);
|
Optional<UserEntity> byAdminEmail = userRepo.findByMobile(mobileNo);
|
||||||
|
|
||||||
if (byAdminEmail.isPresent()) {
|
if (byAdminEmail.isPresent()) {
|
||||||
UsersDetails user = byAdminEmail.get();
|
UserEntity user = byAdminEmail.get();
|
||||||
String token = jwtUtil.generateToken(user.getUserMobNo());
|
String token = jwtUtil.generateToken(user.getMobile());
|
||||||
|
|
||||||
LOGGER.info("Generated JWT token for mobileNo: " + mobileNo);
|
LOGGER.info("Generated JWT token for mobileNo: " + mobileNo);
|
||||||
|
|
||||||
Object userDetailsDTO = null;
|
Object userDetailsDTO = null;
|
||||||
|
|
||||||
if (user != null) {
|
if (user != null) {
|
||||||
userDetailsDTO = UserDetailsDTO.builder().id(user.getId()).userEmailId(user.getUserEmailId())
|
userDetailsDTO = UserDetailsDTO.builder().id(user.getId()).userEmailId(user.getEmail())
|
||||||
.userMobNo(user.getUserMobNo()).userName(user.getUserName()).userAge(user.getUserAge())
|
.userMobNo(user.getMobile()).userName(user.getName()).userAge(user.getAge()).build();
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
return new AuthResponses(token, "Success", "Login Done", 200, userDetailsDTO);
|
return new AuthResponses(token, "Success", "Login Done", 200, userDetailsDTO);
|
||||||
} else {
|
} else {
|
||||||
@@ -158,8 +153,8 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
System.out.println("Error occurred during login for mobile no: " + loginRequest.getMobile()
|
System.out.println("Error occurred during login for mobile no: " + loginRequest.getMobile() + " Exception: "
|
||||||
+ " Exception: " + ex.getMessage());
|
+ ex.getMessage());
|
||||||
|
|
||||||
return AuthResponses.builder().status("Unauthorized").message("Authentication failed: " + ex.getMessage())
|
return AuthResponses.builder().status("Unauthorized").message("Authentication failed: " + ex.getMessage())
|
||||||
.statusCode(401).build();
|
.statusCode(401).build();
|
||||||
|
|||||||
@@ -2,6 +2,10 @@ package com.billpaymentservice.bbps.util;
|
|||||||
|
|
||||||
public class BBPSConstant {
|
public class BBPSConstant {
|
||||||
|
|
||||||
|
// Jwt Token Expiration Time
|
||||||
|
public static final long JWT_EXPIRATION_MS = 1000 * 60 * 60 * 24; // 24 hours
|
||||||
|
public static final long REFRESH_EXPIRATION_MS = 1000L * 60 * 60 * 24 * 7; // 7 days
|
||||||
|
|
||||||
public static final Long SENT_TO_PROCESSOR_CODE = 198L;
|
public static final Long SENT_TO_PROCESSOR_CODE = 198L;
|
||||||
public static final Long SUCCESS_CODE = 200L;
|
public static final Long SUCCESS_CODE = 200L;
|
||||||
public static final Long FAILED_CODE = 99L;
|
public static final Long FAILED_CODE = 99L;
|
||||||
|
|||||||
@@ -20,9 +20,9 @@ swagger.server.description=Local Development Server
|
|||||||
# DataSource
|
# DataSource
|
||||||
spring.datasource.url=jdbc:postgresql://localhost:5432/BBPS
|
spring.datasource.url=jdbc:postgresql://localhost:5432/BBPS
|
||||||
spring.datasource.username=postgres
|
spring.datasource.username=postgres
|
||||||
#spring.datasource.password=UAT@DB_2025
|
spring.datasource.password=UAT@DB_2025
|
||||||
|
|
||||||
spring.datasource.password=himanshu@123
|
#spring.datasource.password=himanshu@123
|
||||||
spring.datasource.driver-class-name=org.postgresql.Driver
|
spring.datasource.driver-class-name=org.postgresql.Driver
|
||||||
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
|
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user