-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
93bf702
commit bdc923c
Showing
56 changed files
with
769 additions
and
241 deletions.
There are no files selected for viewing
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file added
BIN
+3.74 KB
build/tmp/compileJava/compileTransaction/stash-dir/GlobalExceptionHandler.class.uniqueId0
Binary file not shown.
Binary file removed
BIN
-4.12 KB
build/tmp/compileJava/compileTransaction/stash-dir/UserController.class.uniqueId3
Binary file not shown.
Binary file removed
BIN
-484 Bytes
build/tmp/compileJava/compileTransaction/stash-dir/UserDao.class.uniqueId1
Binary file not shown.
Binary file removed
BIN
-4.22 KB
build/tmp/compileJava/compileTransaction/stash-dir/UserImpl.class.uniqueId0
Binary file not shown.
Binary file removed
BIN
-1.28 KB
build/tmp/compileJava/compileTransaction/stash-dir/UserServices.class.uniqueId2
Binary file not shown.
Binary file not shown.
Binary file not shown.
5 changes: 5 additions & 0 deletions
5
...in/java/com/ecommerce/shopping/ecommerceuserpannelapi/Authentication/AuthResponseDto.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
package com.ecommerce.shopping.ecommerceuserpannelapi.Authentication; | ||
|
||
|
||
public record AuthResponseDto(String token, String email,String mobile) { | ||
} |
91 changes: 91 additions & 0 deletions
91
...in/java/com/ecommerce/shopping/ecommerceuserpannelapi/Authentication/AuthServiceImpl.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
package com.ecommerce.shopping.ecommerceuserpannelapi.Authentication; | ||
import com.ecommerce.shopping.ecommerceuserpannelapi.entities.UserEntities; | ||
import com.ecommerce.shopping.ecommerceuserpannelapi.payloads.ApiResponseObject; | ||
import com.ecommerce.shopping.ecommerceuserpannelapi.repositories.UserDao; | ||
import com.ecommerce.shopping.ecommerceuserpannelapi.services.AuthenticationService; | ||
import com.ecommerce.shopping.ecommerceuserpannelapi.utils.JWTUtils; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.http.HttpStatus; | ||
import org.springframework.security.authentication.AuthenticationManager; | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
import org.springframework.security.core.GrantedAuthority; | ||
import org.springframework.security.core.authority.SimpleGrantedAuthority; | ||
import org.springframework.security.core.userdetails.UserDetails; | ||
import org.springframework.security.crypto.password.PasswordEncoder; | ||
import org.springframework.stereotype.Service; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Optional; | ||
|
||
@Service | ||
@RequiredArgsConstructor | ||
public class AuthServiceImpl implements AuthenticationService { | ||
@Autowired | ||
private final AuthenticationManager authenticationManager; | ||
@Autowired | ||
private final PasswordEncoder passwordEncoder; | ||
@Autowired | ||
private final UserDao userDao; | ||
@Override | ||
public ApiResponseObject login(String email, String password) { | ||
try { | ||
var authToken = new UsernamePasswordAuthenticationToken(email, password); | ||
System.out.println("Sout 1"); | ||
var authentication = authenticationManager.authenticate(authToken); | ||
System.out.println("Sout 2"); | ||
// Generate Token | ||
var userName = ((UserDetails) (authentication.getPrincipal())).getUsername(); | ||
System.out.println("Sout 3"); | ||
String token = JWTUtils.generatedToken(userName); | ||
System.out.println("Sout 4"); | ||
System.out.println("Sout 5"); | ||
|
||
System.out.println("Sout 6"); | ||
|
||
var authResponseDto = new AuthResponseDto(token, email,null); | ||
|
||
System.out.println("Sout 7"); | ||
return new ApiResponseObject<>(HttpStatus.OK, "Register SuccessFully", "valid", authResponseDto); | ||
}catch (Exception e){ | ||
System.out.println("Error PUneet ji"); | ||
return new ApiResponseObject<>(HttpStatus.BAD_REQUEST, e.toString(), "Invalid", null); | ||
} | ||
} | ||
|
||
@Override | ||
public ApiResponseObject<AuthResponseDto> signUp(String userName, String email, String password, String mobile) { | ||
try{ | ||
// Check whether user already exists or not | ||
Optional<UserEntities> optionalUserEntities = userDao.findByEmail(email); | ||
if(optionalUserEntities.isPresent()){ | ||
throw new RuntimeException("User already exists"); | ||
} | ||
// authorities | ||
var authorities = new ArrayList<GrantedAuthority>(); | ||
authorities.add(new SimpleGrantedAuthority("ROLE_USER")); | ||
|
||
// Encode password | ||
var encodedPassword = passwordEncoder.encode(password); | ||
|
||
// Generate Token | ||
String token = JWTUtils.generatedToken(email); | ||
var userEntities = UserEntities.builder(). | ||
username(userName) | ||
.passWord(encodedPassword) | ||
.email(email) | ||
.mobile(mobile).accessToken(token) | ||
.authorities(authorities) | ||
.build(); | ||
// Save user | ||
userDao.save(userEntities); | ||
|
||
var authResponseDto = new AuthResponseDto(token, email,mobile); | ||
return new ApiResponseObject<>(HttpStatus.OK, "Register SuccessFully", "valid", authResponseDto); | ||
|
||
}catch (Exception e){ | ||
System.out.println("Error PUneet ji"); | ||
return new ApiResponseObject<>(HttpStatus.BAD_REQUEST, e.toString(), "Invalid", null); | ||
} | ||
} | ||
} |
13 changes: 13 additions & 0 deletions
13
src/main/java/com/ecommerce/shopping/ecommerceuserpannelapi/Authentication/LoginRequest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package com.ecommerce.shopping.ecommerceuserpannelapi.Authentication; | ||
|
||
import lombok.*; | ||
|
||
@Setter | ||
@Getter | ||
@AllArgsConstructor | ||
@NoArgsConstructor | ||
@ToString | ||
public class LoginRequest { | ||
private String email; | ||
private String password; | ||
} |
20 changes: 20 additions & 0 deletions
20
...com/ecommerce/shopping/ecommerceuserpannelapi/Authentication/UserDetailsServicesImpl.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
package com.ecommerce.shopping.ecommerceuserpannelapi.Authentication; | ||
|
||
import com.ecommerce.shopping.ecommerceuserpannelapi.repositories.UserDao; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.security.core.userdetails.User; | ||
import org.springframework.security.core.userdetails.UserDetails; | ||
import org.springframework.security.core.userdetails.UserDetailsService; | ||
import org.springframework.security.core.userdetails.UsernameNotFoundException; | ||
import org.springframework.stereotype.Component; | ||
|
||
@Component | ||
@RequiredArgsConstructor | ||
public class UserDetailsServicesImpl implements UserDetailsService { | ||
private final UserDao userDao; | ||
@Override | ||
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { | ||
var user = userDao.findByEmail(email).orElseThrow(()->new UsernameNotFoundException("Username Not Found")); | ||
return new User(user.getEmail(),user.getPassWord(),user.getAuthorities()); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
31 changes: 31 additions & 0 deletions
31
src/main/java/com/ecommerce/shopping/ecommerceuserpannelapi/config/AuthenticationConfig.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
package com.ecommerce.shopping.ecommerceuserpannelapi.config; | ||
|
||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.security.authentication.AuthenticationManager; | ||
import org.springframework.security.authentication.AuthenticationProvider; | ||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider; | ||
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; | ||
import org.springframework.security.core.userdetails.UserDetailsService; | ||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | ||
import org.springframework.security.crypto.password.PasswordEncoder; | ||
|
||
@Configuration | ||
public class AuthenticationConfig { | ||
@Bean | ||
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception { | ||
return configuration.getAuthenticationManager(); | ||
} | ||
|
||
@Bean | ||
public AuthenticationProvider authenticationProvider(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) { | ||
var authenticationProvider = new DaoAuthenticationProvider(); | ||
authenticationProvider.setUserDetailsService(userDetailsService); | ||
authenticationProvider.setPasswordEncoder(passwordEncoder); | ||
return authenticationProvider; | ||
} | ||
@Bean | ||
public PasswordEncoder bCryptPasswordEncoder(){ | ||
return new BCryptPasswordEncoder(); | ||
} | ||
} |
18 changes: 18 additions & 0 deletions
18
...com/ecommerce/shopping/ecommerceuserpannelapi/config/CustomAuthenticationEntryPoints.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
package com.ecommerce.shopping.ecommerceuserpannelapi.config; | ||
|
||
import jakarta.servlet.ServletException; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import jakarta.servlet.http.HttpServletResponse; | ||
import org.springframework.http.HttpStatus; | ||
import org.springframework.security.core.AuthenticationException; | ||
import org.springframework.security.web.AuthenticationEntryPoint; | ||
import org.springframework.stereotype.Component; | ||
|
||
import java.io.IOException; | ||
@Component | ||
public class CustomAuthenticationEntryPoints implements AuthenticationEntryPoint { | ||
@Override | ||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { | ||
response.sendError(HttpStatus.UNAUTHORIZED.value(), authException.getMessage()); | ||
} | ||
} |
61 changes: 61 additions & 0 deletions
61
...in/java/com/ecommerce/shopping/ecommerceuserpannelapi/config/JWTAuthenticationFilter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
package com.ecommerce.shopping.ecommerceuserpannelapi.config; | ||
|
||
import com.ecommerce.shopping.ecommerceuserpannelapi.utils.JWTUtils; | ||
import jakarta.servlet.FilterChain; | ||
import jakarta.servlet.ServletException; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import jakarta.servlet.http.HttpServletResponse; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.http.HttpHeaders; | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.security.core.userdetails.UserDetailsService; | ||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.util.StringUtils; | ||
import org.springframework.web.filter.OncePerRequestFilter; | ||
|
||
import java.io.IOException; | ||
import java.util.Optional; | ||
|
||
@Component | ||
@RequiredArgsConstructor | ||
public class JWTAuthenticationFilter extends OncePerRequestFilter { | ||
private final UserDetailsService userDetailsService; | ||
|
||
@Override | ||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { | ||
// Fetch token from request | ||
var jwtTokenOptional = getTokenFromRequest(request); | ||
|
||
// Validate jwt token -> JWT utils | ||
jwtTokenOptional.ifPresent(jwtToken -> { | ||
if (JWTUtils.validateToken(jwtToken)) { | ||
// Get user from JWT token | ||
var userNameOptional = JWTUtils.getUsernameFromToken(jwtToken); | ||
userNameOptional.ifPresent(userName-> { | ||
// Fetch user Details with the help of userName | ||
var userDetails = userDetailsService.loadUserByUsername(userName); | ||
// Crate Authentication Token | ||
var authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); | ||
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); | ||
// Set authentication token to Security Context | ||
SecurityContextHolder.getContext().setAuthentication(authenticationToken); | ||
}); | ||
} | ||
}); | ||
|
||
// pass request and response to next filter | ||
filterChain.doFilter(request, response); | ||
} | ||
|
||
public Optional<String> getTokenFromRequest(HttpServletRequest request) { | ||
// Extract authentication header | ||
var authHeader = request.getHeader(HttpHeaders.AUTHORIZATION); | ||
// Bearer <JWT Token> | ||
if (StringUtils.hasText(authHeader) && authHeader.startsWith("Bearer ")) { | ||
return Optional.of(authHeader.substring(7)); | ||
} | ||
return Optional.empty(); | ||
} | ||
} |
1 change: 0 additions & 1 deletion
1
src/main/java/com/ecommerce/shopping/ecommerceuserpannelapi/config/MySecurityConfig.java
This file was deleted.
Oops, something went wrong.
47 changes: 47 additions & 0 deletions
47
.../java/com/ecommerce/shopping/ecommerceuserpannelapi/config/SecurityFilterChainConfig.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
package com.ecommerce.shopping.ecommerceuserpannelapi.config; | ||
|
||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | ||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; | ||
import org.springframework.security.config.http.SessionCreationPolicy; | ||
import org.springframework.security.web.SecurityFilterChain; | ||
import org.springframework.security.web.AuthenticationEntryPoint; | ||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
|
||
@Configuration | ||
@EnableWebSecurity | ||
public class SecurityFilterChainConfig{ | ||
|
||
private final AuthenticationEntryPoint authenticationEntryPoint; | ||
private final JWTAuthenticationFilter jwtAuthenticationFilter; | ||
|
||
public SecurityFilterChainConfig(AuthenticationEntryPoint authenticationEntryPoint, JWTAuthenticationFilter jwtAuthenticationFilter) { | ||
this.authenticationEntryPoint = authenticationEntryPoint; | ||
this.jwtAuthenticationFilter = jwtAuthenticationFilter; | ||
} | ||
|
||
@Bean | ||
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { | ||
// Disable CORS | ||
httpSecurity.cors(AbstractHttpConfigurer::disable); | ||
|
||
// Disable CSRF | ||
httpSecurity.csrf(AbstractHttpConfigurer::disable); | ||
|
||
// Http Request Filter | ||
httpSecurity.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers("/api/auth/**").permitAll().anyRequest().authenticated()); | ||
|
||
// Authentication Entry Point -> Exception Handler | ||
httpSecurity.exceptionHandling(exceptionConfig->exceptionConfig.authenticationEntryPoint(authenticationEntryPoint)); | ||
|
||
// Set Session Policy = STATELESS | ||
httpSecurity.sessionManagement(sessionConfig->sessionConfig.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); | ||
|
||
// Add JWT Authentication Filter | ||
httpSecurity.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); | ||
|
||
return httpSecurity.build(); | ||
} | ||
} |
45 changes: 45 additions & 0 deletions
45
src/main/java/com/ecommerce/shopping/ecommerceuserpannelapi/controllers/AuthController.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package com.ecommerce.shopping.ecommerceuserpannelapi.controllers; | ||
|
||
import com.ecommerce.shopping.ecommerceuserpannelapi.Authentication.AuthServiceImpl; | ||
import com.ecommerce.shopping.ecommerceuserpannelapi.Authentication.LoginRequest; | ||
import com.ecommerce.shopping.ecommerceuserpannelapi.entities.UserEntities; | ||
import com.ecommerce.shopping.ecommerceuserpannelapi.payloads.ApiResponseObject; | ||
import jakarta.validation.Valid; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.http.HttpStatus; | ||
import org.springframework.validation.BindingResult; | ||
import org.springframework.web.bind.annotation.*; | ||
|
||
@RestController | ||
@RequestMapping("/api/auth/") | ||
public class AuthController { | ||
@Autowired | ||
AuthServiceImpl authServiceImpl; | ||
|
||
@PostMapping("login") | ||
public ApiResponseObject login(@RequestBody LoginRequest loginRequest) { | ||
try { | ||
return authServiceImpl.login(loginRequest.getEmail(), loginRequest.getPassword()); | ||
} catch (Exception e) { | ||
System.out.println("Error Sharma ji"); | ||
return new ApiResponseObject<>(HttpStatus.BAD_REQUEST, e.toString(), "Invalid", null); | ||
} | ||
} | ||
|
||
|
||
@PostMapping("sign-up") | ||
public ApiResponseObject signUp(@Valid @RequestBody UserEntities userEntities, BindingResult bindingResult) { | ||
if (bindingResult.hasErrors()) { | ||
return new ApiResponseObject<>(HttpStatus.BAD_REQUEST, "Validation error: " + bindingResult.getAllErrors(), "Invalid", null); | ||
} | ||
try { | ||
return authServiceImpl.signUp(userEntities.getUsername(), userEntities.getEmail(), userEntities.getPassWord(), userEntities.getMobile()); | ||
|
||
} catch (Exception e) { | ||
System.out.println("Error Sharma ji"); | ||
return new ApiResponseObject<>(HttpStatus.BAD_REQUEST, e.toString(), "Invalid", null); | ||
|
||
} | ||
} | ||
|
||
} |
Oops, something went wrong.