feat(session): add session removal endpoint and refactor session management
- Implement new `/sessionMgr/remove` endpoint for superusers to remove sessions - Refactor session and token management to use sessionTokenMap for better tracking - Update session cleanup logic to handle both tokens and sessions - Add documentation for new API endpoint in docs/api.md - Modify logout handler to use new session removal approach
This commit is contained in:
@@ -38,7 +38,7 @@ Create a `config.json` file in the project root:
|
|||||||
## Build
|
## Build
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
go build -o super-frpc
|
go build -o super-frpc.exe
|
||||||
```
|
```
|
||||||
|
|
||||||
For Linux:
|
For Linux:
|
||||||
@@ -60,7 +60,7 @@ For detailed API documentation, please see [docs/api.md](docs/api.md)
|
|||||||
|
|
||||||
- [x] Add Windows boot service support
|
- [x] Add Windows boot service support
|
||||||
- [x] Add session list API
|
- [x] Add session list API
|
||||||
- [ ] Add session management API
|
- [x] Add session management API
|
||||||
- [ ] Add codes per file documentation
|
- [ ] Add codes per file documentation
|
||||||
- [ ] Add user config modify API
|
- [ ] Add user config modify API
|
||||||
|
|
||||||
|
|||||||
@@ -313,6 +313,15 @@ func DBQueryUsers() ([]User, error) { // List all users
|
|||||||
return users, nil
|
return users, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func DBQuerySpecificUser(userID int) (User, error) { // Query user by ID
|
||||||
|
var user User
|
||||||
|
err := db.QueryRow("SELECT userID, username, type FROM userLogin WHERE userID = ?", userID).Scan(&user.UserID, &user.Username, &user.Type)
|
||||||
|
if err != nil {
|
||||||
|
return user, fmt.Errorf("failed to query user: %w", err)
|
||||||
|
}
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
func DBAddFrpcInstance(instance FrpcInstance) error {
|
func DBAddFrpcInstance(instance FrpcInstance) error {
|
||||||
_, err := frpcDB.Exec("INSERT INTO frpcInstances (userID, name, serverAddr, serverPort, auth_method, bootAtStart, runUser, configPath, createdAt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
_, err := frpcDB.Exec("INSERT INTO frpcInstances (userID, name, serverAddr, serverPort, auth_method, bootAtStart, runUser, configPath, createdAt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
instance.UserID, instance.Name, instance.ServerAddr, instance.ServerPort, instance.AuthMethod, instance.BootAtStart, instance.RunUser, instance.ConfigPath, time.Now().Format(time.RFC3339))
|
instance.UserID, instance.Name, instance.ServerAddr, instance.ServerPort, instance.AuthMethod, instance.BootAtStart, instance.RunUser, instance.ConfigPath, time.Now().Format(time.RFC3339))
|
||||||
|
|||||||
+42
@@ -299,6 +299,48 @@ X-Timestamp: 1704067200000
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Remove Session
|
||||||
|
|
||||||
|
**Endpoint**: `/sessionMgr/remove`
|
||||||
|
**Method**: POST
|
||||||
|
**Content-Type**: application/json
|
||||||
|
**Auth Required**: Yes (token)
|
||||||
|
**Permission Level**: Superuser
|
||||||
|
|
||||||
|
**Request Headers**:
|
||||||
|
```
|
||||||
|
X-Token: your_token
|
||||||
|
X-Timestamp: 1704067200000
|
||||||
|
```
|
||||||
|
|
||||||
|
**Request Body**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"sessionID": "session-5f4dcc3b5aa765d61d8327deb882cf99-1704067200000"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Header | Type | Required | Description |
|
||||||
|
|--------|------|----------|-------------|
|
||||||
|
| X-Token | string | Yes | Authentication token |
|
||||||
|
| X-Timestamp | int64 | Yes | Client timestamp in milliseconds |
|
||||||
|
|
||||||
|
| Field | Type | Required | Description |
|
||||||
|
|-------|------|----------|-------------|
|
||||||
|
| sessionID | string | Yes | Session ID to remove |
|
||||||
|
|
||||||
|
**Response**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"message": "Session removed successfully"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Note**: This endpoint requires superuser permission. It removes a session by its sessionID and also removes the associated token, forcing the user to re-login.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Create frpc Instance
|
## Create frpc Instance
|
||||||
|
|
||||||
**Endpoint:** `/frpcAct/instanceMgr/create`
|
**Endpoint:** `/frpcAct/instanceMgr/create`
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ func setupRoutes() {
|
|||||||
// http.HandleFunc("/userMgr/modify", ModifyUserHandler)
|
// http.HandleFunc("/userMgr/modify", ModifyUserHandler)
|
||||||
|
|
||||||
http.HandleFunc("/sessionMgr/list", ListActiveSessionsHandler)
|
http.HandleFunc("/sessionMgr/list", ListActiveSessionsHandler)
|
||||||
|
http.HandleFunc("/sessionMgr/remove", RemoveSessionHandler)
|
||||||
|
|
||||||
http.HandleFunc("/frpcAct/instanceMgr/create", CreateInstanceHandler)
|
http.HandleFunc("/frpcAct/instanceMgr/create", CreateInstanceHandler)
|
||||||
http.HandleFunc("/frpcAct/instanceMgr/list", ListInstancesHandler)
|
http.HandleFunc("/frpcAct/instanceMgr/list", ListInstancesHandler)
|
||||||
|
|||||||
+34
-20
@@ -21,7 +21,7 @@ type TokenInfo struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
tokenMap = make(map[int]*TokenInfo)
|
tokenMap = make(map[int]*TokenInfo) // userID -> TokenInfo
|
||||||
tokenMux sync.RWMutex
|
tokenMux sync.RWMutex
|
||||||
tokenTTL = time.Hour
|
tokenTTL = time.Hour
|
||||||
)
|
)
|
||||||
@@ -34,11 +34,16 @@ type Session struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
sessionMap = make(map[string]*Session)
|
sessionMap = make(map[string]*Session) // sessionID -> Session
|
||||||
sessionMux sync.RWMutex
|
sessionMux sync.RWMutex
|
||||||
sessionTTL = time.Hour
|
sessionTTL = time.Hour
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
sessionTokenMap = make(map[string]string) // sessionID -> token
|
||||||
|
sessionTokenMux sync.RWMutex
|
||||||
|
)
|
||||||
|
|
||||||
func GenerateToken(userID int) (string, error) {
|
func GenerateToken(userID int) (string, error) {
|
||||||
randomBytes := make([]byte, 32)
|
randomBytes := make([]byte, 32)
|
||||||
_, err := rand.Read(randomBytes)
|
_, err := rand.Read(randomBytes)
|
||||||
@@ -144,7 +149,15 @@ func CleanupExpiredTokens() {
|
|||||||
if time.Since(tokenInfo.CreatedAt) > tokenTTL {
|
if time.Since(tokenInfo.CreatedAt) > tokenTTL {
|
||||||
delete(tokenMap, userID)
|
delete(tokenMap, userID)
|
||||||
postLog.Debug(fmt.Sprintf("[CleanupExpiredTokens] Removed expired token for userID %d: %s", userID, tokenInfo.Token))
|
postLog.Debug(fmt.Sprintf("[CleanupExpiredTokens] Removed expired token for userID %d: %s", userID, tokenInfo.Token))
|
||||||
RemoveSession(userID, "")
|
sessionTokenMux.Lock()
|
||||||
|
for sessionID, sessionToken := range sessionTokenMap {
|
||||||
|
if sessionToken == tokenInfo.Token {
|
||||||
|
delete(sessionTokenMap, sessionID)
|
||||||
|
delete(sessionMap, sessionID)
|
||||||
|
postLog.Debug(fmt.Sprintf("[CleanupExpiredTokens] Removed expired session %s for userID %d", sessionID, userID))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sessionTokenMux.Unlock()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -153,9 +166,13 @@ func CleanupExpiredSessions() {
|
|||||||
sessionMux.Lock()
|
sessionMux.Lock()
|
||||||
defer sessionMux.Unlock()
|
defer sessionMux.Unlock()
|
||||||
|
|
||||||
|
sessionTokenMux.Lock()
|
||||||
|
defer sessionTokenMux.Unlock()
|
||||||
|
|
||||||
for sessionID, session := range sessionMap {
|
for sessionID, session := range sessionMap {
|
||||||
if time.Now().After(session.ExpireAt) {
|
if time.Now().After(session.ExpireAt) {
|
||||||
delete(sessionMap, sessionID)
|
delete(sessionMap, sessionID)
|
||||||
|
delete(sessionTokenMap, sessionID)
|
||||||
postLog.Debug(fmt.Sprintf("[CleanupExpiredSessions] Removed expired session %s for user [%d]%s", sessionID, session.UserID, session.Username))
|
postLog.Debug(fmt.Sprintf("[CleanupExpiredSessions] Removed expired session %s for user [%d]%s", sessionID, session.UserID, session.Username))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -271,35 +288,32 @@ func JoinSession(userID int, userName string, token string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
sessionMap[sessionID] = session
|
sessionMap[sessionID] = session
|
||||||
|
sessionTokenMap[sessionID] = token
|
||||||
postLog.Debug(fmt.Sprintf("[JoinSession] User [%d]%s joined session %s with token %s", userID, userName, sessionID, token))
|
postLog.Debug(fmt.Sprintf("[JoinSession] User [%d]%s joined session %s with token %s", userID, userName, sessionID, token))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func RemoveSession(userID int, token string) error {
|
func RemoveSession(sessionID string) error {
|
||||||
sessionMux.Lock()
|
sessionMux.Lock()
|
||||||
defer sessionMux.Unlock()
|
defer sessionMux.Unlock()
|
||||||
|
|
||||||
var sessionIDToRemove string
|
session, exists := sessionMap[sessionID]
|
||||||
for sessionID, session := range sessionMap {
|
if !exists {
|
||||||
if session.UserID == userID {
|
return fmt.Errorf("Session not found: %s", sessionID)
|
||||||
sessionIDToRemove = sessionID
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if sessionIDToRemove != "" {
|
_, exists = sessionTokenMap[sessionID]
|
||||||
delete(sessionMap, sessionIDToRemove)
|
if !exists {
|
||||||
postLog.Info(fmt.Sprintf("[RemoveSession] Removed session %s for user [%d]%s", sessionIDToRemove, userID, GetUsernameByID(userID)))
|
delete(sessionMap, sessionID)
|
||||||
|
return fmt.Errorf("Token not found for session: %s", sessionID)
|
||||||
}
|
}
|
||||||
|
|
||||||
tokenMux.Lock()
|
delete(sessionMap, sessionID)
|
||||||
defer tokenMux.Unlock()
|
delete(sessionTokenMap, sessionID)
|
||||||
|
|
||||||
if tokenInfo, exists := tokenMap[userID]; exists {
|
if tokenInfo, exists := tokenMap[session.UserID]; exists {
|
||||||
if tokenInfo.Token == token || token == "" {
|
DeleteTokenInfo(session.UserID)
|
||||||
delete(tokenMap, userID)
|
postLog.Info(fmt.Sprintf("[RemoveSession] Removed session '%s': '[%d]%s'", sessionID, tokenInfo.UserID, GetUsernameByID(tokenInfo.UserID)))
|
||||||
postLog.Info(fmt.Sprintf("[RemoveSession] Removed token for user [%d]%s", userID, GetUsernameByID(userID)))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
+78
-1
@@ -28,6 +28,10 @@ type RemoveUserRequest struct {
|
|||||||
TargetUserID int `json:"targetUserID"`
|
TargetUserID int `json:"targetUserID"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type RemoveSessionRequest struct {
|
||||||
|
SessionID string `json:"sessionID"`
|
||||||
|
}
|
||||||
|
|
||||||
func RegisterHandler(w http.ResponseWriter, r *http.Request) {
|
func RegisterHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method != http.MethodPost {
|
if r.Method != http.MethodPost {
|
||||||
SendErrorResponse(w, http.StatusMethodNotAllowed, "Invalid request method")
|
SendErrorResponse(w, http.StatusMethodNotAllowed, "Invalid request method")
|
||||||
@@ -195,7 +199,23 @@ func LogoutHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := RemoveSession(userID, r.Header.Get("X-Token")); err != nil {
|
sessionTokenMux.RLock()
|
||||||
|
sessionID := ""
|
||||||
|
for sid, token := range sessionTokenMap {
|
||||||
|
if token == r.Header.Get("X-Token") {
|
||||||
|
sessionID = sid
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sessionTokenMux.RUnlock()
|
||||||
|
|
||||||
|
if sessionID == "" {
|
||||||
|
SendErrorResponse(w, http.StatusNotFound, "Session not found for token")
|
||||||
|
postLog.Warning(fmt.Sprintf("[LogoutHandler] Session not found for token from user [%d]%s", userID, GetUsernameByID(userID)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := RemoveSession(sessionID); err != nil {
|
||||||
SendErrorResponse(w, http.StatusInternalServerError, "Failed to logout")
|
SendErrorResponse(w, http.StatusInternalServerError, "Failed to logout")
|
||||||
postLog.Error(fmt.Sprintf("[LogoutHandler] Failed to logout user [%d]%s: %v", userID, GetUsernameByID(userID), err))
|
postLog.Error(fmt.Sprintf("[LogoutHandler] Failed to logout user [%d]%s: %v", userID, GetUsernameByID(userID), err))
|
||||||
return
|
return
|
||||||
@@ -205,6 +225,63 @@ func LogoutHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
postLog.Info(fmt.Sprintf("[LogoutHandler] User [%d]%s Logout successful", userID, GetUsernameByID(userID)))
|
postLog.Info(fmt.Sprintf("[LogoutHandler] User [%d]%s Logout successful", userID, GetUsernameByID(userID)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func RemoveSessionHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
SendErrorResponse(w, http.StatusMethodNotAllowed, "Invalid request method")
|
||||||
|
postLog.Warning(fmt.Sprintf("[RemoveSessionHandler] Invalid request method: %s", r.Method))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !ValidateTimeStamp(r.Header) {
|
||||||
|
SendErrorResponse(w, http.StatusBadRequest, "Invalid or missing X-Timestamp in header")
|
||||||
|
postLog.Warning("[RemoveSessionHandler] Invalid or missing X-Timestamp in header")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := io.ReadAll(r.Body)
|
||||||
|
if err != nil {
|
||||||
|
SendErrorResponse(w, http.StatusBadRequest, "Failed to read request body")
|
||||||
|
postLog.Warning(fmt.Sprintf("[RemoveSessionHandler] Failed to read request body: %v", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
|
|
||||||
|
var req RemoveSessionRequest
|
||||||
|
if err := json.Unmarshal(body, &req); err != nil {
|
||||||
|
SendErrorResponse(w, http.StatusBadRequest, "Invalid request format")
|
||||||
|
postLog.Warning(fmt.Sprintf("[RemoveSessionHandler] Invalid request format: %v", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.SessionID == "" {
|
||||||
|
SendErrorResponse(w, http.StatusBadRequest, "SessionID is required")
|
||||||
|
postLog.Warning("[RemoveSessionHandler] SessionID is empty")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
userID, err := extractUserIDFromToken(r.Header.Get("X-Token"))
|
||||||
|
if err != nil {
|
||||||
|
SendErrorResponse(w, http.StatusUnauthorized, "Invalid or missing token")
|
||||||
|
postLog.Warning(fmt.Sprintf("[RemoveSessionHandler] Invalid or missing token: %v", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := CheckPermission(userID, "superuser"); err != nil {
|
||||||
|
SendErrorResponse(w, http.StatusForbidden, "Permission denied")
|
||||||
|
postLog.Warning(fmt.Sprintf("[RemoveSessionHandler] Permission denied for user [%d]%s: %v", userID, GetUsernameByID(userID), err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := RemoveSession(req.SessionID); err != nil {
|
||||||
|
SendErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("Failed to remove session: %v", err))
|
||||||
|
postLog.Error(fmt.Sprintf("[RemoveSessionHandler] Failed to remove session %s: %v", req.SessionID, err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
postLog.Info(fmt.Sprintf("[RemoveSessionHandler] User [%d]%s removed session %s", userID, GetUsernameByID(userID), req.SessionID))
|
||||||
|
SendSuccessResponse(w, "Session removed successfully", nil)
|
||||||
|
}
|
||||||
|
|
||||||
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
|
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method != http.MethodPost {
|
if r.Method != http.MethodPost {
|
||||||
SendErrorResponse(w, http.StatusMethodNotAllowed, "Invalid request method")
|
SendErrorResponse(w, http.StatusMethodNotAllowed, "Invalid request method")
|
||||||
|
|||||||
Reference in New Issue
Block a user