Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JWT 토큰 생성 시 사용자 유저 권한 정보 반환 #85

Merged
merged 7 commits into from
May 7, 2023
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ dependencies {

//jwt 라이브러리 추가 - 가장 많이 사용되는 0.9.1
implementation 'io.jsonwebtoken:jjwt:0.9.1'

//CSV 파일을 파싱하는 Java 라이브러리
implementation 'com.opencsv:opencsv:5.5.2'
}

tasks.named('test') {
Expand Down
36 changes: 36 additions & 0 deletions src/main/java/com/hallym/festival/domain/Users/APIUserService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.hallym.festival.domain.Users;

import com.hallym.festival.domain.Users.entity.APIUser;
import com.hallym.festival.domain.Users.entity.MemberRole;
import com.hallym.festival.domain.Users.repository.APIUserRepository;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;

@RequiredArgsConstructor
@ToString
@Service
@Log4j2
public class APIUserService {

private final APIUserRepository apiUserRepository;

public String getRoleSetByMid(String mid) {
APIUser apiUser = apiUserRepository.findByUserId(mid);
String role = String.join(",", apiUser.getRoleSet().stream().map(MemberRole::getValue).collect(Collectors.toList()));

log.info("해당 유저는 " + role + " 권한을 가지고 있습니다.");

if (apiUser != null) {
return role;
} else {
return "apiUser 정보를 제대로 가져오지 못했습니다";
}
}



}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ public class APIUser {
@Column(name = "phone")
private String phone;

public Set<MemberRole> getRoleSet() {
return roleSet;
}

@ElementCollection(fetch = FetchType.EAGER)
@Builder.Default
private Set<MemberRole> roleSet = new HashSet<>(); //권한 정보
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
package com.hallym.festival.domain.Users.entity;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

@AllArgsConstructor
@Getter
@RequiredArgsConstructor
public enum MemberRole {

USER("ROLE_USER"), //부스 운영 관리자
ADMIN("ROLE_ADMIN"), ; //축제 준비 위원회(총 관리자)

private String value;

MemberRole(String value) {
this.value = value;
}

public String getValue() {
return value;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@

public interface APIUserRepository extends JpaRepository<APIUser, String> {

@EntityGraph(attributePaths = "roleSet")
@Query("select m from APIUser m where m.mid = :mid")
Optional<APIUser> getWithRoles(@Param("mid") String mid); //로그인 시 Role도 같이 로딩
// @EntityGraph(attributePaths = "roleSet")
// @Query("select m from APIUser m where m.mid = :mid")
// Optional<APIUser> getWithRoles(@Param("mid") String mid); //로그인 시 Role도 같이 로딩

@Query("SELECT u FROM APIUser u WHERE u.mid = :mid") //ID에 해당하는 사용자 정보 반환
APIUser findByUserId(@Param("mid") String mid);


}
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,16 @@ public List<UploadResultDTO> upload(UploadFileDTO uploadFileDTO) {
try {
multipartFile.transferTo(savePath);

log.info("Saved file path: " + savePath);

//이미지 파일의 종류라면
if(Files.probeContentType(savePath).startsWith("image")){

image = true;

File thumbFile = new File(uploadPath, "s_" + uuid+"_"+ originalName);

Thumbnailator.createThumbnail(savePath.toFile(), thumbFile, 200,200);
Thumbnailator.createThumbnail(savePath.toFile(), thumbFile, 400,400);
}

} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class Booth extends BaseTimeEntity {
private String booth_title;

@NonNull
@Column(length = 500)
@Column(length = 1000)
private String booth_content;

@NonNull
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ public class Notice extends BaseTimeEntity {
private Long nno;
@NotNull
private String title;

@NotNull
@Column(length = 1000)
private String content;

@ColumnDefault("false")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
String path = request.getRequestURI();

if (!path.equals(refreshPath)) {
log.info("skip refresh token filter.....");
// log.info("skip refresh token filter.....");
filterChain.doFilter(request, response);
return;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package com.hallym.festival.global.security.util;

import com.hallym.festival.domain.Users.APIUserService;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

Expand All @@ -16,13 +18,23 @@
@Log4j2
public class JWTUtil {

@Autowired
private APIUserService apiUserService;

@Value("${com.hallym.festival.jwt.secret}")
private String key;

public String generateToken(Map<String, Object> valueMap, int days){ //토큰을 생성하는 기능

log.info("----------generateKey... 시크릿키 : " + key);

String mid = (String) valueMap.get("mid");

log.info(mid);

String roleSet = apiUserService.getRoleSetByMid(mid);
log.info("----------------" + roleSet);

//헤더 부분
Map<String, Object> headers = new HashMap<>();
headers.put("typ","JWT");
Expand All @@ -31,6 +43,7 @@ public String generateToken(Map<String, Object> valueMap, int days){ //토큰을
//payload 부분 설정
Map<String, Object> payloads = new HashMap<>();
payloads.putAll(valueMap);
payloads.put("role", roleSet); // role_set 정보 추가

//테스트 시에는 짧은 유효 기간
int time = (60*24) * days; //테스트는 분단위로 나중에 60*24 (일)단위변경
Expand Down
63 changes: 63 additions & 0 deletions src/test/java/com/hallym/festival/repository/UserImportTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.hallym.festival.repository;

import com.hallym.festival.domain.Users.dto.APIUserDTO;
import com.hallym.festival.domain.Users.entity.APIUser;
import com.hallym.festival.domain.Users.repository.APIUserRepository;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import javax.transaction.Transactional;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

@ExtendWith(SpringExtension.class)
@SpringBootTest
@Transactional
public class UserImportTest {

@Autowired
private APIUserRepository apiUserRepository;

@BeforeEach
public void setUp() {
apiUserRepository.deleteAll();
}

@Test
public void testCsvReader() throws IOException {
// csv 파일을 읽어올 InputStream 생성
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("test.csv").getFile());
FileInputStream inputStream = new FileInputStream(file);

// CSVReader 생성
InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
CSVReader reader = new CSVReaderBuilder(streamReader).withSkipLines(1).build();

// CSV에서 읽어온 데이터를 APIUser 엔티티로 변환하여 DB에 저장
String[] line;
while ((line = reader.readNext()) != null) {
APIUserDTO apiUserDTO = new APIUserDTO();
apiUserDTO.setMid(line[0]);
apiUserDTO.setName(line[1]);
apiUserDTO.setDepartment(line[2]);
apiUserDTO.setPhone(line[3]);
// apiUserRepository.save(apiUser);
}

// DB에 저장된 데이터 확인
List<APIUser> apiUsers = apiUserRepository.findAll();
Assertions.assertEquals(3, apiUsers.size());
}
}
32 changes: 17 additions & 15 deletions src/test/java/com/hallym/festival/service/BoothServiceTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.IntStream;

@SpringBootTest
@Log4j2
Expand All @@ -24,20 +25,21 @@ public class BoothServiceTests {

@DisplayName("부스 데이터 등록 테스트")
@Test
public void testRegister(){

BoothDTO boothDTO = BoothDTO.builder()
.booth_title("타코야끼")
.booth_content("새벽 4시 45분")
.writer("주펄")
.booth_type(BoothType.푸드트럭)
.dayNight(DayNight.DAY)
.openDay("[2,3]")
.build();

Long bno = boothService.register(boothDTO);

log.info("bno: " + bno);
public void testRegister() {
IntStream.rangeClosed(1, 10).forEach(i -> {
BoothDTO boothDTO = BoothDTO.builder()
.booth_title("부스 제목"+i)
.booth_content("부스 콘텐츠"+i)
.writer("2015434"+i)
.booth_type(BoothType.주점)
.dayNight(DayNight.DAY)
.openDay("[1,2,3]")
.build();

Long bno = boothService.register(boothDTO);

log.info("bno: " + bno);
});
}

@DisplayName("이미지를 포함한 등록 테스트")
Expand All @@ -49,7 +51,7 @@ public void testRegisterWithImages() {
BoothDTO boothDTO = BoothDTO.builder()
.booth_title("파일 첨부 게시글2")
.booth_content("테스트입니다.")
.writer("user99")
.writer("20154342")
.booth_type(BoothType.플리마켓)
.dayNight(DayNight.NIGHT)
.openDay("[2,3]")
Expand Down