Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
s2hoon committed Jan 8, 2024
2 parents 06af214 + 142874e commit 8de82ca
Show file tree
Hide file tree
Showing 25 changed files with 583 additions and 174 deletions.
72 changes: 72 additions & 0 deletions .github/workflows/gradle.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
name: Java CI with Gradle

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

permissions:
contents: read

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v2
with:
java-version: '17'
distribution: 'temurin'
## gradle caching
- name: Gradle Caching
uses: actions/cache@v2
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-
## create application-prod.properties
- name: make application-prod.properties
if: contains(github.ref, 'main') # branch가 main 일 때, 나머지는 위와 동일
run: |
cd ./src/main/resources
touch ./application-prod.properties
echo "${{ secrets.PROPERTIES_PROD }}" > ./application-prod.properties
shell: bash

## gradle build
- name: Build with Gradle
run: ./gradlew build -x test

## docker build & push to production
- name: Docker build & push to prod
if: contains(github.ref, 'main')
run: |
docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }}
docker build -f Dockerfile-prod -t ${{ secrets.DOCKER_USERNAME }}/studyflex .
docker push ${{ secrets.DOCKER_USERNAME }}/studyflex

## deploy to production
- name: Deploy to prod
uses: appleboy/ssh-action@master
id: deploy-prod
if: contains(github.ref, 'main')
with:
host: ${{ secrets.HOST_PROD }}
username: ubuntu
key: ${{ secrets.SSH_KEY }}
envs: GITHUB_SHA
script: |
sudo docker stop studyflex
sudo docker rm studyflex
sudo docker pull ${{ secrets.DOCKER_USERNAME }}/studyflex
sudo docker run -d -p 8080:8080 --name studyflex ${{ secrets.DOCKER_USERNAME }}/studyflex
sudo docker image prune -f
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ dependencies {
// school web mail
implementation 'com.github.in-seo:univcert:master-SNAPSHOT'

// password mail
implementation 'org.springframework.boot:spring-boot-starter-mail'


compileOnly 'org.projectlombok:lombok'
Expand Down
73 changes: 25 additions & 48 deletions src/main/java/com/umc/StudyFlexBE/config/jwt/JwtTokenProvider.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
package com.umc.StudyFlexBE.config.jwt;
//import org.springframework.security.core.userdetails.User;
import com.umc.StudyFlexBE.security.CustomUserDetails;
import io.jsonwebtoken.*;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
Expand All @@ -12,14 +22,9 @@
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
@Slf4j
Expand All @@ -31,6 +36,7 @@ public class JwtTokenProvider implements InitializingBean {

@Value("${jwt.token-validity-in-seconds}")
private long tokenValidityInMilliseconds;

private Key key;


Expand All @@ -41,35 +47,26 @@ public void afterPropertiesSet() throws Exception {
}

public String createToken(Authentication authentication) {

Long memberId = null;
if (authentication.getPrincipal() instanceof CustomUserDetails) {
CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
memberId = userDetails.getMemberId();
}

String authorities = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(","));

// 토큰의 expire 시간을 설정
long now = (new Date()).getTime();
Date validity = new Date(now + this.tokenValidityInMilliseconds);

JwtBuilder builder = Jwts.builder()
return Jwts.builder()
.setSubject(authentication.getName())
.claim(AUTHORITIES_KEY, authorities)
.signWith(SignatureAlgorithm.forName("HS512"), key)
.setExpiration(validity);

if (memberId != null) {
builder.claim("memberId", memberId);
}
return builder.compact();
.claim(AUTHORITIES_KEY, authorities) // 정보 저장
.signWith(key, SignatureAlgorithm.HS512) // 사용할 암호화 알고리즘과 , signature 에 들어갈 secret값 세팅
.setExpiration(validity) // set Expire Time 해당 옵션 안넣으면 expire안함
.compact();
}

// 토큰으로 클레임을 만들고 이를 이용해 유저 객체를 만들어서 최종적으로 authentication 객체를 리턴
public Authentication getAuthentication(String token) {
Claims claims = Jwts.parserBuilder()
Claims claims = Jwts
.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
Expand All @@ -80,31 +77,11 @@ public Authentication getAuthentication(String token) {
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());


CustomUserDetails principal = new CustomUserDetails(
claims.get("memberId", Long.class),
claims.getSubject(),
"",
authorities,
true,
true,
true,
true
);
User principal = new User(claims.getSubject(), "", authorities);

return new UsernamePasswordAuthenticationToken(principal, token, authorities);
}

public Long getMemberIdFromToken(String token) {
Claims claims = Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.getBody();

return claims.get("memberId", Long.class);
}

// 토큰의 유효성 검증을 수행
public boolean validateToken(String token) {
try {
Expand All @@ -125,4 +102,4 @@ public boolean validateToken(String token) {
}
return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@
import com.umc.StudyFlexBE.service.ComplaintService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import com.umc.StudyFlexBE.security.CustomUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
Expand All @@ -29,10 +32,8 @@ public ResponseEntity<BaseResponse<ComplaintResponseDto>> postComplaint(
@RequestBody ComplaintRequestDto request) {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
Long memberId = userDetails.getMemberId();

ComplaintResponseDto complaintResponse = complaintService.postComplaint(memberId, studyId, request);
String email = authentication.getName();
ComplaintResponseDto complaintResponse = complaintService.postComplaint(email, studyId, request);
return ResponseEntity.ok(new BaseResponse<>(BaseResponseStatus.SUCCESS, complaintResponse));
} catch (Exception e) {
return ResponseEntity.internalServerError().body(new BaseResponse<>(BaseResponseStatus.BAD_REQUEST));
Expand Down
24 changes: 13 additions & 11 deletions src/main/java/com/umc/StudyFlexBE/controller/InquiryController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,25 @@

import com.umc.StudyFlexBE.dto.request.Inquiry.InquiryAnswerRequestDto;
import com.umc.StudyFlexBE.dto.request.Inquiry.InquiryUploadRequestDto;
import com.umc.StudyFlexBE.dto.response.*;
import com.umc.StudyFlexBE.dto.response.BaseResponse;
import com.umc.StudyFlexBE.dto.response.BaseResponseStatus;
import com.umc.StudyFlexBE.dto.response.Inquiry.InquiryAnswerResponseDto;
import com.umc.StudyFlexBE.dto.response.Inquiry.InquiryListResponseDto;
import com.umc.StudyFlexBE.dto.response.Inquiry.InquiryResponseDto;
import com.umc.StudyFlexBE.dto.response.Inquiry.InquiryUploadResponseDto;
import com.umc.StudyFlexBE.entity.Inquiry;
import com.umc.StudyFlexBE.security.CustomUserDetails;
import com.umc.StudyFlexBE.service.InquiryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/app/inquiry")
Expand All @@ -31,10 +37,8 @@ public ResponseEntity<BaseResponse<InquiryUploadResponseDto>> postInquiry(
@RequestBody InquiryUploadRequestDto request) {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
Long memberId = userDetails.getMemberId();

Inquiry inquiry = inquiryService.createInquiry(memberId, request);
String email = authentication.getName();
Inquiry inquiry = inquiryService.createInquiry(email, request);
return ResponseEntity.ok(new BaseResponse<>(BaseResponseStatus.SUCCESS, new InquiryUploadResponseDto(inquiry.getId())));
} catch (Exception e) {
return ResponseEntity.internalServerError().body(new BaseResponse<>(BaseResponseStatus.BAD_REQUEST));
Expand Down Expand Up @@ -78,10 +82,8 @@ public ResponseEntity<BaseResponse<InquiryAnswerResponseDto>> postAnswer(
@RequestBody InquiryAnswerRequestDto request) {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
Long memberId = userDetails.getMemberId();

InquiryAnswerResponseDto inquiryAnswerResponse = inquiryService.postAnswer(inquiryId, request, memberId);
String email = authentication.getName();
InquiryAnswerResponseDto inquiryAnswerResponse = inquiryService.postAnswer(inquiryId, request, email);
return ResponseEntity.ok(new BaseResponse<>(BaseResponseStatus.SUCCESS, inquiryAnswerResponse));
} catch (Exception e) {
return ResponseEntity.internalServerError().body(new BaseResponse<>(BaseResponseStatus.BAD_REQUEST));
Expand Down
Loading

0 comments on commit 8de82ca

Please sign in to comment.