Add logout functionality and expose refresh token retrieval

- Implemented GinLogout function to handle user logout, including revoking access and refresh tokens, clearing authentication cookies, and returning a success response.
- Added public method GetRefreshToken to retrieve the refresh token from the request, enhancing token management.
- Updated user routing to link the logout endpoint to the new GinLogout function, improving the user authentication flow.
This commit is contained in:
Max 2025-10-16 14:53:49 +08:00
parent a8159a0e90
commit c58bc8c4fe
3 changed files with 40 additions and 1 deletions

View file

@ -153,6 +153,11 @@ func (s *Service) getRefreshToken(c *gin.Context) string {
return strings.TrimPrefix(token, "Bearer ")
}
// GetRefreshToken gets the refresh token from the request (public method)
func (s *Service) GetRefreshToken(c *gin.Context) string {
return s.getRefreshToken(c)
}
// Get Session ID from cookies, headers, or query string
func (s *Service) getSessionID(c *gin.Context) string {

View file

@ -438,6 +438,40 @@ func generateSessionID() string {
return session.ID()
}
// GinLogout handles user logout
func GinLogout(c *gin.Context) {
ctx := c.Request.Context()
// Get access token and refresh token from cookies or headers
// These methods already handle Bearer prefix removal and cookie prefixes
accessToken := oauth.OAuth.GetAccessToken(c)
refreshToken := oauth.OAuth.GetRefreshToken(c)
// Revoke access token if present
if accessToken != "" {
err := oauth.OAuth.Revoke(ctx, accessToken, "access_token")
if err != nil {
log.Warn("Failed to revoke access token during logout: %v", err)
}
}
// Revoke refresh token if present
if refreshToken != "" {
err := oauth.OAuth.Revoke(ctx, refreshToken, "refresh_token")
if err != nil {
log.Warn("Failed to revoke refresh token during logout: %v", err)
}
}
// Clear all authentication cookies
response.DeleteAllAuthCookies(c)
// Return success response
response.RespondWithSuccess(c, http.StatusOK, gin.H{
"message": "Logout successful",
})
}
// SendLoginCookies sends all necessary cookies for a successful login
// This includes access token, refresh token, and optionally session ID cookies with appropriate security settings
func SendLoginCookies(c *gin.Context, loginResponse *LoginResponse, sessionID string) {

View file

@ -36,7 +36,7 @@ func Attach(group *gin.RouterGroup, oauth types.OAuth) {
group.POST("/entry/register", oauth.Guard, GinEntryRegister) // Register a new user
group.POST("/entry/login", oauth.Guard, GinEntryLogin) // Login a user
group.POST("/entry/otp", oauth.Guard, GinSendOTP) // Send OTP
group.POST("/logout", oauth.Guard, placeholder) // User logout
group.POST("/logout", oauth.Guard, GinLogout) // User logout
// Logined User Settings
attachProfile(group, oauth) // User profile management