Skip to content

Commit

Permalink
🎇 Add Controllers
Browse files Browse the repository at this point in the history
  • Loading branch information
Puneetsharma5525 committed Jun 6, 2024
1 parent 93bf702 commit bdc923c
Show file tree
Hide file tree
Showing 56 changed files with 769 additions and 241 deletions.
Binary file modified .gradle/8.2.1/checksums/checksums.lock
Binary file not shown.
Binary file modified .gradle/8.2.1/checksums/md5-checksums.bin
Binary file not shown.
Binary file modified .gradle/8.2.1/checksums/sha1-checksums.bin
Binary file not shown.
Binary file modified .gradle/8.2.1/executionHistory/executionHistory.bin
Binary file not shown.
Binary file modified .gradle/8.2.1/executionHistory/executionHistory.lock
Binary file not shown.
Binary file modified .gradle/8.2.1/fileHashes/fileHashes.bin
Binary file not shown.
Binary file modified .gradle/8.2.1/fileHashes/fileHashes.lock
Binary file not shown.
Binary file modified .gradle/8.2.1/fileHashes/resourceHashesCache.bin
Binary file not shown.
Binary file modified .gradle/buildOutputCleanup/buildOutputCleanup.lock
Binary file not shown.
Binary file modified .gradle/file-system.probe
Binary file not shown.
16 changes: 11 additions & 5 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

151 changes: 122 additions & 29 deletions .idea/workspace.xml

Large diffs are not rendered by default.

9 changes: 9 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,15 @@ repositories {
}

dependencies {
// https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
implementation 'org.apache.commons:commons-lang3:3.14.0'
// API dependency
implementation 'io.jsonwebtoken:jjwt-api:0.12.5'
// Implementation dependency
implementation 'io.jsonwebtoken:jjwt-impl:0.12.5'
// Jackson dependency (or Gson if preferred)
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.12.5'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf:3.2.3'
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file modified build/tmp/compileJava/previous-compilation-data.bin
Binary file not shown.
Binary file modified build/tmp/compileTestJava/previous-compilation-data.bin
Binary file not shown.
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) {
}
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);
}
}
}
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;
}
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());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,5 @@
public class EcommerceApiApplication {
public static void main(String[] args) {
SpringApplication.run(EcommerceApiApplication.class, args);


}

}
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();
}
}
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());
}
}
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();
}
}

This file was deleted.

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();
}
}
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);

}
}

}
Loading

0 comments on commit bdc923c

Please sign in to comment.