日志
This commit is contained in:
@@ -0,0 +1,51 @@
|
|||||||
|
package com.banben.modules.auth;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登录日志表自举建表。
|
||||||
|
*
|
||||||
|
* <p>应用本身不在启动时自动执行建表脚本(dev/prod 的初始化脚本仅在数据库首次初始化时跑一次)。
|
||||||
|
* 但登录日志功能是后加的,已初始化的运行库里可能缺这张表,会导致 {@code /admin/login-logs/page}
|
||||||
|
* 直接抛 500。这里在容器就绪后幂等地补建该表,保证新库旧库都能正常工作,不影响已有数据。</p>
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class LoginLogTableInitializer {
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
|
public LoginLogTableInitializer(JdbcTemplate jdbcTemplate) {
|
||||||
|
this.jdbcTemplate = jdbcTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
|
public void init() {
|
||||||
|
try {
|
||||||
|
jdbcTemplate.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS login_log ("
|
||||||
|
+ "id BIGSERIAL NOT NULL PRIMARY KEY, "
|
||||||
|
+ "user_id BIGINT, "
|
||||||
|
+ "username VARCHAR(128), "
|
||||||
|
+ "real_name VARCHAR(128), "
|
||||||
|
+ "org_name VARCHAR(256), "
|
||||||
|
+ "ip VARCHAR(64), "
|
||||||
|
+ "user_agent VARCHAR(512), "
|
||||||
|
+ "login_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
|
||||||
|
+ "logout_time TIMESTAMP, "
|
||||||
|
+ "online SMALLINT DEFAULT 1, "
|
||||||
|
+ "create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
|
||||||
|
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_ll_user_id ON login_log (user_id)");
|
||||||
|
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_ll_login_time ON login_log (login_time)");
|
||||||
|
jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_ll_online ON login_log (online)");
|
||||||
|
log.info("登录日志表 login_log 已就绪(不存在则已自动创建)");
|
||||||
|
} catch (Exception e) {
|
||||||
|
// 建表失败不应阻断启动;缺表时登录日志接口已做优雅降级
|
||||||
|
log.warn("自动创建 login_log 表失败(不影响启动,请检查数据库权限):{}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ import com.banben.modules.auth.dto.LoginRequest;
|
|||||||
import com.banben.modules.auth.dto.LoginResponse;
|
import com.banben.modules.auth.dto.LoginResponse;
|
||||||
import com.banben.modules.auth.entity.SysUser;
|
import com.banben.modules.auth.entity.SysUser;
|
||||||
import com.banben.modules.auth.service.AuthService;
|
import com.banben.modules.auth.service.AuthService;
|
||||||
|
import com.banben.modules.auth.service.LoginLogService;
|
||||||
|
import com.banben.modules.auth.context.UserContext;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
@@ -23,6 +25,7 @@ import java.util.List;
|
|||||||
public class AuthController {
|
public class AuthController {
|
||||||
|
|
||||||
private final AuthService authService;
|
private final AuthService authService;
|
||||||
|
private final LoginLogService loginLogService;
|
||||||
|
|
||||||
@Operation(summary = "登录")
|
@Operation(summary = "登录")
|
||||||
@PostMapping("/login")
|
@PostMapping("/login")
|
||||||
@@ -45,7 +48,8 @@ public class AuthController {
|
|||||||
@Operation(summary = "登出")
|
@Operation(summary = "登出")
|
||||||
@PostMapping("/logout")
|
@PostMapping("/logout")
|
||||||
public Result<Void> logout() {
|
public Result<Void> logout() {
|
||||||
// 采用无状态 JWT,登出由前端清除本地令牌即可;此处预留服务端黑名单能力
|
// 采用无状态 JWT,登出由前端清除本地令牌即可;此处同时回填登录日志的退出时间
|
||||||
|
loginLogService.recordLogout(UserContext.currentUserId());
|
||||||
return Result.success();
|
return Result.success();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package com.banben.modules.auth.controller;
|
||||||
|
|
||||||
|
import com.banben.common.PageResult;
|
||||||
|
import com.banben.common.Result;
|
||||||
|
import com.banben.modules.admin.support.AdminAccess;
|
||||||
|
import com.banben.modules.auth.dto.LoginLogQuery;
|
||||||
|
import com.banben.modules.auth.entity.LoginLog;
|
||||||
|
import com.banben.modules.auth.service.LoginLogService;
|
||||||
|
import com.banben.modules.auth.vo.LoginLogSummary;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 后台管理 - 登录日志。
|
||||||
|
*/
|
||||||
|
@Tag(name = "后台管理-登录日志")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/admin/login-logs")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class LoginLogController {
|
||||||
|
|
||||||
|
private final LoginLogService loginLogService;
|
||||||
|
private final AdminAccess adminAccess;
|
||||||
|
|
||||||
|
@Operation(summary = "登录日志分页(支持账号/姓名/单位关键字、在线状态、登录时间区间)")
|
||||||
|
@GetMapping("/page")
|
||||||
|
public Result<PageResult<LoginLog>> page(LoginLogQuery query) {
|
||||||
|
adminAccess.require();
|
||||||
|
return Result.success(loginLogService.page(query));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "登录日志概览:会话总数 / 当前在线 / 今日登录")
|
||||||
|
@GetMapping("/summary")
|
||||||
|
public Result<LoginLogSummary> summary() {
|
||||||
|
adminAccess.require();
|
||||||
|
return Result.success(loginLogService.summary());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.banben.modules.auth.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登录日志查询条件。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Schema(description = "登录日志查询条件")
|
||||||
|
public class LoginLogQuery {
|
||||||
|
|
||||||
|
@Schema(description = "页码,从1开始", example = "1")
|
||||||
|
private Long current = 1L;
|
||||||
|
|
||||||
|
@Schema(description = "每页条数", example = "20")
|
||||||
|
private Long size = 20L;
|
||||||
|
|
||||||
|
@Schema(description = "关键字:匹配账号 / 姓名 / 单位")
|
||||||
|
private String keyword;
|
||||||
|
|
||||||
|
/** ONLINE 在线 / OFFLINE 离线 / 空 全部 */
|
||||||
|
@Schema(description = "状态:ONLINE 在线 / OFFLINE 离线 / 空 全部")
|
||||||
|
private String status;
|
||||||
|
|
||||||
|
@Schema(description = "登录时间起(含,yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss)")
|
||||||
|
private String loginStart;
|
||||||
|
|
||||||
|
@Schema(description = "登录时间止(含)")
|
||||||
|
private String loginEnd;
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package com.banben.modules.auth.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户登录日志(会话维度)。
|
||||||
|
*
|
||||||
|
* <p>一次成功登录产生一条会话记录:{@code online=1}、{@code logoutTime=null};
|
||||||
|
* 用户主动退出时回填 {@code logoutTime} 并置 {@code online=0}。
|
||||||
|
* 「在线」状态以 {@code logoutTime 为 null} 为准,前端据此展示在线/离线。</p>
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("login_log")
|
||||||
|
@Schema(description = "用户登录日志(会话维度:一次登录一条,登出置 logout_time)")
|
||||||
|
public class LoginLog implements Serializable {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
@Schema(description = "主键")
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Schema(description = "用户ID")
|
||||||
|
private Long userId;
|
||||||
|
|
||||||
|
@Schema(description = "登录账号")
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
@Schema(description = "姓名")
|
||||||
|
private String realName;
|
||||||
|
|
||||||
|
@Schema(description = "所属单位")
|
||||||
|
private String orgName;
|
||||||
|
|
||||||
|
@Schema(description = "登录IP")
|
||||||
|
private String ip;
|
||||||
|
|
||||||
|
@Schema(description = "浏览器/客户端标识")
|
||||||
|
private String userAgent;
|
||||||
|
|
||||||
|
@Schema(description = "登录时间")
|
||||||
|
private LocalDateTime loginTime;
|
||||||
|
|
||||||
|
@Schema(description = "退出时间,未退出为 null")
|
||||||
|
private LocalDateTime logoutTime;
|
||||||
|
|
||||||
|
@Schema(description = "是否在线:1在线 0离线")
|
||||||
|
private Integer online;
|
||||||
|
|
||||||
|
@TableField(fill = FieldFill.INSERT)
|
||||||
|
@Schema(description = "创建时间")
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.banben.modules.auth.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.banben.modules.auth.entity.LoginLog;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户登录日志 Mapper。
|
||||||
|
*/
|
||||||
|
public interface LoginLogMapper extends BaseMapper<LoginLog> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.banben.modules.auth.service;
|
||||||
|
|
||||||
|
import com.banben.common.PageResult;
|
||||||
|
import com.banben.modules.auth.dto.LoginLogQuery;
|
||||||
|
import com.banben.modules.auth.entity.LoginLog;
|
||||||
|
import com.banben.modules.auth.vo.LoginLogSummary;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户登录日志服务。
|
||||||
|
*/
|
||||||
|
public interface LoginLogService {
|
||||||
|
|
||||||
|
/** 记录一次成功登录(会话开始)。 */
|
||||||
|
void recordLogin(Long userId, String username, String realName, String orgName, String ip, String userAgent);
|
||||||
|
|
||||||
|
/** 记录退出:回填该用户最近一条未退出的会话。 */
|
||||||
|
void recordLogout(Long userId);
|
||||||
|
|
||||||
|
/** 分页查询登录日志。 */
|
||||||
|
PageResult<LoginLog> page(LoginLogQuery query);
|
||||||
|
|
||||||
|
/** 概览统计:总数 / 在线 / 今日登录。 */
|
||||||
|
LoginLogSummary summary();
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.banben.modules.auth.service.impl;
|
package com.banben.modules.auth.service.impl;
|
||||||
|
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
import com.banben.common.BusinessException;
|
import com.banben.common.BusinessException;
|
||||||
import com.banben.modules.auth.context.UserContext;
|
import com.banben.modules.auth.context.UserContext;
|
||||||
@@ -13,11 +14,15 @@ import com.banben.modules.auth.entity.SysUser;
|
|||||||
import com.banben.modules.auth.mapper.SysUserMapper;
|
import com.banben.modules.auth.mapper.SysUserMapper;
|
||||||
import com.banben.modules.auth.nav.NavMenus;
|
import com.banben.modules.auth.nav.NavMenus;
|
||||||
import com.banben.modules.auth.service.AuthService;
|
import com.banben.modules.auth.service.AuthService;
|
||||||
|
import com.banben.modules.auth.service.LoginLogService;
|
||||||
import com.banben.modules.auth.util.JwtUtil;
|
import com.banben.modules.auth.util.JwtUtil;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.context.request.RequestContextHolder;
|
||||||
|
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@@ -36,6 +41,7 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
private final SysRoleMenuMapper roleMenuMapper;
|
private final SysRoleMenuMapper roleMenuMapper;
|
||||||
private final PasswordEncoder passwordEncoder;
|
private final PasswordEncoder passwordEncoder;
|
||||||
private final JwtUtil jwtUtil;
|
private final JwtUtil jwtUtil;
|
||||||
|
private final LoginLogService loginLogService;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public LoginResponse login(LoginRequest request) {
|
public LoginResponse login(LoginRequest request) {
|
||||||
@@ -60,6 +66,12 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
user.setLastLoginTime(LocalDateTime.now());
|
user.setLastLoginTime(LocalDateTime.now());
|
||||||
sysUserMapper.updateById(user);
|
sysUserMapper.updateById(user);
|
||||||
|
|
||||||
|
// 记录登录日志(会话维度):取客户端 IP 与 UA
|
||||||
|
HttpServletRequest httpReq = currentRequest();
|
||||||
|
String ip = httpReq == null ? null : clientIp(httpReq);
|
||||||
|
String ua = httpReq == null ? null : httpReq.getHeader("User-Agent");
|
||||||
|
loginLogService.recordLogin(user.getId(), user.getUsername(), user.getRealName(), user.getOrgName(), ip, ua);
|
||||||
|
|
||||||
String token = jwtUtil.generate(user.getId(), user.getUsername(), user.getRole());
|
String token = jwtUtil.generate(user.getId(), user.getUsername(), user.getRole());
|
||||||
|
|
||||||
LoginResponse response = new LoginResponse();
|
LoginResponse response = new LoginResponse();
|
||||||
@@ -129,4 +141,28 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
SysRole role = sysRoleMapper.selectById(user.getRoleId());
|
SysRole role = sysRoleMapper.selectById(user.getRoleId());
|
||||||
return role != null && "ADMIN".equalsIgnoreCase(role.getCode());
|
return role != null && "ADMIN".equalsIgnoreCase(role.getCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 从请求上下文取当前 HttpServletRequest(非 Web 请求线程下为 null)。 */
|
||||||
|
private HttpServletRequest currentRequest() {
|
||||||
|
try {
|
||||||
|
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||||
|
return attrs == null ? null : attrs.getRequest();
|
||||||
|
} catch (Exception e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 取真实客户端 IP,兼容反向代理的 X-Forwarded-For。 */
|
||||||
|
private String clientIp(HttpServletRequest request) {
|
||||||
|
String forwarded = request.getHeader("X-Forwarded-For");
|
||||||
|
if (StrUtil.isNotBlank(forwarded)) {
|
||||||
|
// X-Forwarded-For 格式:client, proxy1, proxy2
|
||||||
|
return StrUtil.subPre(forwarded.trim(), forwarded.indexOf(',') < 0 ? forwarded.length() : forwarded.indexOf(',')).trim();
|
||||||
|
}
|
||||||
|
String realIp = request.getHeader("X-Real-IP");
|
||||||
|
if (StrUtil.isNotBlank(realIp)) {
|
||||||
|
return realIp.trim();
|
||||||
|
}
|
||||||
|
return request.getRemoteAddr();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
package com.banben.modules.auth.service.impl;
|
||||||
|
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.banben.common.PageResult;
|
||||||
|
import com.banben.modules.auth.dto.LoginLogQuery;
|
||||||
|
import com.banben.modules.auth.entity.LoginLog;
|
||||||
|
import com.banben.modules.auth.mapper.LoginLogMapper;
|
||||||
|
import com.banben.modules.auth.service.LoginLogService;
|
||||||
|
import com.banben.modules.auth.vo.LoginLogSummary;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户登录日志服务实现。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class LoginLogServiceImpl implements LoginLogService {
|
||||||
|
|
||||||
|
private final LoginLogMapper logMapper;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void recordLogin(Long userId, String username, String realName, String orgName, String ip, String userAgent) {
|
||||||
|
try {
|
||||||
|
LoginLog entity = new LoginLog();
|
||||||
|
entity.setUserId(userId);
|
||||||
|
entity.setUsername(username);
|
||||||
|
entity.setRealName(realName);
|
||||||
|
entity.setOrgName(orgName);
|
||||||
|
entity.setIp(ip);
|
||||||
|
entity.setUserAgent(userAgent == null ? null : StrUtil.subPre(userAgent, 500));
|
||||||
|
entity.setLoginTime(LocalDateTime.now());
|
||||||
|
entity.setOnline(1);
|
||||||
|
logMapper.insert(entity);
|
||||||
|
} catch (Exception e) {
|
||||||
|
// 日志写入失败不应影响登录主流程
|
||||||
|
log.warn("记录登录日志失败(不影响登录):{}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void recordLogout(Long userId) {
|
||||||
|
if (userId == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
LoginLog entity = new LoginLog();
|
||||||
|
entity.setLogoutTime(LocalDateTime.now());
|
||||||
|
entity.setOnline(0);
|
||||||
|
// 仅关闭该用户最近一条尚未退出的会话
|
||||||
|
logMapper.update(entity, new QueryWrapper<LoginLog>()
|
||||||
|
.eq("user_id", userId)
|
||||||
|
.isNull("logout_time")
|
||||||
|
.orderByDesc("login_time")
|
||||||
|
.last("LIMIT 1"));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("记录退出日志失败:{}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PageResult<LoginLog> page(LoginLogQuery q) {
|
||||||
|
long current = q.getCurrent() == null ? 1L : q.getCurrent();
|
||||||
|
long size = q.getSize() == null ? 20L : q.getSize();
|
||||||
|
try {
|
||||||
|
QueryWrapper<LoginLog> w = new QueryWrapper<>();
|
||||||
|
if (StrUtil.isNotBlank(q.getKeyword())) {
|
||||||
|
String kw = q.getKeyword().trim();
|
||||||
|
w.and(x -> x.like("username", kw).or().like("real_name", kw).or().like("org_name", kw));
|
||||||
|
}
|
||||||
|
if ("ONLINE".equalsIgnoreCase(q.getStatus())) {
|
||||||
|
w.eq("online", 1).isNull("logout_time");
|
||||||
|
} else if ("OFFLINE".equalsIgnoreCase(q.getStatus())) {
|
||||||
|
w.isNotNull("logout_time");
|
||||||
|
}
|
||||||
|
if (StrUtil.isNotBlank(q.getLoginStart())) {
|
||||||
|
w.ge("login_time", q.getLoginStart().trim());
|
||||||
|
}
|
||||||
|
if (StrUtil.isNotBlank(q.getLoginEnd())) {
|
||||||
|
// 结束日期按当天 23:59:59 包含整日,避免漏掉结束日当天的记录
|
||||||
|
String end = q.getLoginEnd().trim();
|
||||||
|
if (end.length() == 10) {
|
||||||
|
end = end + " 23:59:59";
|
||||||
|
}
|
||||||
|
w.le("login_time", end);
|
||||||
|
}
|
||||||
|
w.orderByDesc("login_time");
|
||||||
|
Page<LoginLog> page = logMapper.selectPage(Page.of(current, size), w);
|
||||||
|
return PageResult.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
|
||||||
|
} catch (Exception e) {
|
||||||
|
// 表缺失等异常时降级为空结果,避免进入后台管理时整页报「操作失败」
|
||||||
|
log.warn("分页查询登录日志失败:{}", e.getMessage());
|
||||||
|
return PageResult.of(new ArrayList<>(), 0L, current, size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public LoginLogSummary summary() {
|
||||||
|
LoginLogSummary s = new LoginLogSummary();
|
||||||
|
try {
|
||||||
|
s.setTotal(logMapper.selectCount(new QueryWrapper<>()));
|
||||||
|
s.setOnline(logMapper.selectCount(new QueryWrapper<LoginLog>().eq("online", 1).isNull("logout_time")));
|
||||||
|
LocalDateTime startOfToday = LocalDate.now().atStartOfDay();
|
||||||
|
s.setToday(logMapper.selectCount(new QueryWrapper<LoginLog>().ge("login_time", startOfToday)));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("统计登录日志概览失败:{}", e.getMessage());
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.banben.modules.auth.vo;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登录日志概览统计。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Schema(description = "登录日志概览统计")
|
||||||
|
public class LoginLogSummary {
|
||||||
|
|
||||||
|
@Schema(description = "会话总数")
|
||||||
|
private long total;
|
||||||
|
|
||||||
|
@Schema(description = "当前在线人数(未退出的会话数)")
|
||||||
|
private long online;
|
||||||
|
|
||||||
|
@Schema(description = "今日登录次数")
|
||||||
|
private long today;
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
-- =====================================================================
|
||||||
|
-- 用户登录日志(会话维度)
|
||||||
|
-- 一次成功登录产生一条会话记录(online=1, logout_time=null);
|
||||||
|
-- 用户主动退出时回填 logout_time 并置 online=0。在线状态以 logout_time 为空为准。
|
||||||
|
-- 兼容 PostgreSQL / 瀚高(HighGo)
|
||||||
|
-- =====================================================================
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS login_log
|
||||||
|
(
|
||||||
|
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
|
user_id BIGINT,
|
||||||
|
username VARCHAR(128),
|
||||||
|
real_name VARCHAR(128),
|
||||||
|
org_name VARCHAR(256),
|
||||||
|
ip VARCHAR(64),
|
||||||
|
user_agent VARCHAR(512),
|
||||||
|
login_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
logout_time TIMESTAMP,
|
||||||
|
online SMALLINT DEFAULT 1,
|
||||||
|
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_ll_user_id ON login_log (user_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_ll_login_time ON login_log (login_time);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_ll_online ON login_log (online);
|
||||||
|
|
||||||
|
COMMENT ON TABLE login_log IS '用户登录日志(一次成功登录一条会话记录,登出写入 logout_time 并置 online=0)';
|
||||||
|
COMMENT ON COLUMN login_log.user_id IS '系统用户ID';
|
||||||
|
COMMENT ON COLUMN login_log.username IS '登录账号';
|
||||||
|
COMMENT ON COLUMN login_log.real_name IS '姓名';
|
||||||
|
COMMENT ON COLUMN login_log.org_name IS '所属单位';
|
||||||
|
COMMENT ON COLUMN login_log.ip IS '登录IP';
|
||||||
|
COMMENT ON COLUMN login_log.user_agent IS '浏览器/客户端标识';
|
||||||
|
COMMENT ON COLUMN login_log.login_time IS '登录时间';
|
||||||
|
COMMENT ON COLUMN login_log.logout_time IS '退出时间,未退出为 null';
|
||||||
|
COMMENT ON COLUMN login_log.online IS '是否在线:1在线 0离线';
|
||||||
@@ -167,3 +167,36 @@ VALUES
|
|||||||
(2, '电子图书镜像库', '西安某院校图书馆', '10.0.0.41:8080', 'http://cdio.example.org/fulltext/BB-2026-0002-mirror', 'BB-2026-0002-MIRROR', '电子', 2);
|
(2, '电子图书镜像库', '西安某院校图书馆', '10.0.0.41:8080', 'http://cdio.example.org/fulltext/BB-2026-0002-mirror', 'BB-2026-0002-MIRROR', '电子', 2);
|
||||||
|
|
||||||
SELECT setval('resource_source_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM resource_source), 0), 1), true);
|
SELECT setval('resource_source_id_seq', GREATEST(COALESCE((SELECT MAX(id) FROM resource_source), 0), 1), true);
|
||||||
|
|
||||||
|
-- =====================================================================
|
||||||
|
-- 用户登录日志(会话维度):一次成功登录一条记录,登出写入 logout_time 并置 online=0
|
||||||
|
-- =====================================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS login_log
|
||||||
|
(
|
||||||
|
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
|
user_id BIGINT,
|
||||||
|
username VARCHAR(128),
|
||||||
|
real_name VARCHAR(128),
|
||||||
|
org_name VARCHAR(256),
|
||||||
|
ip VARCHAR(64),
|
||||||
|
user_agent VARCHAR(512),
|
||||||
|
login_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
logout_time TIMESTAMP,
|
||||||
|
online SMALLINT DEFAULT 1,
|
||||||
|
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_ll_user_id ON login_log (user_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_ll_login_time ON login_log (login_time);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_ll_online ON login_log (online);
|
||||||
|
|
||||||
|
COMMENT ON TABLE login_log IS '用户登录日志(一次成功登录一条会话记录,登出写入 logout_time 并置 online=0)';
|
||||||
|
COMMENT ON COLUMN login_log.user_id IS '系统用户ID';
|
||||||
|
COMMENT ON COLUMN login_log.username IS '登录账号';
|
||||||
|
COMMENT ON COLUMN login_log.real_name IS '姓名';
|
||||||
|
COMMENT ON COLUMN login_log.org_name IS '所属单位';
|
||||||
|
COMMENT ON COLUMN login_log.ip IS '登录IP';
|
||||||
|
COMMENT ON COLUMN login_log.user_agent IS '浏览器/客户端标识';
|
||||||
|
COMMENT ON COLUMN login_log.login_time IS '登录时间';
|
||||||
|
COMMENT ON COLUMN login_log.logout_time IS '退出时间,未退出为 null';
|
||||||
|
COMMENT ON COLUMN login_log.online IS '是否在线:1在线 0离线';
|
||||||
|
|||||||
@@ -146,3 +146,58 @@ export function saveListFields(scene: string, items: ListFieldConfig[]) {
|
|||||||
export function resetListFields(scene: string) {
|
export function resetListFields(scene: string) {
|
||||||
return request.post<never, ListFieldConfig[]>(`/admin/list-fields/${scene}/reset`)
|
return request.post<never, ListFieldConfig[]>(`/admin/list-fields/${scene}/reset`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==================== 登录日志 ====================
|
||||||
|
|
||||||
|
export interface LoginLog {
|
||||||
|
id?: number
|
||||||
|
userId?: number
|
||||||
|
/** 登录账号 */
|
||||||
|
username?: string
|
||||||
|
/** 姓名 */
|
||||||
|
realName?: string
|
||||||
|
/** 所属单位 */
|
||||||
|
orgName?: string
|
||||||
|
/** 登录IP */
|
||||||
|
ip?: string
|
||||||
|
/** 浏览器/客户端标识 */
|
||||||
|
userAgent?: string
|
||||||
|
/** 登录时间 */
|
||||||
|
loginTime?: string
|
||||||
|
/** 退出时间,未退出为 null */
|
||||||
|
logoutTime?: string | null
|
||||||
|
/** 是否在线:1在线 0离线 */
|
||||||
|
online?: number
|
||||||
|
createTime?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoginLogQuery {
|
||||||
|
current: number
|
||||||
|
size: number
|
||||||
|
keyword?: string
|
||||||
|
/** ONLINE 在线 / OFFLINE 离线 / 不传 全部 */
|
||||||
|
status?: string
|
||||||
|
/** 登录时间起(yyyy-MM-dd) */
|
||||||
|
loginStart?: string
|
||||||
|
/** 登录时间止(yyyy-MM-dd) */
|
||||||
|
loginEnd?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoginLogSummary {
|
||||||
|
/** 会话总数 */
|
||||||
|
total: number
|
||||||
|
/** 当前在线人数 */
|
||||||
|
online: number
|
||||||
|
/** 今日登录次数 */
|
||||||
|
today: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 登录日志分页 */
|
||||||
|
export function pageLoginLogs(params: LoginLogQuery) {
|
||||||
|
return request.get<never, PageResult<LoginLog>>('/admin/login-logs/page', { params })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 登录日志概览统计 */
|
||||||
|
export function loginLogSummary() {
|
||||||
|
return request.get<never, LoginLogSummary>('/admin/login-logs/summary')
|
||||||
|
}
|
||||||
|
|||||||
@@ -12,7 +12,8 @@ const menuTitle: Record<string, string> = {
|
|||||||
hits: '敏感词命中处置',
|
hits: '敏感词命中处置',
|
||||||
library: '院校资源库',
|
library: '院校资源库',
|
||||||
fields: '列表字段配置',
|
fields: '列表字段配置',
|
||||||
deposit: '呈缴管理'
|
deposit: '呈缴管理',
|
||||||
|
log: '日志管理'
|
||||||
}
|
}
|
||||||
const pageTitle = computed(() => menuTitle[activeMenu.value] || '后台管理')
|
const pageTitle = computed(() => menuTitle[activeMenu.value] || '后台管理')
|
||||||
|
|
||||||
@@ -50,6 +51,13 @@ import {
|
|||||||
type DepositQuery,
|
type DepositQuery,
|
||||||
type DepositRecord
|
type DepositRecord
|
||||||
} from '@/api/deposit'
|
} from '@/api/deposit'
|
||||||
|
import {
|
||||||
|
loginLogSummary,
|
||||||
|
pageLoginLogs,
|
||||||
|
type LoginLog,
|
||||||
|
type LoginLogQuery,
|
||||||
|
type LoginLogSummary
|
||||||
|
} from '@/api/admin'
|
||||||
|
|
||||||
// ==================== 敏感词库 ====================
|
// ==================== 敏感词库 ====================
|
||||||
const wordQuery = reactive({ current: 1, size: 10, keyword: '' })
|
const wordQuery = reactive({ current: 1, size: 10, keyword: '' })
|
||||||
@@ -438,6 +446,66 @@ function depositStatusText(status?: string) {
|
|||||||
return '待审核'
|
return '待审核'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==================== 日志管理 ====================
|
||||||
|
const logQuery = reactive<LoginLogQuery>({ current: 1, size: 20, keyword: '', status: '', loginStart: '', loginEnd: '' })
|
||||||
|
const logList = ref<LoginLog[]>([])
|
||||||
|
const logTotal = ref(0)
|
||||||
|
const logLoading = ref(false)
|
||||||
|
const logDateRange = ref<string[]>([])
|
||||||
|
const logSummary = ref<LoginLogSummary>({ total: 0, online: 0, today: 0 })
|
||||||
|
|
||||||
|
async function fetchLogs() {
|
||||||
|
logLoading.value = true
|
||||||
|
try {
|
||||||
|
const page = await pageLoginLogs({
|
||||||
|
current: logQuery.current,
|
||||||
|
size: logQuery.size,
|
||||||
|
keyword: logQuery.keyword || undefined,
|
||||||
|
status: logQuery.status || undefined,
|
||||||
|
loginStart: logDateRange.value?.[0] || undefined,
|
||||||
|
loginEnd: logDateRange.value?.[1] || undefined,
|
||||||
|
})
|
||||||
|
logList.value = page.records || []
|
||||||
|
logTotal.value = page.total || 0
|
||||||
|
} finally {
|
||||||
|
logLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchLogSummary() {
|
||||||
|
try {
|
||||||
|
logSummary.value = await loginLogSummary()
|
||||||
|
} catch {
|
||||||
|
logSummary.value = { total: 0, online: 0, today: 0 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function searchLogs() {
|
||||||
|
logQuery.current = 1
|
||||||
|
fetchLogs()
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetLogFilters() {
|
||||||
|
logQuery.keyword = ''
|
||||||
|
logQuery.status = ''
|
||||||
|
logDateRange.value = []
|
||||||
|
searchLogs()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 在线时长:未退出按当前时间算,已退出按退出时间算 */
|
||||||
|
function onlineDuration(row: LoginLog): string {
|
||||||
|
const start = row.loginTime ? new Date(row.loginTime).getTime() : 0
|
||||||
|
if (!start) return '-'
|
||||||
|
const end = row.logoutTime ? new Date(row.logoutTime).getTime() : Date.now()
|
||||||
|
const mins = Math.max(0, Math.floor((end - start) / 60000))
|
||||||
|
if (mins < 60) return `${mins} 分钟`
|
||||||
|
const hours = Math.floor(mins / 60)
|
||||||
|
const rem = mins % 60
|
||||||
|
if (hours < 24) return `${hours} 小时${rem ? ' ' + rem + ' 分' : ''}`
|
||||||
|
const days = Math.floor(hours / 24)
|
||||||
|
return `${days} 天 ${hours % 24} 小时`
|
||||||
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
fetchWords()
|
fetchWords()
|
||||||
fetchHits()
|
fetchHits()
|
||||||
@@ -445,6 +513,8 @@ onMounted(() => {
|
|||||||
fetchStats()
|
fetchStats()
|
||||||
fetchFields()
|
fetchFields()
|
||||||
fetchDeposits()
|
fetchDeposits()
|
||||||
|
fetchLogs()
|
||||||
|
fetchLogSummary()
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -468,6 +538,7 @@ onMounted(() => {
|
|||||||
<el-menu-item index="library">院校资源库</el-menu-item>
|
<el-menu-item index="library">院校资源库</el-menu-item>
|
||||||
<el-menu-item index="fields">列表字段配置</el-menu-item>
|
<el-menu-item index="fields">列表字段配置</el-menu-item>
|
||||||
<el-menu-item index="deposit">呈缴管理</el-menu-item>
|
<el-menu-item index="deposit">呈缴管理</el-menu-item>
|
||||||
|
<el-menu-item index="log">日志管理</el-menu-item>
|
||||||
</el-menu>
|
</el-menu>
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
@@ -780,6 +851,86 @@ onMounted(() => {
|
|||||||
@current-change="fetchDeposits"
|
@current-change="fetchDeposits"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- ==================== 日志管理 ==================== -->
|
||||||
|
<div v-show="activeMenu === 'log'">
|
||||||
|
<div class="log-summary">
|
||||||
|
<div class="log-card">
|
||||||
|
<div class="log-card__num">{{ logSummary.total }}</div>
|
||||||
|
<div class="log-card__label">会话总数</div>
|
||||||
|
</div>
|
||||||
|
<div class="log-card log-card--online">
|
||||||
|
<div class="log-card__num">{{ logSummary.online }}</div>
|
||||||
|
<div class="log-card__label">当前在线</div>
|
||||||
|
</div>
|
||||||
|
<div class="log-card log-card--today">
|
||||||
|
<div class="log-card__num">{{ logSummary.today }}</div>
|
||||||
|
<div class="log-card__label">今日登录</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="toolbar">
|
||||||
|
<el-input
|
||||||
|
v-model="logQuery.keyword"
|
||||||
|
placeholder="账号 / 姓名 / 单位"
|
||||||
|
clearable
|
||||||
|
style="width: 220px"
|
||||||
|
@keyup.enter="searchLogs"
|
||||||
|
@clear="searchLogs"
|
||||||
|
/>
|
||||||
|
<el-select v-model="logQuery.status" placeholder="全部状态" clearable style="width: 130px" @change="searchLogs">
|
||||||
|
<el-option label="在线" value="ONLINE" />
|
||||||
|
<el-option label="离线" value="OFFLINE" />
|
||||||
|
</el-select>
|
||||||
|
<el-date-picker
|
||||||
|
v-model="logDateRange"
|
||||||
|
type="daterange"
|
||||||
|
range-separator="至"
|
||||||
|
start-placeholder="登录起"
|
||||||
|
end-placeholder="登录止"
|
||||||
|
value-format="YYYY-MM-DD"
|
||||||
|
style="width: 260px"
|
||||||
|
@change="searchLogs"
|
||||||
|
/>
|
||||||
|
<el-button type="primary" @click="searchLogs">查询</el-button>
|
||||||
|
<el-button @click="resetLogFilters">重置</el-button>
|
||||||
|
<el-button @click="fetchLogSummary">刷新概览</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-table v-loading="logLoading" :data="logList" border stripe>
|
||||||
|
<el-table-column type="index" label="#" width="50" />
|
||||||
|
<el-table-column prop="username" label="账号" width="140" show-overflow-tooltip />
|
||||||
|
<el-table-column prop="realName" label="姓名" width="120" show-overflow-tooltip />
|
||||||
|
<el-table-column prop="orgName" label="单位" min-width="160" show-overflow-tooltip />
|
||||||
|
<el-table-column prop="ip" label="登录IP" width="140" />
|
||||||
|
<el-table-column prop="loginTime" label="登录时间" width="180" />
|
||||||
|
<el-table-column label="退出时间" width="180">
|
||||||
|
<template #default="{ row }">{{ row.logoutTime || '—' }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="在线时长" width="140">
|
||||||
|
<template #default="{ row }">{{ onlineDuration(row) }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="状态" width="90">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag size="small" :type="row.logoutTime ? 'info' : 'success'">
|
||||||
|
{{ row.logoutTime ? '离线' : '在线' }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<el-pagination
|
||||||
|
class="pager"
|
||||||
|
background
|
||||||
|
layout="total, sizes, prev, pager, next, jumper"
|
||||||
|
:total="logTotal"
|
||||||
|
v-model:current-page="logQuery.current"
|
||||||
|
v-model:page-size="logQuery.size"
|
||||||
|
:page-sizes="[10, 20, 50, 100]"
|
||||||
|
@current-change="fetchLogs"
|
||||||
|
@size-change="fetchLogs"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 敏感词 新增/编辑 弹窗 -->
|
<!-- 敏感词 新增/编辑 弹窗 -->
|
||||||
@@ -974,4 +1125,51 @@ onMounted(() => {
|
|||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.log-summary {
|
||||||
|
display: flex;
|
||||||
|
gap: 16px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-card {
|
||||||
|
min-width: 150px;
|
||||||
|
padding: 16px 20px;
|
||||||
|
border: 1px solid var(--card-gold-border);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
background: var(--brand-light);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-card__num {
|
||||||
|
font-size: 28px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--text-main);
|
||||||
|
font-family: var(--font-serif);
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-card__label {
|
||||||
|
margin-top: 4px;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-card--online {
|
||||||
|
background: #e8f5e9;
|
||||||
|
border-color: #b7dfc1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-card--online .log-card__num {
|
||||||
|
color: #2e7d32;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-card--today {
|
||||||
|
background: #eaf2fb;
|
||||||
|
border-color: #bcd4ef;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-card--today .log-card__num {
|
||||||
|
color: #1565c0;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
Reference in New Issue
Block a user