Skip to content

Commit

Permalink
Merge pull request #9 from STUDIO-EYE/feat/EPIC-136]-user
Browse files Browse the repository at this point in the history
[Feat/epic 136] user
  • Loading branch information
ibaesuyeon authored Apr 27, 2024
2 parents 23692c9 + 3efb08f commit 58f0117
Show file tree
Hide file tree
Showing 11 changed files with 82 additions and 41 deletions.
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
package com.example.UserService.config;

import com.example.UserService.domain.Role;
import com.example.UserService.dto.JWTAuthResponse;
import com.example.UserService.service.RedisService;
import io.jsonwebtoken.*;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
Expand Down Expand Up @@ -47,14 +45,12 @@ protected void init() {
}

// generate JWT token
// public JWTAuthResponse generateToken(String email, Authentication authentication, Long userId) {
public JWTAuthResponse generateToken(String email, Authentication authentication, Long userId, Role role) {
public JWTAuthResponse generateToken(String email, Authentication authentication, Long userId) {
String username = authentication.getName();

Claims claims = Jwts.claims().setSubject(email);
claims.put("username", username);
claims.put("userId", userId);
claims.put("role", role);

Date currentDate = new Date();
Date accessTokenExpireDate = new Date(currentDate.getTime() + ACCESS_TOKEN_VALID_TIME);
Expand All @@ -81,7 +77,6 @@ public JWTAuthResponse generateToken(String email, Authentication authentication
response.setRefreshToken(refreshToken);
response.setTokenType(BEARER);
response.setAccessTokenExpireDate(ACCESS_TOKEN_VALID_TIME);
response.setRole(role);
response.setId(userId);
return response;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,23 +31,23 @@ public class UserController {
private final JwtTokenProvider jwtTokenProvider;

@GetMapping("/health_check")
public String status(){
public String status() {
return "It's Working in User Service";
}

@GetMapping("/welcome")
public String welcome(){
public String welcome() {
return env.getProperty("greeting.message");
}

@PostMapping("/login")
public ResponseEntity<JWTAuthResponse> login(@RequestBody RequestLogin requestLogin){
public ResponseEntity<JWTAuthResponse> login(@RequestBody RequestLogin requestLogin) {
JWTAuthResponse token = userService.login(requestLogin);
return ResponseEntity.ok(token);
}

@PostMapping("/register")
public ResponseEntity<String> register(@RequestBody RequestUser requestUser){
public ResponseEntity<String> register(@RequestBody RequestUser requestUser) {
String response = userService.register(requestUser);
return new ResponseEntity<>(response, HttpStatus.CREATED);
}
Expand Down Expand Up @@ -87,7 +87,7 @@ public ResponseEntity<List<Long>> getAllApprovedUserIds() {
//토큰 재발급
@PatchMapping("/reissue")
public ResponseEntity<JWTAuthResponse> reissue(HttpServletRequest request,
HttpServletResponse response) {
HttpServletResponse response) {

String refreshToken = jwtTokenProvider.resolveRefreshToken(request);
JWTAuthResponse newAccessToken = userService.reissueAccessToken(refreshToken);
Expand Down Expand Up @@ -116,5 +116,19 @@ public ResponseEntity verificationEmail(@RequestParam("email") @Valid @Email Str
public ResponseEntity unregister(@RequestParam("userId") @Valid Long userId) {
return userService.unregister(userId);
}
}

//모든 회원 정보 반환
@GetMapping("/users")
public ResponseEntity<List<UserResponse>> getAllUsers() {
List<UserResponse> users = userService.getAllUsers();
return ResponseEntity.ok(users);
}

//승인 여부 변경
@PutMapping("/approve")
public ResponseEntity approveUser(@RequestParam("userId") @Valid Long userId,
@RequestParam("approved") boolean approved) {
boolean isApproved = userService.updateApproved(userId, approved);
return ResponseEntity.ok().body(isApproved);
}
}
15 changes: 0 additions & 15 deletions src/main/java/com/example/UserService/domain/Role.java

This file was deleted.

8 changes: 5 additions & 3 deletions src/main/java/com/example/UserService/domain/UserEntity.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.CreatedDate;

import java.time.LocalDate;
import java.util.Optional;

@Setter
Expand Down Expand Up @@ -36,9 +38,9 @@ public class UserEntity {
@Column(nullable = false)
private boolean isApproved;

@Enumerated(EnumType.STRING)
@Column(nullable = false)
private Role role;
@CreatedDate
private LocalDate createdAt;

private UserEntity(Optional<UserEntity> userEntity) {
this.id = id;
Expand All @@ -48,7 +50,7 @@ private UserEntity(Optional<UserEntity> userEntity) {
this.phoneNumber = phoneNumber;
this.encryptedPwd = encryptedPwd;
this.isApproved = isApproved;
this.role = role;
this.createdAt = createdAt;
}

public UserEntity() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.example.UserService.dto;

import com.example.UserService.domain.Role;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
Expand All @@ -15,7 +14,5 @@ public class JWTAuthResponse {
private String accessToken;
private String refreshToken;
private Long accessTokenExpireDate;
private Role role;
private Long id;
}

7 changes: 6 additions & 1 deletion src/main/java/com/example/UserService/dto/UserResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import lombok.Getter;

import java.time.LocalDate;

//feignClient 응답용

@Getter
Expand All @@ -10,14 +12,17 @@ public class UserResponse {
private String email;
private String name;
private String phoneNumber;
private LocalDate createdAt;
private boolean isApproved;
private String message;

public UserResponse(Long id, String email, String name, String phoneNumber, boolean isApproved) {
public UserResponse(Long id, String email, String name, String phoneNumber,
LocalDate createdAt, boolean isApproved) {
this.id = id;
this.email = email;
this.name = name;
this.phoneNumber = phoneNumber;
this.createdAt = createdAt;
this.isApproved = isApproved;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

Expand All @@ -24,6 +25,7 @@ default UserResponse findUserResponseByUserId(Long userId) {
userEntity.getEmail(),
userEntity.getName(),
userEntity.getPhoneNumber(),
userEntity.getCreatedAt(),
userEntity.isApproved());
}

Expand All @@ -35,9 +37,25 @@ default UserResponse findUserResponseByEmail(String email) {
userEntity.getEmail(),
userEntity.getName(),
userEntity.getPhoneNumber(),
userEntity.getCreatedAt(),
userEntity.isApproved());
}

@Query("SELECT u.id FROM UserEntity u WHERE u.isApproved = true")
List<Long> getAllApprovedUserIds();

default List<UserResponse> findAllUsers(){
List<UserEntity> userEntityList = findAll();
List<UserResponse> userResponseList = new ArrayList<>();
for(UserEntity userEntity : userEntityList) {
userResponseList.add (new UserResponse(
userEntity.getId(),
userEntity.getEmail(),
userEntity.getName(),
userEntity.getPhoneNumber(),
userEntity.getCreatedAt(),
userEntity.isApproved()));
}
return userResponseList;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,8 @@ public interface UserService{
List<Long> getAllApprovedUserIds();

ResponseEntity unregister(Long userId);

List<UserResponse> getAllUsers();

boolean updateApproved(Long userId, boolean approved);
}
23 changes: 21 additions & 2 deletions src/main/java/com/example/UserService/service/UserServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import java.util.Random;
Expand Down Expand Up @@ -70,7 +71,7 @@ public JWTAuthResponse login(RequestLogin requestLogin) {
UserEntity user = userRepository.findById(userId).orElseThrow(); // new ExceptionCode.MEMBER_NOT_FOUND

// JWTAuthResponse token = jwtTokenProvider.generateToken(requestLogin.getEmail(), authentication, userId);
JWTAuthResponse token = jwtTokenProvider.generateToken(requestLogin.getEmail(), authentication, userId, user.getRole());
JWTAuthResponse token = jwtTokenProvider.generateToken(requestLogin.getEmail(), authentication, userId);
return token;
}

Expand All @@ -87,6 +88,7 @@ public String register(RequestUser requestUser) {
UserEntity userEntity = mapper.map(requestUser, UserEntity.class);
userEntity.setEncryptedPwd(pwdEncoder.encode(requestUser.getPwd()));
userEntity.setApproved(false);
userEntity.setCreatedAt(LocalDate.now());
userRepository.save(userEntity);

return "User registered successfully!.";
Expand Down Expand Up @@ -119,7 +121,7 @@ public JWTAuthResponse reissueAccessToken(String refreshToken) {
if (redisService.checkExistsValue(redisRefreshToken) && refreshToken.equals(redisRefreshToken)) {
Optional<UserEntity> findUser = this.findOne(email);
UserEntity userEntity = UserEntity.of(findUser);
JWTAuthResponse tokenDto = jwtTokenProvider.generateToken(email, jwtTokenProvider.getAuthentication(refreshToken), userEntity.getId(), userEntity.getRole());
JWTAuthResponse tokenDto = jwtTokenProvider.generateToken(email, jwtTokenProvider.getAuthentication(refreshToken), userEntity.getId());
String newAccessToken = tokenDto.getAccessToken();
long refreshTokenExpirationMillis = jwtTokenProvider.getRefreshTokenExpirationMillis();
return tokenDto;
Expand Down Expand Up @@ -198,4 +200,21 @@ public ResponseEntity unregister(Long userId) {

return null;
}

@Override
public List<UserResponse> getAllUsers() {
List<UserResponse> userResponses = userRepository.findAllUsers();
if (userResponses == null) {
throw new BusinessLogicException(ExceptionCode.MEMBER_NOT_FOUND);
}
return userResponses;
}

@Override
public boolean updateApproved(Long userId, boolean approved) {
UserEntity user = userRepository.findById(userId).orElseThrow();
user.setApproved(approved);
userRepository.save(user);
return user.isApproved();
}
}
9 changes: 4 additions & 5 deletions src/main/java/com/example/UserService/vo/RequestUser.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package com.example.UserService.vo;

import com.example.UserService.domain.Role;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.*;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
Expand All @@ -28,7 +30,4 @@ public class RequestUser {
@Size(min = 10, max = 15, message = "전화번호는 10자에서 15자 사이여야 합니다")
private String phoneNumber;

@NotNull(message = "권한을 입력해주세요")
private Role role;

}
3 changes: 3 additions & 0 deletions src/main/java/com/example/UserService/vo/ResponseUser.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@

import lombok.Data;

import java.time.LocalDate;

@Data
public class ResponseUser {
private String email;
private String name;
private String phoneNumber;
private LocalDate createdAt;
private boolean isApproved;
}

0 comments on commit 58f0117

Please sign in to comment.