This commit is contained in:
2026-11-04 14:39:25 +08:00
parent 4f3fc578d0
commit 0b5c0a40e9
14 changed files with 721 additions and 2 deletions
@@ -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.entity.SysUser;
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.tags.Tag;
import jakarta.validation.Valid;
@@ -23,6 +25,7 @@ import java.util.List;
public class AuthController {
private final AuthService authService;
private final LoginLogService loginLogService;
@Operation(summary = "登录")
@PostMapping("/login")
@@ -45,7 +48,8 @@ public class AuthController {
@Operation(summary = "登出")
@PostMapping("/logout")
public Result<Void> logout() {
// 采用无状态 JWT,登出由前端清除本地令牌即可;此处预留服务端黑名单能力
// 采用无状态 JWT,登出由前端清除本地令牌即可;此处同时回填登录日志的退出时间
loginLogService.recordLogout(UserContext.currentUserId());
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;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.banben.common.BusinessException;
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.nav.NavMenus;
import com.banben.modules.auth.service.AuthService;
import com.banben.modules.auth.service.LoginLogService;
import com.banben.modules.auth.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
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.util.ArrayList;
@@ -36,6 +41,7 @@ public class AuthServiceImpl implements AuthService {
private final SysRoleMenuMapper roleMenuMapper;
private final PasswordEncoder passwordEncoder;
private final JwtUtil jwtUtil;
private final LoginLogService loginLogService;
@Override
public LoginResponse login(LoginRequest request) {
@@ -60,6 +66,12 @@ public class AuthServiceImpl implements AuthService {
user.setLastLoginTime(LocalDateTime.now());
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());
LoginResponse response = new LoginResponse();
@@ -129,4 +141,28 @@ public class AuthServiceImpl implements AuthService {
SysRole role = sysRoleMapper.selectById(user.getRoleId());
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离线';