feat: 会话管理 - 支持按设备粒度踢下线
- 新增 sessions 表,每次登录创建会话记录(记录 IP/UA) - AuthMiddleware 改为基于 session 校验,可精确踢掉单个设备 - 自己改密码后踢掉其他设备,管理员改密码后踢掉该用户全部设备 - 新增 GET /api/me/sessions 查看活跃会话列表 - 新增 DELETE /api/me/sessions/:sessionId 踢掉指定会话 - 新增 DELETE /api/admin/users/:id/sessions 管理员强制下线某用户 - 兼容无 session_id 的旧 token,回退到 TokenInvalidBefore 校验
This commit is contained in:
@@ -2,12 +2,14 @@ package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"lmvpn/internal/db"
|
||||
"lmvpn/internal/middleware"
|
||||
"lmvpn/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
@@ -50,12 +52,25 @@ func Login(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
token, err := middleware.GenerateToken(user.ID, user.Username, user.Role)
|
||||
sessionID := uuid.New().String()
|
||||
token, err := middleware.GenerateToken(sessionID, user.ID, user.Username, user.Role)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "生成令牌失败"})
|
||||
return
|
||||
}
|
||||
|
||||
session := model.Session{
|
||||
SessionID: sessionID,
|
||||
UserID: user.ID,
|
||||
IP: c.ClientIP(),
|
||||
UserAgent: c.GetHeader("User-Agent"),
|
||||
ExpiresAt: time.Now().Add(24 * time.Hour),
|
||||
}
|
||||
if err := db.DB.Create(&session).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "创建会话失败"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, loginResponse{
|
||||
Token: token,
|
||||
User: userInfo{
|
||||
@@ -102,11 +117,18 @@ func ChangePassword(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := db.DB.Model(&user).Update("password", string(hash)).Error; err != nil {
|
||||
now := time.Now()
|
||||
if err := db.DB.Model(&user).Updates(map[string]interface{}{
|
||||
"password": string(hash),
|
||||
"token_invalid_before": now,
|
||||
}).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "密码修改失败"})
|
||||
return
|
||||
}
|
||||
|
||||
sessionID, _ := c.Get("session_id")
|
||||
db.DB.Model(&model.Session{}).Where("user_id = ? AND session_id != ?", userID, sessionID).Update("invalid", true)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "密码修改成功"})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"lmvpn/internal/db"
|
||||
"lmvpn/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type sessionResponse struct {
|
||||
SessionID string `json:"session_id"`
|
||||
IP string `json:"ip"`
|
||||
UserAgent string `json:"user_agent"`
|
||||
Current bool `json:"current"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
}
|
||||
|
||||
func ListMySessions(c *gin.Context) {
|
||||
userID, _ := c.Get("user_id")
|
||||
currentSessionID, _ := c.Get("session_id")
|
||||
|
||||
var sessions []model.Session
|
||||
db.DB.Where("user_id = ? AND invalid = ? AND expires_at > ?", userID, false, time.Now()).
|
||||
Order("created_at desc").
|
||||
Find(&sessions)
|
||||
|
||||
result := make([]sessionResponse, len(sessions))
|
||||
for i, s := range sessions {
|
||||
result[i] = sessionResponse{
|
||||
SessionID: s.SessionID,
|
||||
IP: s.IP,
|
||||
UserAgent: s.UserAgent,
|
||||
Current: s.SessionID == currentSessionID,
|
||||
CreatedAt: s.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
ExpiresAt: s.ExpiresAt.Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"sessions": result})
|
||||
}
|
||||
|
||||
func RevokeMySession(c *gin.Context) {
|
||||
sessionID := c.Param("sessionId")
|
||||
if sessionID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
|
||||
return
|
||||
}
|
||||
|
||||
userID, _ := c.Get("user_id")
|
||||
currentSessionID, _ := c.Get("session_id")
|
||||
|
||||
if sessionID == currentSessionID {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "不能撤销当前会话"})
|
||||
return
|
||||
}
|
||||
|
||||
var session model.Session
|
||||
if err := db.DB.Where("session_id = ? AND user_id = ?", sessionID, userID).First(&session).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "会话不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
db.DB.Model(&session).Update("invalid", true)
|
||||
c.JSON(http.StatusOK, gin.H{"message": "已撤销会话"})
|
||||
}
|
||||
|
||||
func AdminRevokeUserSessions(c *gin.Context) {
|
||||
idStr := c.Param("id")
|
||||
id, err := strconv.ParseUint(idStr, 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
|
||||
return
|
||||
}
|
||||
|
||||
var user model.User
|
||||
if err := db.DB.First(&user, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
db.DB.Model(&model.Session{}).Where("user_id = ?", id).Update("invalid", true)
|
||||
c.JSON(http.StatusOK, gin.H{"message": "已强制下线该用户"})
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"lmvpn/internal/db"
|
||||
"lmvpn/internal/model"
|
||||
@@ -153,6 +154,7 @@ func UpdateUser(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
updates["password"] = string(hash)
|
||||
updates["token_invalid_before"] = time.Now()
|
||||
}
|
||||
|
||||
if len(updates) == 0 {
|
||||
@@ -165,6 +167,10 @@ func UpdateUser(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if req.Password != "" {
|
||||
db.DB.Model(&model.Session{}).Where("user_id = ?", id).Update("invalid", true)
|
||||
}
|
||||
|
||||
db.DB.First(&user, id)
|
||||
c.JSON(http.StatusOK, formatUser(&user))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user