Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package DGU_AI_LAB.admin_be.domain.adminActionLog;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** 이 μ—”λ“œν¬μΈνŠΈκ°€ μ„±κ³΅ν•˜λ“  μ‹€νŒ¨ν•˜λ“  κ΄€λ¦¬μž μž‘μ—… 기둝을 ν•˜λ‚˜ 남긴닀. */
@Target(ElementType.METHOD) // λ©”μ„œλ“œμ—λ§Œ 뢙일 수 μžˆλ‹€. ν΄λž˜μŠ€λ‚˜ ν•„λ“œμ— 뢙이면 컴파일 였λ₯˜.
@Retention(RetentionPolicy.RUNTIME) // μ‹€ν–‰ 쀑에도 남겨 λ‘”λ‹€. λΉΌλ©΄ κΈ°λ³Έκ°’ CLASSκ°€ λ˜μ–΄ μ‹€ν–‰ 쀑에 읽을 수 μ—†κ³ ,
// 기둝 μ½”λ“œκ°€ 항상 null을 λ°›μ•„ 아무것도 남지 μ•ŠλŠ”λ‹€(였λ₯˜λ„ μ•ˆ λ‚œλ‹€).
public @interface AdminAction {
/** 무슨 μž‘μ—…μΈμ§€ */
AdminActionType value();

/** λŒ€μƒμ˜ μ‹λ³„μžλ₯Ό 담은 경둜 λ³€μˆ˜ 이름. 예: "requestId" */
String targetId();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package DGU_AI_LAB.admin_be.domain.adminActionLog;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

@Entity
@Table(name = "admin_action_logs")
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class AdminActionLog {

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

@Column(name = "admin_id", nullable = false)
private Long adminId;

@Column(name = "action_type", nullable = false, length = 50)
private String actionType;

@Column(name = "target_type", nullable = false, length = 30)
private String targetType;

@Column(name = "target_id", nullable = false, length = 255)
private String targetId;

@Column(name = "requested_role", length = 32)
private String requestedRole;

@Column(name = "http_status", nullable = false)
private int httpStatus;

@Column(name = "occurred_at", nullable = false)
private LocalDateTime occurredAt;

public AdminActionLog(Long adminId, AdminActionType actionType, String targetId,
String requestedRole, int httpStatus, LocalDateTime occurredAt) {
this.adminId = adminId;
this.actionType = actionType.name();
this.targetType = actionType.targetType().name();
this.targetId = targetId;
this.requestedRole = requestedRole;
this.httpStatus = httpStatus;
this.occurredAt = occurredAt;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package DGU_AI_LAB.admin_be.domain.adminActionLog;

import DGU_AI_LAB.admin_be.domain.users.dto.request.ChangeRoleRequestDTO;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.lang.reflect.Type;

@ControllerAdvice
public class AdminActionLogBodyAdvice extends RequestBodyAdviceAdapter {

static final String REQUESTED_ROLE_ATTRIBUTE =
AdminActionLogBodyAdvice.class.getName() + ".requestedRole";

@Override
public boolean supports(MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
AdminAction action = parameter.getMethodAnnotation(AdminAction.class);
return action != null
&& action.value() == AdminActionType.USER_ROLE_CHANGE
&& parameter.getParameterType() == ChangeRoleRequestDTO.class;
}

@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage,
MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
if (attributes != null && body instanceof ChangeRoleRequestDTO dto && dto.role() != null) {
attributes.setAttribute(
REQUESTED_ROLE_ATTRIBUTE, dto.role().name(), RequestAttributes.SCOPE_REQUEST);
}
return body;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package DGU_AI_LAB.admin_be.domain.adminActionLog;

import DGU_AI_LAB.admin_be.global.common.SuccessResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.ZoneOffset;
import java.util.List;

@RestController
@RequestMapping("/api/admin/action-logs")
@RequiredArgsConstructor
public class AdminActionLogController {

private final AdminActionLogQueryRepository queryRepository;

@GetMapping
public ResponseEntity<SuccessResponse<?>> findLogs(
@Valid @ModelAttribute AdminActionLogQuery query) {
int pageSize = query.pageSize();
List<AdminActionLog> rows = queryRepository.find(query);

List<LogItem> items = rows.stream()
.limit(pageSize)
.map(LogItem::from)
.toList();

Cursor nextCursor = null;
if (rows.size() > pageSize) {
LogItem lastItem = items.get(items.size() - 1);
nextCursor = new Cursor(lastItem.occurredAt(), lastItem.id());
}

return SuccessResponse.ok(new LogPage(items, nextCursor));
}

public record LogPage(List<LogItem> items, Cursor nextCursor) {
}

public record Cursor(String before, Long beforeId) {
}

public record LogItem(
Long id,
Long adminId,
String actionType,
String targetType,
String targetId,
String requestedRole,
int httpStatus,
String occurredAt
) {
private static LogItem from(AdminActionLog row) {
return new LogItem(
row.getId(),
row.getAdminId(),
row.getActionType(),
row.getTargetType(),
row.getTargetId(),
row.getRequestedRole(),
row.getHttpStatus(),
row.getOccurredAt().toInstant(ZoneOffset.UTC).toString());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package DGU_AI_LAB.admin_be.domain.adminActionLog;

import DGU_AI_LAB.admin_be.global.auth.CustomUserDetails;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class AdminActionLogInterceptor implements HandlerInterceptor {

private final AdminActionLogWriter adminActionLogWriter;

@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) {
if (!(handler instanceof HandlerMethod handlerMethod)) {
return;
}

AdminAction action = handlerMethod.getMethodAnnotation(AdminAction.class);
if (action == null) {
return;
}

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()
|| !(authentication.getPrincipal() instanceof CustomUserDetails principal)) {
return;
}

Long adminId = principal.getUserId();

Object variables = request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
if (!(variables instanceof Map<?, ?> pathVariables)
|| !(pathVariables.get(action.targetId()) instanceof String targetId)) {
log.error("Missing admin action target: adminId={} action={} variable={}",
adminId, action.value(), action.targetId());
return;
}

Object roleAttribute = request.getAttribute(AdminActionLogBodyAdvice.REQUESTED_ROLE_ATTRIBUTE);
String requestedRole = roleAttribute instanceof String role ? role : null;

AdminActionLog entry = new AdminActionLog(
adminId, action.value(), targetId, requestedRole,
response.getStatus(), LocalDateTime.now(ZoneOffset.UTC));

adminActionLogWriter.submit(entry);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package DGU_AI_LAB.admin_be.domain.adminActionLog;

import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.Size;

import java.time.Instant;

public record AdminActionLogQuery(
@Positive Long adminId,
Instant from,
Instant to,
AdminTargetType targetType,
@Size(min = 1, max = 255) String targetId,
AdminActionType actionType,
@Size(min = 1, max = 32) String requestedRole,
@Min(100) @Max(599) Integer httpStatus,
Instant before,
@Positive Long beforeId,
@Min(1) @Max(100) Integer size
) {
@AssertTrue(message = "from은 to보닀 이전이어야 ν•©λ‹ˆλ‹€.")
public boolean isPeriodValid() {
return from == null || to == null || from.isBefore(to);
}

@AssertTrue(message = "before와 beforeIdλŠ” ν•¨κ»˜ μ§€μ •ν•΄μ•Ό ν•©λ‹ˆλ‹€.")
public boolean isCursorValid() {
return before == null ? beforeId == null : beforeId != null;
}

public int pageSize() {
return size == null ? 20 : size;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package DGU_AI_LAB.admin_be.domain.adminActionLog;

import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

@Repository
public class AdminActionLogQueryRepository {

@PersistenceContext
private EntityManager entityManager;

@Transactional(readOnly = true)
public List<AdminActionLog> find(AdminActionLogQuery filter) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<AdminActionLog> query = builder.createQuery(AdminActionLog.class);
Root<AdminActionLog> row = query.from(AdminActionLog.class);
Path<LocalDateTime> occurredAt = row.get("occurredAt");
Path<Long> id = row.get("id");
List<Predicate> conditions = new ArrayList<>();

addEquality(builder, row, conditions, "adminId", filter.adminId());
addEquality(builder, row, conditions, "targetId", filter.targetId());
addEquality(builder, row, conditions, "requestedRole", filter.requestedRole());
addEquality(builder, row, conditions, "httpStatus", filter.httpStatus());

if (filter.targetType() != null) {
conditions.add(builder.equal(row.get("targetType"), filter.targetType().name()));
}
if (filter.actionType() != null) {
conditions.add(builder.equal(row.get("actionType"), filter.actionType().name()));
}
if (filter.from() != null) {
LocalDateTime from = LocalDateTime.ofInstant(filter.from(), ZoneOffset.UTC);
conditions.add(builder.greaterThanOrEqualTo(occurredAt, from));
}
if (filter.to() != null) {
LocalDateTime to = LocalDateTime.ofInstant(filter.to(), ZoneOffset.UTC);
conditions.add(builder.lessThan(occurredAt, to));
}
if (filter.before() != null) {
LocalDateTime before = LocalDateTime.ofInstant(filter.before(), ZoneOffset.UTC);
conditions.add(builder.or(
builder.lessThan(occurredAt, before),
builder.and(
builder.equal(occurredAt, before),
builder.lessThan(id, filter.beforeId()))));
}

query.select(row)
.where(conditions.toArray(Predicate[]::new))
.orderBy(builder.desc(occurredAt), builder.desc(id));

return entityManager.createQuery(query)
.setMaxResults(filter.pageSize() + 1)
.getResultList();
}

private void addEquality(CriteriaBuilder builder, Root<AdminActionLog> row,
List<Predicate> conditions, String field, Object value) {
if (value != null) {
conditions.add(builder.equal(row.get(field), value));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package DGU_AI_LAB.admin_be.domain.adminActionLog;

import org.springframework.data.jpa.repository.JpaRepository;

public interface AdminActionLogRepository extends JpaRepository<AdminActionLog, Long> {
}
Loading
Loading