Skip to content

Commit

Permalink
Merge pull request #84 from 0702Yoon/main
Browse files Browse the repository at this point in the history
멤버 상세 조회, 멤버 이름 변경 등 기능 구현
  • Loading branch information
0702Yoon authored Aug 14, 2024
2 parents 47aac67 + 1cf7199 commit 067ec8e
Show file tree
Hide file tree
Showing 13 changed files with 112 additions and 39 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.example.bigbrotherbe.domain.member.controller;

import com.example.bigbrotherbe.domain.member.dto.request.ChangePasswordRequest;
import com.example.bigbrotherbe.domain.member.dto.request.MemberInfoChangeRequest;
import com.example.bigbrotherbe.domain.member.dto.request.MemberRequest;
import com.example.bigbrotherbe.domain.member.dto.request.SignUpDto;
import com.example.bigbrotherbe.domain.member.dto.response.AffiliationCollegeResponse;
Expand Down Expand Up @@ -68,7 +69,7 @@ public interface MemberController {
@Operation(summary = "이메일 인증 코드 검증")
ResponseEntity<com.example.bigbrotherbe.global.exception.response.ApiResponse<EmailVerificationResult>> verificationEmail(@RequestParam(name = "email") String email, @RequestParam(name = "code") String code);

@PatchMapping()
@PatchMapping("/password")
@Operation(summary = "비밀번호 변경")
ResponseEntity<com.example.bigbrotherbe.global.exception.response.ApiResponse<Void>> changePassword(@RequestBody ChangePasswordRequest changePasswordRequest);

Expand All @@ -85,7 +86,7 @@ public interface MemberController {
@Operation(summary = "유저 탈퇴")
ResponseEntity<com.example.bigbrotherbe.global.exception.response.ApiResponse<Void>> memberDeleteSelf();

// @PatchMapping
// ? @Operation(summary = "유저 상세 정보 변경")
// ResponseEntity<com.example.bigbrotherbe.global.exception.response.ApiResponse<MemberInfoResponse>> changeMemberInfo(@RequestBody MemberInfoChangeRequest memberInfoChangeRequest);
@PatchMapping("/information")
@Operation(summary = "유저 상세 정보 변경")
ResponseEntity<com.example.bigbrotherbe.global.exception.response.ApiResponse<MemberInfoResponse>> changeMemberInfo(@RequestBody MemberInfoChangeRequest memberInfoChangeRequest);
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.example.bigbrotherbe.domain.member.controller;

import com.example.bigbrotherbe.domain.member.dto.request.ChangePasswordRequest;
import com.example.bigbrotherbe.domain.member.dto.request.MemberInfoChangeRequest;
import com.example.bigbrotherbe.domain.member.dto.request.MemberRequest;
import com.example.bigbrotherbe.domain.member.dto.request.SignUpDto;
import com.example.bigbrotherbe.domain.member.dto.response.AffiliationCollegeResponse;
Expand All @@ -10,9 +11,7 @@
import com.example.bigbrotherbe.global.email.EmailRequest;
import com.example.bigbrotherbe.global.email.EmailVerificationResult;
import com.example.bigbrotherbe.global.exception.response.ApiResponse;
import com.example.bigbrotherbe.global.jwt.AuthUtil;
import com.example.bigbrotherbe.global.jwt.JwtToken;
import com.example.bigbrotherbe.global.jwt.JwtTokenProvider;
import com.example.bigbrotherbe.domain.member.service.MemberService;

import com.example.bigbrotherbe.global.jwt.entity.TokenDto;
Expand Down Expand Up @@ -90,4 +89,10 @@ public ResponseEntity<ApiResponse<Void>> memberDeleteSelf() {
memberService.deleteSelf();
return ResponseEntity.ok(ApiResponse.success(SUCCESS));
}

@Override
public ResponseEntity<ApiResponse<MemberInfoResponse>> changeMemberInfo(
MemberInfoChangeRequest memberInfoChangeRequest) {
return ResponseEntity.ok(ApiResponse.success(SUCCESS,memberService.changeMemberInfo(memberInfoChangeRequest.userName())));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.example.bigbrotherbe.domain.member.dto.request;



public record MemberInfoChangeRequest(String userName) {

}
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,12 @@ public class SignUpDto {

@Email(message = "이메일 형식에 맞지 않습니다.")
@NotBlank(message = "사용자 이메일을 입력해주세요.")
@Schema(description = "사용자 이메일", example = "test123@mju.ac.kr")
@Schema(description = "사용자 이메일", example = "gkstkddbs99@mju.ac.kr")
private String email;
private String councilType;

@Schema(description = "단과대", example = "ICT융합대학")
private String college;
@Schema(description = "학과, 전공", example = "응용소프트웨어전공")
private String affiliation;

public Member toEntity(SignUpDto signUpDto, String encodePassword) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,18 @@ public class MemberResponse {
private final String memberName;
private final String email;
private final LocalDateTime create_at;
private final String councilType;
private final String affiliationName;
private final String college;
private final String affiliation;

public static MemberResponse form(Long id, String username, String email, LocalDateTime createAt, String councilType, String affiliationName) {
public static MemberResponse form(Long id, String username, String email, LocalDateTime createAt, String college, String affiliation) {
return MemberResponse
.builder()
.id(id)
.memberName(username)
.email(email)
.create_at(createAt)
.councilType(councilType)
.affiliationName(affiliationName)
.college(college)
.affiliation(affiliation)
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,8 @@ public void changePassword(String memberPass) {
private static boolean isValidEmail(String email) {
return EMAIL_PATTERN.matcher(email).matches();
}

public void changeName(String username) {
this.username = username;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;

@Entity
@Builder
Expand All @@ -25,7 +24,7 @@ public class Affiliation {
private String studentCouncil;

@Column
private String affiliationName;
private String name;

@Column
private String presidentName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
import org.springframework.data.jpa.repository.JpaRepository;

public interface AffiliationRepository extends JpaRepository<Affiliation, Long> {
Optional<Affiliation> findByAffiliationName(String affiliationName);
Optional<Affiliation> findByName(String name);
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,6 @@ public interface MemberService {
TokenDto refreshToken(String refreshToken);

void deleteSelf();

MemberInfoResponse changeMemberInfo(String userName);
}
Original file line number Diff line number Diff line change
Expand Up @@ -75,20 +75,32 @@ public MemberResponse userSignUp(SignUpDto signUpDto) {


// Affiliation 조회
Affiliation affiliation = affiliationRepository.findByAffiliationName(signUpDto.getAffiliation())
log.info(signUpDto.getCollege() +" " + signUpDto.getAffiliation());
Affiliation college = affiliationRepository.findByName(signUpDto.getCollege())
.orElseThrow(() -> new BusinessException(ErrorCode.NO_EXIST_AFFILIATION));

// AffiliationMember 엔티티 생성
AffiliationMember affiliationMember = AffiliationMember.builder()
AffiliationMember memberCollage = AffiliationMember.builder()
.member(savedMember)
.affiliation(affiliation)
.affiliation(college)
.role("ROLE_USER")
.build();
affiliationMemberRepository.save(affiliationMember);
affiliationMemberRepository.save(memberCollage);

Affiliation affiliation = affiliationRepository.findByName(signUpDto.getAffiliation())
.orElseThrow(() -> new BusinessException(ErrorCode.NO_EXIST_AFFILIATION));

AffiliationMember memberAffiliation = AffiliationMember.builder()
.member(savedMember)
.affiliation(affiliation)
.role("ROLE_USER")
.build();

affiliationMemberRepository.save(memberAffiliation);

savedMember = memberLoader.getMember(savedMember.getId());

return MemberResponse.form(savedMember.getId(), savedMember.getUsername(), savedMember.getEmail(), savedMember.getCreateAt(), affiliation.getCouncilType(), affiliation.getAffiliationName());
return MemberResponse.form(savedMember.getId(), savedMember.getUsername(), savedMember.getEmail(), savedMember.getCreateAt(), college.getName(), affiliation.getName());
}

@Transactional
Expand Down Expand Up @@ -186,7 +198,7 @@ public void changePasswrd(String email,String password) {
@Override
@Transactional
public void makeAffiliation() {
affiliationRepository.save(Affiliation.builder().affiliation_id(1L).affiliationName("총학").build());
affiliationRepository.save(Affiliation.builder().affiliation_id(1L).name("총학").build());
}

public List<AffiliationCollegeResponse> getColleges() {
Expand Down Expand Up @@ -225,6 +237,20 @@ public void deleteSelf() {
memberDeleter.deleteMember(member);
}

@Override
public MemberInfoResponse changeMemberInfo(String username) {
Member member = authUtil.getLoginMember();
member.changeName(username);
return MemberInfoResponse
.builder()
.email(member.getEmail())
.memberName(member.getUsername())
.createAt(member.getCreateAt())
.updateAt(member.getUpdateAt())
.affiliationListDto(getMemberAffiliationRoleList())
.build();
}

public List<AffiliationCode> getDepartmentsByFaculty(AffiliationCode faculty) {
return AffiliationCode.getDepartmentsByCollege(faculty);
}
Expand All @@ -242,7 +268,7 @@ private AffiliationListDto affiliationListToEntity(String userName, List<Affilia

for (AffiliationMember affiliationMember : affiliationMemberList) {
Affiliation affiliation = affiliationMember.getAffiliation();
affiliationListDto.addAffiliation(affiliation.getCouncilType(), affiliation.getAffiliationName(), affiliationMember.getRole());
affiliationListDto.addAffiliation(affiliation.getCouncilType(), affiliation.getName(), affiliationMember.getRole());
}
return affiliationListDto;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@ public class InitialDataLoader {
public CommandLineRunner loadData(MemberRepository memberRepository, AffiliationRepository affiliationRepository,
AffiliationMemberRepository affiliationMemberRepository, PasswordEncoder passwordEncoder) {
return args -> {
if (affiliationRepository.findByAffiliationName("응용소프트웨어전공").isEmpty()) {
affiliationRepository.save(Affiliation.builder().affiliation_id(1L).affiliationName("응용소프트웨어전공").councilType("단과대").build());
if (affiliationRepository.findByName("응용소프트웨어전공").isEmpty()) {
affiliationRepository.save(Affiliation.builder().affiliation_id(1L).name("응용소프트웨어전공").councilType("학과").build());
}

if (affiliationRepository.findByAffiliationName("디지털콘텐츠디자인학과").isEmpty()) {
affiliationRepository.save(Affiliation.builder().affiliation_id(2L).affiliationName("디지털콘텐츠디자인학과").councilType("학과").build());

if (affiliationRepository.findByName("디지털콘텐츠디자인학과").isEmpty()) {
affiliationRepository.save(Affiliation.builder().affiliation_id(2L).name("디지털콘텐츠디자인학과").councilType("학과").build());
}
if (affiliationRepository.findByName("ICT융합대학").isEmpty()) {
affiliationRepository.save(Affiliation.builder().affiliation_id(3L).name("ICT융합대학").councilType("단과대").build());
}
// Check if an admin user already exists
if (memberRepository.findByUsername("admin").isEmpty()) {
Expand All @@ -36,7 +38,7 @@ public CommandLineRunner loadData(MemberRepository memberRepository, Affiliation
admin.setEmail("[email protected]");
admin.setUsername("admin");
memberRepository.save(admin);
Affiliation affiliation = affiliationRepository.findByAffiliationName("응용소프트웨어전공")
Affiliation affiliation = affiliationRepository.findByName("응용소프트웨어전공")
.orElseThrow(() -> new IllegalArgumentException("잘못된 소속 이름입니다."));

// AffiliationMember 엔티티 생성
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package com.example.bigbrotherbe.global.jwt;
import com.example.bigbrotherbe.global.exception.BusinessException;
import com.example.bigbrotherbe.global.exception.response.ApiResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -20,17 +24,33 @@ public class JwtAuthenticationFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;

String token = resolveToken(request);
if (token != null && jwtTokenProvider.validateToken(token) && jwtTokenProvider.checkTokenType(token)) {
// 유효한 엑세스 토큰이 있는 경우
Authentication authentication = jwtTokenProvider.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
try {
String token = resolveToken(request);
if (token != null && jwtTokenProvider.validateToken(token)
&& jwtTokenProvider.checkTokenType(token)) {
// 유효한 엑세스 토큰이 있는 경우
Authentication authentication = jwtTokenProvider.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(servletRequest, servletResponse);
}
catch (BusinessException e) {
handleException((HttpServletResponse) servletResponse, e);
// 예외 처리 로직
}

filterChain.doFilter(servletRequest, servletResponse);
}
private void handleException(HttpServletResponse response, BusinessException e) throws IOException {

if (e != null) {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
String jsonResponse = new ObjectMapper().writeValueAsString(ApiResponse.error(e.getErrorCode()));
response.getWriter().write(jsonResponse); // ApiResponse의 내용을 JSON으로 변환하여 작성
} else {
response.getWriter().write("{\"error\": \"An unexpected error occurred.\"}");
}
}
private String resolveToken(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,16 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.requestMatchers(SERVER+"/members/sign-in").permitAll()
.requestMatchers(SERVER+"/members/sign-up/**").permitAll()
.requestMatchers(SERVER+"/members/refresh").permitAll()
.requestMatchers(HttpMethod.PATCH,SERVER+"/members").permitAll()

// USER 권한이 있어야 요청할 수 있음
.requestMatchers(SERVER+"/members/test").hasRole("USER")
.requestMatchers(SERVER+"/members/test").hasAnyRole("ADMIN","USER")
.requestMatchers(SERVER+"/members").hasAnyRole("ADMIN","USER")
// 유저 어드민 권한이 있어야 요청할 수 있음
.requestMatchers(SERVER+"/members/password").hasAnyRole("ADMIN","USER")
.requestMatchers(SERVER+"/members/manager").hasRole("ADMIN")
.requestMatchers(SERVER+"members/information").hasAnyRole("ADMIN","USER")
// 이 밖에 모든 요청에 대해서 인증을 필요로 한다는 설정
.anyRequest().permitAll()
.anyRequest().authenticated()
)
// JWT 인증을 위하여 직접 구현한 필터를 UsernamePasswordAuthenticationFilter 전에 실행
.addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider),
Expand Down

0 comments on commit 067ec8e

Please sign in to comment.