Refactor session handling: Move session checking to session.go

This commit is contained in:
2024-05-01 12:37:00 +07:00
parent b3fdb17113
commit e8e5ce7bd5
8 changed files with 86 additions and 174 deletions

View File

@ -1,6 +1,8 @@
package session
import (
"errors"
"github.com/fossyy/filekeeper/types"
"net/http"
"strconv"
"sync"
@ -30,6 +32,14 @@ type SessionInfo struct {
AccessAt string
}
type UserStatus string
const (
Authorized UserStatus = "authorized"
Unauthorized UserStatus = "unauthorized"
InvalidSession UserStatus = "invalid_session"
)
type SessionInfoList map[string][]*SessionInfo
var GlobalSessionStore = SessionStore{Sessions: make(map[string]*Session)}
@ -125,3 +135,27 @@ func (sessionInfo *SessionInfo) UpdateAccessTime() {
formattedTime := currentTime.Format("01-02-2006")
sessionInfo.AccessAt = formattedTime
}
func GetSession(r *http.Request) (UserStatus, types.User) {
cookie, err := r.Cookie("Session")
if err != nil {
return Unauthorized, types.User{}
}
storeSession, err := GlobalSessionStore.Get(cookie.Value)
if err != nil {
if errors.Is(err, &SessionNotFoundError{}) {
return InvalidSession, types.User{}
}
return Unauthorized, types.User{}
}
val := storeSession.Values["user"]
var userSession = types.User{}
userSession, ok := val.(types.User)
if !ok {
return Unauthorized, types.User{}
}
return Authorized, userSession
}