Skip to content
Merged
104 changes: 104 additions & 0 deletions src/main/java/com/mr/domain/auth/entity/SocialAuth.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package com.mr.domain.auth.entity;

import com.mr.domain.auth.entity.enums.AuthErrorStatus;
import com.mr.domain.auth.entity.enums.SocialType;
import com.mr.global.apipayload.code.CommonStatus;
import com.mr.global.apipayload.exception.GeneralException;
import com.mr.global.entity.BaseCreatedEntity;
import jakarta.persistence.*;
import java.time.LocalDateTime;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@Entity
// TODO: 추후 User 도메인 완성 시 단방향/양방향 인덱스 추가
@Table(
name = "social_auth",
indexes = {
@Index(name = "idx_social_auth_token_hash", columnList = "refresh_token_hash")
})
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class SocialAuth extends BaseCreatedEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "social_auth_id")
private Long id;

// TODO: User 엔티티 연관관계 연결 예정
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
@Column(name = "user_id", nullable = false)
private Long userId;

@Enumerated(EnumType.STRING)
@Column(name = "social_type", nullable = false, length = 20)
private SocialType socialType;

@Column(name = "social_id", nullable = false, length = 100)
private String socialId;

@Column(name = "refresh_token", length = 1000)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

길이 제한이 1000으로 되어 있는데, 혹시 TEXT 타입을 쓰는 방법도 가능한가요? 제가 토큰의 길이가 어느 정도 인지 잘 몰라서 여쭈어봅니다!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PostgreSQL에서는 TEXT 타입을 사용해도 괜찮습니다! TEXT와 VARCHAR(n) 사이에 성능상 큰 차이는 없어서, refresh token의 최대 길이가 명확하지 않다면 TEXT로 두는 것도 안전한 선택일 것 같습니다. 반대로 현재 사용하는 토큰이 1,000자를 넘지 않는 것이 보장되고, DB 차원에서 길이 제한을 명시하고 싶다면 지금처럼 VARCHAR(1000)을 유지해도 괜찮을 것 같습니다!

사용 중인 OAuth 제공자의 안내는 다음과 같습니다.

  • 카카오는 access token과 refresh token의 길이가 상황에 따라 달라질 수 있으므로 length 100 이상을 권장하고 있습니다.
  • Google은 refresh token의 최대 크기를 512바이트로 안내하고 있으며, 해당 한도 내에서 토큰 크기가 달라질 수 있다고 명시하고 있습니다.

현재 카카오와 Google 토큰을 저장하는 용도라면 VARCHAR(1000)으로도 충분해 보이지만, 특별히 길이를 제한해야 하는 요구사항이 없다면 TEXT로 두어 향후 토큰 형식 변경에 유연하게 대응하는 것도 괜찮겠네용

[참고한 공식 답변/문서]

private String refreshToken;

@Column(name = "refresh_token_hash", length = 64, unique = true)
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
private String refreshTokenHash;

@Column(name = "expired_at")
private LocalDateTime expiredAt;

@Column(name = "device_info", length = 255)
private String deviceInfo;

@Builder(access = AccessLevel.PRIVATE)
private SocialAuth(Long userId, SocialType socialType, String socialId, String refreshToken,
LocalDateTime expiredAt, String deviceInfo) {

validateRequiredField(userId);
validateRequiredField(socialType);
validateRequiredField(socialId);

this.userId = userId;
this.socialType = socialType;
this.socialId = socialId;
this.refreshToken = refreshToken;
this.expiredAt = expiredAt;
this.deviceInfo = deviceInfo;
}

public static SocialAuth create(Long userId, SocialType socialType, String socialId,
String refreshToken, LocalDateTime expiredAt, String deviceInfo) {
return SocialAuth.builder()
.userId(userId)
.socialType(socialType)
.socialId(socialId)
.refreshToken(refreshToken)
.expiredAt(expiredAt)
.deviceInfo(deviceInfo)
.build();
}
private static void validateRequiredField(Object value) {
if (value == null || (value instanceof String && ((String) value).trim().isEmpty())) {
throw new GeneralException(AuthErrorStatus.INVALID_AUTH_REQUEST);
}
}
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved

public void updateRefreshToken(String encryptedToken, String tokenHash, LocalDateTime newExpiredAt, String deviceInfo) {
validateRequiredField(encryptedToken);
validateRequiredField(tokenHash);

if (newExpiredAt == null || newExpiredAt.isBefore(LocalDateTime.now())) {
throw new GeneralException(AuthErrorStatus.INVALID_TOKEN_EXPIRY);
}
this.refreshToken = encryptedToken;
this.refreshTokenHash = tokenHash;
this.expiredAt = newExpiredAt;
this.deviceInfo = deviceInfo;
}

public void expireToken() {
this.refreshToken = null;
this.expiredAt = null;
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.mr.global.apipayload.domain;
package com.mr.domain.auth.entity.enums;

import com.mr.global.apipayload.code.BaseCode;
import org.springframework.http.HttpStatus;
Expand All @@ -9,8 +9,9 @@
@AllArgsConstructor
public enum AuthErrorStatus implements BaseCode {

// 예원님 도메인 에러코드 컨벤션 적용
TOKEN_MISSING(HttpStatus.BAD_REQUEST, "AUTH_400_07", "토큰 값이 필요합니다."),
INVALID_AUTH_REQUEST(HttpStatus.BAD_REQUEST, "AUTH_400_01", "인증 관련 필수 입력값이 올바르지 않거나 누락되었습니다."),
TOKEN_MISSING(HttpStatus.BAD_REQUEST, "AUTH_400_02", "토큰 값이 필요합니다."),
INVALID_TOKEN_EXPIRY(HttpStatus.BAD_REQUEST, "AUTH_400_03", "만료 시간은 현재 시간 이후여야 합니다."),
INVALID_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_401_01", "유효하지 않은 토큰입니다."),
EXPIRED_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_401_02", "만료된 토큰입니다.");

Expand Down
6 changes: 6 additions & 0 deletions src/main/java/com/mr/domain/auth/entity/enums/SocialType.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.mr.domain.auth.entity.enums;

public enum SocialType {
KAKAO,
GOOGLE
}
93 changes: 93 additions & 0 deletions src/main/java/com/mr/domain/user/entity/UsageLimit.java
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package com.mr.domain.user.entity;

import com.mr.domain.user.entity.enums.UserUsageErrorStatus;
import com.mr.global.apipayload.exception.GeneralException;
import com.mr.global.entity.BaseCreatedEntity;
import jakarta.persistence.*;
Comment thread
ownue marked this conversation as resolved.
Resolved
import java.time.LocalDate;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@Entity
@Table(
name = "usage_limit",
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
indexes = {
@Index(name = "idx_usage_limit_user_date", columnList = "user_id, limit_date", unique = true)
})
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class UsageLimit extends BaseCreatedEntity {

private static final int DEFAULT_MAX_FREE_COUNT = 3; // Free 3회 제한

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "usage_limit_id")
private Long id;

// TODO: User 엔티티 연관관계 연결 예정
@Column(name = "user_id", nullable = false)
private Long userId;

@Column(name = "limit_date", nullable = false)
private LocalDate limitDate;

@Column(name = "remaining_count", nullable = false)
private Integer remainingCount;

@Column(name = "max_count", nullable = false)
private Integer maxCount;

@Builder(access = AccessLevel.PRIVATE)
private UsageLimit(Long userId, LocalDate limitDate, Integer remainingCount, Integer maxCount) {
validateRequired(userId, "userId");
validateRequired(limitDate, "limitDate");
validatePositiveOrZero(remainingCount, "remainingCount");
validatePositiveOrZero(maxCount, "maxCount");

this.userId = userId;
this.limitDate = limitDate;
this.remainingCount = remainingCount;
this.maxCount = maxCount;
}

public static UsageLimit createDefault(Long userId, LocalDate limitDate) {
return UsageLimit.builder()
.userId(userId)
.limitDate(limitDate)
.maxCount(DEFAULT_MAX_FREE_COUNT)
.remainingCount(DEFAULT_MAX_FREE_COUNT)
.build();
}

public static void validateRequired(Object value, String fieldName) {
if (value == null) {
throw new GeneralException(UserUsageErrorStatus.INVALID_USAGE_COUNT);
}
}

private static void validatePositiveOrZero(Integer value, String fieldName) {
if (value == null || value < 0) {
throw new GeneralException(UserUsageErrorStatus.INVALID_USAGE_COUNT);
}
}
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved

// 분석 요청 시 카운트 로직
public void consume() {
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
if (this.remainingCount <= 0) {
throw new GeneralException(UserUsageErrorStatus.USAGE_LIMIT_EXCEEDED);
}
this.remainingCount--;
}

// 관리자 기능으로 잔여 횟수 수동 조절할 때 사용
public void updateRemainingCount(Integer newCount) {
validatePositiveOrZero(newCount, "newCount");
if (newCount > this.maxCount) {
throw new GeneralException(UserUsageErrorStatus.INVALID_USAGE_COUNT);
}
this.remainingCount = newCount;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.mr.domain.user.entity.enums;

import com.mr.global.apipayload.code.BaseCode;
import org.springframework.http.HttpStatus;
import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public enum UserUsageErrorStatus implements BaseCode {

// 잔여 횟수 소진 에러
USAGE_LIMIT_EXCEEDED(HttpStatus.FORBIDDEN, "USAGE_403_01", "일일 잔여 분석 횟수를 모두 소진하였습니다."),

// 유효하지 않은 카운트 수정 요청
INVALID_USAGE_COUNT(HttpStatus.BAD_REQUEST, "USAGE_400_01", "잔여 횟수는 최대 제한 횟수를 초과할 수 없습니다."),

// 해당 날짜의 이용 제한 데이터가 존재하지 않을 때
USAGE_RECORD_NOT_FOUND(HttpStatus.NOT_FOUND, "USAGE_404_01", "해당 날짜의 이용 제한 기록을 찾을 수 없습니다.");

private final HttpStatus status;
private final String code;
private final String message;
}
Loading