feat: create/update session when refreshing
This commit is contained in:
@ -3,10 +3,12 @@ package auth
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"gitea.local/admin/hspguard/internal/repository"
|
||||||
"gitea.local/admin/hspguard/internal/types"
|
"gitea.local/admin/hspguard/internal/types"
|
||||||
"gitea.local/admin/hspguard/internal/util"
|
"gitea.local/admin/hspguard/internal/util"
|
||||||
"gitea.local/admin/hspguard/internal/web"
|
"gitea.local/admin/hspguard/internal/web"
|
||||||
@ -64,6 +66,44 @@ func (h *AuthHandler) refreshToken(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
jti, err := uuid.Parse(userClaims.ID)
|
||||||
|
if session, err := h.repo.GetUserSessionByRefreshJTI(r.Context(), &jti); err != nil {
|
||||||
|
log.Printf("WARN: No existing user session found for user with '%s' email (jti: '%s'): %v\n", user.Email, userClaims.ID, err)
|
||||||
|
|
||||||
|
userAgent := r.UserAgent()
|
||||||
|
|
||||||
|
ipAddr := util.GetClientIP(r)
|
||||||
|
deviceInfo := util.BuildDeviceInfo(userAgent, ipAddr)
|
||||||
|
|
||||||
|
// Create User Session
|
||||||
|
session, err := h.repo.CreateUserSession(r.Context(), repository.CreateUserSessionParams{
|
||||||
|
UserID: user.ID,
|
||||||
|
SessionType: "user",
|
||||||
|
ExpiresAt: &refresh.ExpiresAt,
|
||||||
|
LastActive: nil,
|
||||||
|
IpAddress: &ipAddr,
|
||||||
|
UserAgent: &userAgent,
|
||||||
|
AccessTokenID: &access.ID,
|
||||||
|
RefreshTokenID: &refresh.ID,
|
||||||
|
DeviceInfo: deviceInfo,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("ERR: Failed to create user session after logging in: %v\n", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("INFO: User session created for '%s' with '%s' id\n", user.Email, session.ID.String())
|
||||||
|
} else {
|
||||||
|
err := h.repo.UpdateSessionTokens(r.Context(), repository.UpdateSessionTokensParams{
|
||||||
|
ID: session.ID,
|
||||||
|
AccessTokenID: &access.ID,
|
||||||
|
RefreshTokenID: &refresh.ID,
|
||||||
|
ExpiresAt: &refresh.ExpiresAt,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("ERR: Failed to update user session with '%s' id: %v\n", session.ID.String(), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type Response struct {
|
type Response struct {
|
||||||
AccessToken string `json:"access"`
|
AccessToken string `json:"access"`
|
||||||
RefreshToken string `json:"refresh"`
|
RefreshToken string `json:"refresh"`
|
||||||
|
Reference in New Issue
Block a user