Skip to content

Commit

Permalink
feat: User Entity 작성 & User Repository 작성 & UserUtils 작성 #14
Browse files Browse the repository at this point in the history
  • Loading branch information
bongsh0112 committed Sep 14, 2023
1 parent c87b6fe commit 37220b5
Show file tree
Hide file tree
Showing 13 changed files with 236 additions and 2 deletions.
3 changes: 1 addition & 2 deletions Api/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ dependencies {
test {
useJUnitPlatform()
}

bootJar{
archivesBaseName = 'app'
archiveFileName = 'app.jar'
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package playlist.server.config.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.CollectionUtils;
import playlist.server.exception.SecurityContextNotFoundException;

import java.util.List;

public class SecurityUtils {

private static SimpleGrantedAuthority swagger = new SimpleGrantedAuthority("ROLE_SWAGGER");

private static List<SimpleGrantedAuthority> notUserAuthority = List.of(swagger);

public static Long getCurrentUserId() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw SecurityContextNotFoundException.EXCEPTION;
}

if (authentication.isAuthenticated()
&& !CollectionUtils.containsAny(
authentication.getAuthorities(), notUserAuthority)) {
return authentication.getName().equals("anonymousUser")
? 0L
: Long.valueOf(authentication.getName());
}
// 스웨거 유저일시 유저 아이디 0 반환
return 0L;
}
}
20 changes: 20 additions & 0 deletions Api/src/main/java/playlist/server/utils/UserUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package playlist.server.utils;

import lombok.RequiredArgsConstructor;
import playlist.server.config.security.SecurityUtils;
import playlist.server.domain.domains.user.adaptor.UserAdaptor;
import playlist.server.domain.domains.user.domains.User;

@RequiredArgsConstructor
public class UserUtils {

private final UserAdaptor userAdaptor;

public Long getUserId() {
return SecurityUtils.getCurrentUserId();
}

public User getUser() {
return userAdaptor.query(SecurityUtils.getCurrentUserId());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.http.HttpStatus;
import playlist.server.dto.ErrorDetail;

@Getter
Expand All @@ -19,6 +20,7 @@ public enum GlobalException implements BaseErrorCode {
EXPIRED_REFRESH_TOKEN_ERROR(UNAUTHORIZED.value(), "401-1", "리프레시 토큰이 만료되었습니다."),
INVALID_TOKEN_ERROR(UNAUTHORIZED.value(), "401-2", "올바르지 않은 토큰입니다."),
DATE_FORMAT_ERROR(BAD_REQUEST.value(), "400-2", "날짜 형식을 확인해주세요."),
SECURITY_CONTEXT_NOT_FOUND_ERROR(INTERNAL_SERVER_ERROR.value(), "500-2", "Security Context 에러입니다.")
;

private final Integer statusCode;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package playlist.server.exception;

public class SecurityContextNotFoundException extends BaseException {

public static final BaseException EXCEPTION = new SecurityContextNotFoundException();

private SecurityContextNotFoundException() {
super(GlobalException.SECURITY_CONTEXT_NOT_FOUND_ERROR);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package playlist.server.domain.domains;

import com.fasterxml.jackson.annotation.JsonFormat;
import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import lombok.Getter;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.sql.Timestamp;

@Getter
@MappedSuperclass
@EntityListeners(value = {AuditingEntityListener.class})
public abstract class AbstractTimeStamp {

@Column(name = "created_at", nullable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
@CreationTimestamp
@JsonFormat(
shape = JsonFormat.Shape.STRING,
pattern = "yyyy-MM-dd hh:mm:ss")
private Timestamp createdAt;

@Column(name = "created_at", nullable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
@UpdateTimestamp
@JsonFormat(
shape = JsonFormat.Shape.STRING,
pattern = "yyyy-MM-dd hh:mm:ss")
private Timestamp updatedAt;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package playlist.server.domain.domains.user.Exception;

import lombok.RequiredArgsConstructor;
import playlist.server.dto.ErrorDetail;
import playlist.server.exception.BaseErrorCode;
import static org.springframework.http.HttpStatus.*;

@RequiredArgsConstructor
public enum UserException implements BaseErrorCode {
USER_NOT_FOUND_ERROR(NOT_FOUND.value(), "User_404_1", "유저를 찾을 수 없습니다.");

private final Integer statusCode;
private final String errorCode;
private final String reason;

@Override
public ErrorDetail getErrorDetail() {
return ErrorDetail.of(statusCode, errorCode, reason);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package playlist.server.domain.domains.user.Exception;

import lombok.RequiredArgsConstructor;
import playlist.server.exception.BaseException;

@RequiredArgsConstructor
public class UserNotFoundException extends BaseException {
public static final BaseException EXCEPTION = new UserNotFoundException();

private UserNotFoundException() {
super(UserException.USER_NOT_FOUND_ERROR);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package playlist.server.domain.domains.user.adaptor;


import lombok.RequiredArgsConstructor;
import playlist.server.annotation.Adaptor;
import playlist.server.domain.domains.user.Exception.UserNotFoundException;
import playlist.server.domain.domains.user.domains.User;
import playlist.server.domain.domains.user.repository.UserRepository;

@Adaptor
@RequiredArgsConstructor
public class UserAdaptor {

private final UserAdaptor userAdaptor;
private final UserRepository userRepository;

public User query(Long userId) {
return userRepository.findById(userId).orElseThrow(() -> UserNotFoundException.EXCEPTION);
}

public User save(User user) {
return userRepository.save(user);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package playlist.server.domain.domains.user.domains;

public enum AccountRole {

USER,
ADMIN;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package playlist.server.domain.domains.user.domains;

public enum LoginType {
DEFAULT,
KAKAO,
NAVER,
GOOGLE,
APPLE,
GITHUB
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package playlist.server.domain.domains.user.domains;


import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.ColumnDefault;
import org.jetbrains.annotations.NotNull;
import playlist.server.domain.domains.AbstractTimeStamp;

@Getter
@Entity
@Table(name = "user")
@NoArgsConstructor(access = AccessLevel.PROTECTED)

public class User extends AbstractTimeStamp {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = false, length = 200)
private String email;

@Column(nullable = false, length = 100)
private String password;

//@Embedded private Profile profile;

@Enumerated(EnumType.ORDINAL)
@Column(nullable = false, name = "role", columnDefinition = "varchar(32) default 'USER'")
private AccountRole accountRole;

@Enumerated(EnumType.ORDINAL)
@Column(length = 32, nullable = false, columnDefinition = "varchar(32) default 'DEFAULT'")
private LoginType loginType;

@NotNull
@Column(name = "fail_cnt", nullable = false)
@ColumnDefault("0")
private int failCnt;

@NotNull
@Column(name = "rank_id", nullable = false)
@ColumnDefault("0")
private int rankId;

@NotNull
@ColumnDefault("0")
private int exp;

@Column(name = "update_user")
private long updateUser;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package playlist.server.domain.domains.user.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import playlist.server.domain.domains.user.domains.User;

import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findUserByEmail(String email);
}

0 comments on commit 37220b5

Please sign in to comment.