Skip to content

Commit

Permalink
remove all
Browse files Browse the repository at this point in the history
  • Loading branch information
hervtart committed Oct 16, 2023
1 parent e6a010d commit 19fe209
Show file tree
Hide file tree
Showing 15 changed files with 339 additions and 15 deletions.
1 change: 0 additions & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-mail")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.security:spring-security-test")
implementation("ch.qos.logback:logback-core")
implementation("ch.qos.logback:logback-classic")
Expand Down
32 changes: 28 additions & 4 deletions src/main/java/com/gapple/weeingback/WeeingBackApplication.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,37 @@
package com.gapple.weeingback;

import com.gapple.weeingback.domain.user.entity.User;
import com.gapple.weeingback.domain.user.service.UserService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

@SpringBootApplication
public class WeeingBackApplication {

public static void main(String[] args) {
public static void main(String[] args) throws IOException {
SpringApplication.run(WeeingBackApplication.class, args);
}

}
Scanner scanner = new Scanner(System.in);
BigInteger a = scanner.nextBigInteger();
BigInteger b = scanner.nextBigInteger();
System.out.println(a.add(b));
System.out.println(a.subtract(b));
System.out.println(a.multiply(b));
}
}
22 changes: 17 additions & 5 deletions src/main/java/com/gapple/weeingback/domain/check/entity/Check.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,29 @@

import com.gapple.weeingback.domain.user.entity.User;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;

@Table
@Entity(name = "CHECK_TABLE")
@Entity
@Getter @Setter
public class Check {
@Id @GeneratedValue
@Column(name = "CHECK_ID")
private Long id;
private Long checkId;
private Long issuedAt; // 상담 신청 일자
private Long start; // 언제 가야하는지
private boolean isTrue; // 선생님이 승인했는지r
private Long startAt; // 언제 가야하는지
private boolean isAccess = false; // 선생님이 승인했는지
private boolean isTrue = false; // 활성화된 Check 인지

@OneToOne(mappedBy = "check")
private User user;

public Check(boolean isTrue){
this.isTrue = isTrue;
}

public Check(){}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.gapple.weeingback.domain.user.controller;

import com.gapple.weeingback.domain.user.entity.User;
import com.gapple.weeingback.domain.user.entity.dto.UserJoinRequest;
import com.gapple.weeingback.domain.user.entity.dto.UserLoginRequest;
import com.gapple.weeingback.domain.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
private final UserService userService;

@PostMapping("/join")
public void join(@RequestBody UserJoinRequest request) throws Exception {
userService.join(request);
}

@PostMapping("/login")
public void login(@RequestBody UserLoginRequest request){
userService.login(request);
}

@PostMapping("/token")
public String giveToken(@RequestBody UserLoginRequest request){
userService.token(request);
return null;
}

@GetMapping("/")
public String hello(@AuthenticationPrincipal Object principal){
return principal.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,22 @@

import com.gapple.weeingback.domain.check.entity.Check;
import jakarta.persistence.*;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;

@Table
@Entity(name = "USER_TABLE")
@Entity
@Getter @Setter
public class User {
@Id @GeneratedValue
@Column(name = "USER_ID")
private Long id;
private String name;
private String email;
private String password;
private UserRole role;

@OneToOne
@JoinTable(name = "CHECK_ID")
@JoinColumn(name = "check_id")
private Check check;
// private UserRole role;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.gapple.weeingback.domain.user.entity.dto;

import com.gapple.weeingback.domain.user.entity.UserRole;
import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public class UserJoinRequest {
private String name;
private String email;
private String password;
// private UserRole userRole;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.gapple.weeingback.domain.user.entity.dto;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public class UserLoginRequest {
private String email;
private String password;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.gapple.weeingback.domain.user.repository;

import com.gapple.weeingback.domain.user.entity.User;
import lombok.RequiredArgsConstructor;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
boolean existsUserByEmail(String email);
User findUserByEmail(String email);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.gapple.weeingback.domain.user.service;

import com.gapple.weeingback.domain.check.entity.Check;
import com.gapple.weeingback.domain.user.entity.User;

import com.gapple.weeingback.domain.user.entity.dto.UserJoinRequest;
import com.gapple.weeingback.domain.user.entity.dto.UserLoginRequest;
import com.gapple.weeingback.domain.user.repository.UserRepository;
import com.gapple.weeingback.global.jwt.JwtProvider;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;

@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private JwtProvider jwtProvider = new JwtProvider();

public void join(UserJoinRequest request) throws Exception{
User user = new User();
user.setName(request.getName());
user.setEmail(request.getEmail());
user.setPassword(request.getPassword());
user.setCheck(new Check());

if(!userRepository.existsUserByEmail(request.getEmail())) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
userRepository.save(user);
}
else throw new Exception();
}

public String login(UserLoginRequest request){
Authentication authentication = new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword());
SecurityContextHolder.getContext().setAuthentication(authentication);
return authentication.getName();
}

public String token(UserLoginRequest request){
User user = userRepository.findUserByEmail(request.getEmail());
if(passwordEncoder.matches(request.getPassword(), user.getPassword())){
// jwtProvider.generateToken();
}
return null;
}
}
25 changes: 25 additions & 0 deletions src/main/java/com/gapple/weeingback/global/config/AppConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.gapple.weeingback.global.config;

import com.gapple.weeingback.domain.user.repository.UserRepository;
import com.gapple.weeingback.domain.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@RequiredArgsConstructor
public class AppConfig {
private final UserRepository userRepository;

@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}

@Bean
public UserService userService(){
return new UserService(userRepository, passwordEncoder());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.gapple.weeingback.global.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 static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
http.authorizeHttpRequests(request -> request
.requestMatchers("/user/**").permitAll()
.anyRequest().authenticated()
)
.httpBasic(withDefaults());
// .formLogin(withDefaults());

http.sessionManagement((sessionManagement) ->
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
); // Don't use Session

http.csrf(AbstractHttpConfigurer::disable);

return http.build();
}
}
56 changes: 56 additions & 0 deletions src/main/java/com/gapple/weeingback/global/filter/JwtFilter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.gapple.weeingback.global.filter;

import com.gapple.weeingback.global.jwt.JwtProvider;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
public class JwtFilter extends GenericFilter {
public static final String AUTHORIZATION_HEADER = "Authorization";

private final JwtProvider provider;

public JwtFilter(JwtProvider provider){
this.provider = provider;
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

System.out.println("doFilter");

HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String jwt = resolveToken(httpServletRequest);
String requestURI = httpServletRequest.getRequestURI();

// 토큰 유효성 검증 후 정상이면 SecurityContext에 저장
if(StringUtils.hasText(jwt) && provider.validateToken(jwt)){ // TODO 토큰 검증 만들기
Authentication authentication = provider.getAuthentication(jwt); // TODO 토큰 인증 주기
SecurityContextHolder.getContext().setAuthentication(authentication);
log.debug("Security Context에 '{}' 인증 정보를 저장했습니다, uri: {}",authentication.getName(),requestURI);
}

else log.debug("유효한 JWT 토큰이 없습니다, uri: {}",requestURI);

// 생성한 필터 실행
chain.doFilter(httpServletRequest,response);
}

// Request Header에서 토큰 정보를 꺼내오기
private String resolveToken(HttpServletRequest request){
String bearerToken = request.getHeader(AUTHORIZATION_HEADER);
if(StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")){

System.out.println("token : " + bearerToken);

return bearerToken.substring(7);
}
return null;
}
}
33 changes: 33 additions & 0 deletions src/main/java/com/gapple/weeingback/global/jwt/JwtProvider.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.gapple.weeingback.global.jwt;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.Authentication;

import java.security.Key;
import java.util.Date;

public class JwtProvider {
private String secret = "1234lbvyv1giuyr1fvbh3uy1jrgbv";
private Key key;

public JwtProvider(){


}

public String generateToken(String email, String type, Long expired){
String token = Jwts.builder()
.setSubject(type)
.setAudience(email)
.setExpiration(new Date(System.currentTimeMillis() + 1000L))
.setIssuedAt(new Date(System.currentTimeMillis()))
// .signWith(new Key, SignatureAlgorithm.HS256)
.compact();
return token;
}

public Authentication getAuthentication(String token){

}
}
Loading

0 comments on commit 19fe209

Please sign in to comment.