diff --git a/backend/src/main/java/com/banben/modules/auth/LoginLogTableInitializer.java b/backend/src/main/java/com/banben/modules/auth/LoginLogTableInitializer.java
new file mode 100644
index 0000000..459e029
--- /dev/null
+++ b/backend/src/main/java/com/banben/modules/auth/LoginLogTableInitializer.java
@@ -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;
+
+/**
+ * 登录日志表自举建表。
+ *
+ *
应用本身不在启动时自动执行建表脚本(dev/prod 的初始化脚本仅在数据库首次初始化时跑一次)。
+ * 但登录日志功能是后加的,已初始化的运行库里可能缺这张表,会导致 {@code /admin/login-logs/page}
+ * 直接抛 500。这里在容器就绪后幂等地补建该表,保证新库旧库都能正常工作,不影响已有数据。
+ */
+@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());
+ }
+ }
+}
diff --git a/backend/src/main/java/com/banben/modules/auth/controller/AuthController.java b/backend/src/main/java/com/banben/modules/auth/controller/AuthController.java
index 6a760f5..67b6b51 100644
--- a/backend/src/main/java/com/banben/modules/auth/controller/AuthController.java
+++ b/backend/src/main/java/com/banben/modules/auth/controller/AuthController.java
@@ -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 logout() {
- // 采用无状态 JWT,登出由前端清除本地令牌即可;此处预留服务端黑名单能力
+ // 采用无状态 JWT,登出由前端清除本地令牌即可;此处同时回填登录日志的退出时间
+ loginLogService.recordLogout(UserContext.currentUserId());
return Result.success();
}
}
diff --git a/backend/src/main/java/com/banben/modules/auth/controller/LoginLogController.java b/backend/src/main/java/com/banben/modules/auth/controller/LoginLogController.java
new file mode 100644
index 0000000..faa403b
--- /dev/null
+++ b/backend/src/main/java/com/banben/modules/auth/controller/LoginLogController.java
@@ -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> page(LoginLogQuery query) {
+ adminAccess.require();
+ return Result.success(loginLogService.page(query));
+ }
+
+ @Operation(summary = "登录日志概览:会话总数 / 当前在线 / 今日登录")
+ @GetMapping("/summary")
+ public Result summary() {
+ adminAccess.require();
+ return Result.success(loginLogService.summary());
+ }
+}
diff --git a/backend/src/main/java/com/banben/modules/auth/dto/LoginLogQuery.java b/backend/src/main/java/com/banben/modules/auth/dto/LoginLogQuery.java
new file mode 100644
index 0000000..2148334
--- /dev/null
+++ b/backend/src/main/java/com/banben/modules/auth/dto/LoginLogQuery.java
@@ -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;
+}
diff --git a/backend/src/main/java/com/banben/modules/auth/entity/LoginLog.java b/backend/src/main/java/com/banben/modules/auth/entity/LoginLog.java
new file mode 100644
index 0000000..fe34a32
--- /dev/null
+++ b/backend/src/main/java/com/banben/modules/auth/entity/LoginLog.java
@@ -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;
+
+/**
+ * 用户登录日志(会话维度)。
+ *
+ * 一次成功登录产生一条会话记录:{@code online=1}、{@code logoutTime=null};
+ * 用户主动退出时回填 {@code logoutTime} 并置 {@code online=0}。
+ * 「在线」状态以 {@code logoutTime 为 null} 为准,前端据此展示在线/离线。
+ */
+@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;
+}
diff --git a/backend/src/main/java/com/banben/modules/auth/mapper/LoginLogMapper.java b/backend/src/main/java/com/banben/modules/auth/mapper/LoginLogMapper.java
new file mode 100644
index 0000000..7724814
--- /dev/null
+++ b/backend/src/main/java/com/banben/modules/auth/mapper/LoginLogMapper.java
@@ -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 {
+}
diff --git a/backend/src/main/java/com/banben/modules/auth/service/LoginLogService.java b/backend/src/main/java/com/banben/modules/auth/service/LoginLogService.java
new file mode 100644
index 0000000..62d0d74
--- /dev/null
+++ b/backend/src/main/java/com/banben/modules/auth/service/LoginLogService.java
@@ -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 page(LoginLogQuery query);
+
+ /** 概览统计:总数 / 在线 / 今日登录。 */
+ LoginLogSummary summary();
+}
diff --git a/backend/src/main/java/com/banben/modules/auth/service/impl/AuthServiceImpl.java b/backend/src/main/java/com/banben/modules/auth/service/impl/AuthServiceImpl.java
index 6dce1c8..4d33b15 100644
--- a/backend/src/main/java/com/banben/modules/auth/service/impl/AuthServiceImpl.java
+++ b/backend/src/main/java/com/banben/modules/auth/service/impl/AuthServiceImpl.java
@@ -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();
+ }
}
diff --git a/backend/src/main/java/com/banben/modules/auth/service/impl/LoginLogServiceImpl.java b/backend/src/main/java/com/banben/modules/auth/service/impl/LoginLogServiceImpl.java
new file mode 100644
index 0000000..b25b73c
--- /dev/null
+++ b/backend/src/main/java/com/banben/modules/auth/service/impl/LoginLogServiceImpl.java
@@ -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()
+ .eq("user_id", userId)
+ .isNull("logout_time")
+ .orderByDesc("login_time")
+ .last("LIMIT 1"));
+ } catch (Exception e) {
+ log.warn("记录退出日志失败:{}", e.getMessage());
+ }
+ }
+
+ @Override
+ public PageResult page(LoginLogQuery q) {
+ long current = q.getCurrent() == null ? 1L : q.getCurrent();
+ long size = q.getSize() == null ? 20L : q.getSize();
+ try {
+ QueryWrapper 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 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().eq("online", 1).isNull("logout_time")));
+ LocalDateTime startOfToday = LocalDate.now().atStartOfDay();
+ s.setToday(logMapper.selectCount(new QueryWrapper().ge("login_time", startOfToday)));
+ } catch (Exception e) {
+ log.warn("统计登录日志概览失败:{}", e.getMessage());
+ }
+ return s;
+ }
+}
diff --git a/backend/src/main/java/com/banben/modules/auth/vo/LoginLogSummary.java b/backend/src/main/java/com/banben/modules/auth/vo/LoginLogSummary.java
new file mode 100644
index 0000000..d140462
--- /dev/null
+++ b/backend/src/main/java/com/banben/modules/auth/vo/LoginLogSummary.java
@@ -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;
+}
diff --git a/backend/src/main/resources/db/schema-v17.sql b/backend/src/main/resources/db/schema-v17.sql
new file mode 100644
index 0000000..f34fcab
--- /dev/null
+++ b/backend/src/main/resources/db/schema-v17.sql
@@ -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离线';
diff --git a/deploy/db/init.sql b/deploy/db/init.sql
index 6bf8098..b7e375a 100644
--- a/deploy/db/init.sql
+++ b/deploy/db/init.sql
@@ -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);
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离线';
diff --git a/frontend/src/api/admin.ts b/frontend/src/api/admin.ts
index 406ee15..15584ff 100644
--- a/frontend/src/api/admin.ts
+++ b/frontend/src/api/admin.ts
@@ -146,3 +146,58 @@ export function saveListFields(scene: string, items: ListFieldConfig[]) {
export function resetListFields(scene: string) {
return request.post(`/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>('/admin/login-logs/page', { params })
+}
+
+/** 登录日志概览统计 */
+export function loginLogSummary() {
+ return request.get('/admin/login-logs/summary')
+}
diff --git a/frontend/src/views/admin/AdminView.vue b/frontend/src/views/admin/AdminView.vue
index 679481d..0e0d5a9 100644
--- a/frontend/src/views/admin/AdminView.vue
+++ b/frontend/src/views/admin/AdminView.vue
@@ -12,7 +12,8 @@ const menuTitle: Record = {
hits: '敏感词命中处置',
library: '院校资源库',
fields: '列表字段配置',
- deposit: '呈缴管理'
+ deposit: '呈缴管理',
+ log: '日志管理'
}
const pageTitle = computed(() => menuTitle[activeMenu.value] || '后台管理')
@@ -50,6 +51,13 @@ import {
type DepositQuery,
type DepositRecord
} from '@/api/deposit'
+import {
+ loginLogSummary,
+ pageLoginLogs,
+ type LoginLog,
+ type LoginLogQuery,
+ type LoginLogSummary
+} from '@/api/admin'
// ==================== 敏感词库 ====================
const wordQuery = reactive({ current: 1, size: 10, keyword: '' })
@@ -438,6 +446,66 @@ function depositStatusText(status?: string) {
return '待审核'
}
+// ==================== 日志管理 ====================
+const logQuery = reactive({ current: 1, size: 20, keyword: '', status: '', loginStart: '', loginEnd: '' })
+const logList = ref([])
+const logTotal = ref(0)
+const logLoading = ref(false)
+const logDateRange = ref([])
+const logSummary = ref({ 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(() => {
fetchWords()
fetchHits()
@@ -445,6 +513,8 @@ onMounted(() => {
fetchStats()
fetchFields()
fetchDeposits()
+ fetchLogs()
+ fetchLogSummary()
})
@@ -468,6 +538,7 @@ onMounted(() => {
院校资源库
列表字段配置
呈缴管理
+ 日志管理
@@ -780,6 +851,86 @@ onMounted(() => {
@current-change="fetchDeposits"
/>
+
+
+
+
+
+
{{ logSummary.total }}
+
会话总数
+
+
+
{{ logSummary.online }}
+
当前在线
+
+
+
{{ logSummary.today }}
+
今日登录
+
+
+
+
+
+
+
+
+
+
+ 查询
+ 重置
+ 刷新概览
+
+
+
+
+
+
+
+
+
+
+ {{ row.logoutTime || '—' }}
+
+
+ {{ onlineDuration(row) }}
+
+
+
+
+ {{ row.logoutTime ? '离线' : '在线' }}
+
+
+
+
+
+
+
@@ -974,4 +1125,51 @@ onMounted(() => {
font-size: 12px;
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;
+}