Skip to content

Commit

Permalink
Merge branch 'main' into feature/build
Browse files Browse the repository at this point in the history
  • Loading branch information
wwingyou authored Mar 25, 2024
2 parents 4f5d445 + 1003d1b commit 43b756b
Show file tree
Hide file tree
Showing 15 changed files with 259 additions and 85 deletions.
80 changes: 80 additions & 0 deletions .github/workflows/auto-deployment.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
name: AWS EC2 자동 배포

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

jobs:

build:

runs-on: ubuntu-latest

env:
host: ${{ secrets.EC2_HOST }}
username: ${{ secrets.EC2_USERNAME }}

steps:
- uses: actions/checkout@v4.1.2

- name: Show git status
run: git status

- name: Setup Java JDK
uses: actions/setup-java@v4.2.1
with:
java-version: 17
distribution: temurin
java-package: jdk
architecture: x64
cache: gradle

- name: Build Jar
run: |
chmod 755 gradlew
./gradlew bootJar
working-directory: JWT

- name: Prepare SSH connect
env:
private_key: ${{ secrets.EC2_PRIVATE_KEY }}
run: |
echo "$private_key" > private_key.pem
chmod 400 private_key.pem
mkdir ~/.ssh
ssh-keyscan -t rsa $host > ~/.ssh/known_hosts
working-directory: JWT

- name: Upload deployment scripts
run: |
scp -i private_key.pem -r deploy "${username}@${host}:~"
working-directory: JWT

- name: Kill current running Spring process
uses: fifsky/ssh-action@v0.0.6
with:
command: |
sudo chmod 755 deploy/*
deploy/shutdown.sh
deploy/backup.sh
host: ${{ secrets.EC2_HOST }}
user: ${{ secrets.EC2_USERNAME }}
key: ${{ secrets.EC2_PRIVATE_KEY }}

- name: Send jar file to EC2
run: |
jarPath=$(./gradlew -q jarPath)
scp -i private_key.pem $jarPath "${username}@${host}:~/server.jar"
working-directory: JWT

- name: Run new uploaded jar
uses: fifsky/ssh-action@v0.0.6
with:
command: |
sudo chmod 755 deploy/*
deploy/startup.sh
host: ${{ secrets.EC2_HOST }}
user: ${{ secrets.EC2_USERNAME }}
key: ${{ secrets.EC2_PRIVATE_KEY }}
1 change: 1 addition & 0 deletions .idea/modules.xml

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

8 changes: 8 additions & 0 deletions .idea/modules/JWTLogIn.JWT.main.iml

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

7 changes: 7 additions & 0 deletions JWT/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ dependencies {
implementation 'io.jsonwebtoken:jjwt-impl:0.11.2'
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.2'

// Swagger
implementation 'io.springfox:springfox-boot-starter:3.0.0'
implementation 'io.springfox:springfox-swagger-ui:3.0.0'
// implementation 'io.springfox:springfox-swagger2:2.9.2'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2'


// // Spring Security
testImplementation 'org.springframework.security:spring-security-test'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
Expand Down
54 changes: 48 additions & 6 deletions JWT/src/main/java/JWTLogIn/JWT/user/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
import JWTLogIn.JWT.user.security.JwtFilter;
import JWTLogIn.JWT.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
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.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
Expand All @@ -17,26 +20,65 @@
@Configuration
@EnableWebSecurity // request를 filterchain에서 가로채도록 하는 장치
@RequiredArgsConstructor
@Log4j2
public class SecurityConfig {

private final UserService userService;

@Value("${jwt.secret}")
private String secretKey;

private static final String[] PERMIT_URL_ARRAY = {
/* swagger v2 */
"/v2/api-docs",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**",
/* swagger v3 */
"/v3/api-docs/**",
"/swagger-ui/**",
"/swagger-ui/swagger-ui-standalone-preset.js",
"/swagger-ui/swagger-initializer.js",
"/swagger-ui/swagger-ui-bundle.js",
"/swagger-ui/swagger-ui.css",
"/swagger-ui/index.css",
"/swagger-ui/favicon-32x32.png",
"/swagger-ui/favicon-16x16.png",
"/api-docs/json/swagger-config",
"/api-docs/json"
};

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
log.info("WebSecurity......................");

return web -> web.ignoring()
.requestMatchers(PathRequest.toStaticResources().atCommonLocations());
}

@Bean // 요청이 들어오면 SecurityFilterChain이 가로채서 인증, 인가를 체크함.
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

return http
.httpBasic(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable) // 토큰 사용하기에 csrf 불가능
.cors(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(request -> {
request.requestMatchers("/tgwing.kr", "/tgwing.kr/register", "/tgwing.kr/login").permitAll();
// 3개의 url에서는 token인증없이 접근 가능.
request.anyRequest().authenticated();
// 그 외의 url에서는 token인증없이 접근 불가능.
})
.authorizeHttpRequests(request -> request
.requestMatchers("/tgwing.kr", "/tgwing.kr/register", "/tgwing.kr/login")
.permitAll()
.requestMatchers(PERMIT_URL_ARRAY)
.permitAll()
.anyRequest().authenticated()
)
// .formLogin((form) -> form
// .loginPage("/tgwing.kr/login")
// .permitAll()
// )
// .logout((logout) -> logout
// .clearAuthentication(true))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// jwt를 사용하기 때문에 session을 사용하지 않음.
.addFilterBefore(new JwtFilter(userService, secretKey), UsernamePasswordAuthenticationFilter.class)
Expand Down
47 changes: 26 additions & 21 deletions JWT/src/main/java/JWTLogIn/JWT/user/controller/AdminController.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,30 +15,35 @@
import java.util.List;

@RestController
@RequestMapping("/tgwing.kr")
@RequiredArgsConstructor
public class AdminController {

private final UserService userService;
private final AuthService authService;

@GetMapping("/info/user")
public ResponseEntity<List<UserDTO>> userAll(Authentication authentication) {
public ResponseEntity<List<UserDTO>> userAll(Authentication authentication, @RequestHeader("authorization") String token) {
List<UserDTO> userAll = userService.findUserAll();
String jwt = token.split(" ")[1];
String studentId = authService.extractStudentId(jwt);

if(userAll == null)
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();

System.out.println("studentId = " + studentId);

return ResponseEntity.ok(userAll);
}

@GetMapping("/userlist")
public ResponseEntity<List<UserDTO>> userPage(Pageable pageable, @RequestHeader("authorization") String token) {
String jwt = token.split(" ")[1];
Level level = authService.extractLevel(jwt);

if(!level.equals(Level.MANAGER)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
// Level level = authService.extractLevel(jwt);
//
// if(!level.equals(Level.MANAGER)) {
// return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
// }

Page<UserDTO> userAllByPage = userService.findUserAllByPage(pageable);

Expand All @@ -48,11 +53,11 @@ public ResponseEntity<List<UserDTO>> userPage(Pageable pageable, @RequestHeader(
@PutMapping("/userlist/put/manager/{userId}")
public ResponseEntity<Void> changeAdmin(@PathVariable Long userId, @RequestHeader("authorization") String token) {
String jwt = token.split(" ")[1];
Level level = authService.extractLevel(jwt);

if(!level.equals(Level.MANAGER)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
// Level level = authService.extractLevel(jwt);
//
// if(!level.equals(Level.MANAGER)) {
// return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
// }

userService.changeLevel(userId, Level.MANAGER);

Expand All @@ -62,11 +67,11 @@ public ResponseEntity<Void> changeAdmin(@PathVariable Long userId, @RequestHeade
@PutMapping("/userlist/put/member/{userId}")
public ResponseEntity<Void> changeMember(@PathVariable Long userId, @RequestHeader("authorization") String token) {
String jwt = token.split(" ")[1];
Level level = authService.extractLevel(jwt);

if(!level.equals(Level.MANAGER)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
// Level level = authService.extractLevel(jwt);
//
// if(!level.equals(Level.MANAGER)) {
// return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
// }

userService.changeLevel(userId, Level.MEMBER);

Expand All @@ -76,11 +81,11 @@ public ResponseEntity<Void> changeMember(@PathVariable Long userId, @RequestHead
@PutMapping("/userlist/put/normal/{userId}")
public ResponseEntity<Void> changeNormal(@PathVariable Long userId, @RequestHeader("authorization") String token) {
String jwt = token.split(" ")[1];
Level level = authService.extractLevel(jwt);

if(!level.equals(Level.MANAGER)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
// Level level = authService.extractLevel(jwt);
//
// if(!level.equals(Level.MANAGER)) {
// return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
// }

userService.changeLevel(userId, Level.NORMAL);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/tgwing.kr")
@RequiredArgsConstructor
public class UserController {

Expand Down Expand Up @@ -50,7 +51,7 @@ public ResponseEntity<Void> logout() {

@DeleteMapping("/profile/delete/{id}")
public ResponseEntity<Void> deleteId(@PathVariable Long id) {
if(userService.withdrawalUser(id)) {
if(userService.deleteUser(id)) {
System.out.println("회원 삭제 완료");
return ResponseEntity.ok().build();
}
Expand Down
4 changes: 2 additions & 2 deletions JWT/src/main/java/JWTLogIn/JWT/user/dto/UserDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class UserDTO {
private Status status; // 재학/휴학 상태
private String semester; // 학년, 학기(3글자로 설정)
private String phoneNumber; // 전화번호(13글자로 설정)
private Level level;// 일반, 동아리, 관리인 3가지 분류
// private Level level;// 일반, 동아리, 관리인 3가지 분류


public static UserEntity toUserEntity(UserDTO userDTO) {
Expand All @@ -33,7 +33,7 @@ public static UserEntity toUserEntity(UserDTO userDTO) {
.status(userDTO.getStatus())
.semester(userDTO.getSemester())
.phoneNumber(userDTO.getPhoneNumber())
.level(userDTO.getLevel())
// .level(userDTO.getLevel())
.build();
}
}
7 changes: 4 additions & 3 deletions JWT/src/main/java/JWTLogIn/JWT/user/entity/UserEntity.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import JWTLogIn.JWT.user.dto.UserDTO;
import JWTLogIn.JWT.user.entity.Enum.Level;
import JWTLogIn.JWT.user.entity.Enum.Status;
import com.fasterxml.jackson.annotation.JsonValue;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.DynamicInsert;
Expand Down Expand Up @@ -40,8 +41,8 @@ public class UserEntity extends BaseEntity{
@Column(nullable = false, unique = true, length = 13)
private String phoneNumber; // 전화번호(13글자로 설정)

@Column(length = 7)
private Level level;
// @Column(length = 7)
// private Level level;

// 연관매핑: 일대다
// 참조 당하는 엔티티에서 사용
Expand All @@ -60,7 +61,7 @@ public static UserDTO toUserDTO(UserEntity userEntity) {
.status(userEntity.getStatus())
.semester(userEntity.getSemester())
.phoneNumber(userEntity.getPhoneNumber())
.level(userEntity.getLevel())
// .level(userEntity.getLevel())
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@ public interface UserRepository extends JpaRepository<UserEntity, Long> {
@Query("DELETE FROM UserEntity U WHERE U.id = :id")
void deleteUser(@Param("id") Long id);

@Modifying
@Transactional
@Query("UPDATE UserEntity u SET " +
"u.level = :level " +
"WHERE u.id = :id")
void changeLv (@Param("id") Long id, @Param("level") Level level);
// @Modifying
// @Transactional
// @Query("UPDATE UserEntity u SET " +
// "u.level = :level " +
// "WHERE u.id = :id")
// void changeLv (@Param("id") Long id, @Param("level") Level level);


// @Query("UPDATE BoardEntity b SET " +
Expand Down
Loading

0 comments on commit 43b756b

Please sign in to comment.