Merge pull request #18 from fossyy/staging

Staging
This commit is contained in:
2024-05-05 15:53:29 +07:00
committed by GitHub
7 changed files with 53 additions and 40 deletions

2
cache/user.go vendored
View File

@ -26,7 +26,7 @@ func init() {
log = logger.Logger() log = logger.Logger()
userCache = make(map[string]*UserWithExpired) userCache = make(map[string]*UserWithExpired)
ticker := time.NewTicker(time.Hour) ticker := time.NewTicker(time.Minute)
go func() { go func() {
for { for {

View File

@ -167,7 +167,7 @@ func GET(w http.ResponseWriter, r *http.Request) {
log.Error(err.Error()) log.Error(err.Error())
return return
} }
storeSession := session.GlobalSessionStore.Create() storeSession := session.Create()
storeSession.Values["user"] = types.User{ storeSession.Values["user"] = types.User{
UserID: user.UserID, UserID: user.UserID,
Email: oauthUser.Email, Email: oauthUser.Email,

View File

@ -130,7 +130,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
delete(SetupUser, code) delete(SetupUser, code)
storeSession := session.GlobalSessionStore.Create() storeSession := session.Create()
storeSession.Values["user"] = types.User{ storeSession.Values["user"] = types.User{
UserID: userID, UserID: userID,
Email: unregisteredUser.Email, Email: unregisteredUser.Email,

View File

@ -4,25 +4,18 @@ import (
"errors" "errors"
"net/http" "net/http"
"github.com/fossyy/filekeeper/logger"
"github.com/fossyy/filekeeper/session" "github.com/fossyy/filekeeper/session"
"github.com/fossyy/filekeeper/types" "github.com/fossyy/filekeeper/types"
"github.com/fossyy/filekeeper/utils" "github.com/fossyy/filekeeper/utils"
) )
var log *logger.AggregatedLogger
func init() {
log = logger.Logger()
}
func GET(w http.ResponseWriter, r *http.Request) { func GET(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("Session") cookie, err := r.Cookie("Session")
if err != nil { if err != nil {
return return
} }
storeSession, err := session.GlobalSessionStore.Get(cookie.Value) storeSession, err := session.Get(cookie.Value)
if err != nil { if err != nil {
if errors.Is(err, &session.SessionNotFoundError{}) { if errors.Is(err, &session.SessionNotFoundError{}) {
storeSession.Destroy(w) storeSession.Destroy(w)
@ -31,7 +24,7 @@ func GET(w http.ResponseWriter, r *http.Request) {
return return
} }
session.GlobalSessionStore.Delete(cookie.Value) storeSession.Delete()
session.RemoveSessionInfo(storeSession.Values["user"].(types.User).Email, cookie.Value) session.RemoveSessionInfo(storeSession.Values["user"].(types.User).Email, cookie.Value)
http.SetCookie(w, &http.Cookie{ http.SetCookie(w, &http.Cookie{

View File

@ -58,7 +58,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
} }
if email == userData.Email && utils.CheckPasswordHash(password, userData.Password) { if email == userData.Email && utils.CheckPasswordHash(password, userData.Password) {
storeSession := session.GlobalSessionStore.Create() storeSession := session.Create()
storeSession.Values["user"] = types.User{ storeSession.Values["user"] = types.User{
UserID: userData.UserID, UserID: userData.UserID,
Email: email, Email: email,

View File

@ -50,7 +50,7 @@ func init() {
for _, data := range VerifyUser { for _, data := range VerifyUser {
data.mu.Lock() data.mu.Lock()
if currentTime.Sub(data.CreateTime) > time.Minute*1 { if currentTime.Sub(data.CreateTime) > time.Minute*10 {
delete(VerifyUser, data.Code) delete(VerifyUser, data.Code)
delete(VerifyEmail, data.User.Email) delete(VerifyEmail, data.User.Email)
cacheClean++ cacheClean++

View File

@ -1,7 +1,8 @@
package session package session
import ( import (
"errors" "fmt"
"github.com/fossyy/filekeeper/logger"
"github.com/fossyy/filekeeper/types" "github.com/fossyy/filekeeper/types"
"net/http" "net/http"
"strconv" "strconv"
@ -12,13 +13,10 @@ import (
) )
type Session struct { type Session struct {
ID string ID string
Values map[string]interface{} Values map[string]interface{}
} CreateTime time.Time
mu sync.Mutex
type SessionStore struct {
Sessions map[string]*Session
mu sync.Mutex
} }
type SessionInfo struct { type SessionInfo struct {
@ -33,6 +31,7 @@ type SessionInfo struct {
} }
type UserStatus string type UserStatus string
type SessionNotFoundError struct{}
const ( const (
Authorized UserStatus = "authorized" Authorized UserStatus = "authorized"
@ -40,38 +39,62 @@ const (
InvalidSession UserStatus = "invalid_session" InvalidSession UserStatus = "invalid_session"
) )
var GlobalSessionStore = SessionStore{Sessions: make(map[string]*Session)} var GlobalSessionStore = make(map[string]*Session)
var UserSessionInfoList = make(map[string]map[string]*SessionInfo) var UserSessionInfoList = make(map[string]map[string]*SessionInfo)
var log *logger.AggregatedLogger
type SessionNotFoundError struct{} func init() {
log = logger.Logger()
ticker := time.NewTicker(time.Minute)
go func() {
for {
<-ticker.C
currentTime := time.Now()
cacheClean := 0
cleanID := utils.GenerateRandomString(10)
log.Info(fmt.Sprintf("Cache cleanup [Session] [%s] initiated at %02d:%02d:%02d", cleanID, currentTime.Hour(), currentTime.Minute(), currentTime.Second()))
for _, data := range GlobalSessionStore {
data.mu.Lock()
if currentTime.Sub(data.CreateTime) > time.Hour*24*7 {
RemoveSessionInfo(data.Values["user"].(types.User).Email, data.ID)
delete(GlobalSessionStore, data.ID)
cacheClean++
}
data.mu.Unlock()
}
log.Info(fmt.Sprintf("Cache cleanup [Session] [%s] completed: %d entries removed. Finished at %s", cleanID, cacheClean, time.Since(currentTime)))
}
}()
}
func (e *SessionNotFoundError) Error() string { func (e *SessionNotFoundError) Error() string {
return "session not found" return "session not found"
} }
func (s *SessionStore) Get(id string) (*Session, error) { func Get(id string) (*Session, error) {
s.mu.Lock() if session, ok := GlobalSessionStore[id]; ok {
defer s.mu.Unlock()
if session, ok := s.Sessions[id]; ok {
return session, nil return session, nil
} }
return nil, &SessionNotFoundError{} return nil, &SessionNotFoundError{}
} }
func (s *SessionStore) Create() *Session { func Create() *Session {
id := utils.GenerateRandomString(128) id := utils.GenerateRandomString(128)
session := &Session{ session := &Session{
ID: id, ID: id,
Values: make(map[string]interface{}), Values: make(map[string]interface{}),
} }
s.Sessions[id] = session GlobalSessionStore[id] = session
return session return session
} }
func (s *SessionStore) Delete(id string) { func (s *Session) Delete() {
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
delete(s.Sessions, id) delete(GlobalSessionStore, s.ID)
} }
func (s *Session) Save(w http.ResponseWriter) { func (s *Session) Save(w http.ResponseWriter) {
@ -114,7 +137,7 @@ func RemoveSessionInfo(email string, id string) {
func RemoveAllSessions(email string) { func RemoveAllSessions(email string) {
sessionInfos := UserSessionInfoList[email] sessionInfos := UserSessionInfoList[email]
for _, sessionInfo := range sessionInfos { for _, sessionInfo := range sessionInfos {
delete(GlobalSessionStore.Sessions, sessionInfo.SessionID) delete(GlobalSessionStore, sessionInfo.SessionID)
} }
delete(UserSessionInfoList, email) delete(UserSessionInfoList, email)
} }
@ -140,17 +163,14 @@ func GetSession(r *http.Request) (UserStatus, types.User, string) {
return Unauthorized, types.User{}, "" return Unauthorized, types.User{}, ""
} }
storeSession, err := GlobalSessionStore.Get(cookie.Value) storeSession, ok := GlobalSessionStore[cookie.Value]
if err != nil { if !ok {
if errors.Is(err, &SessionNotFoundError{}) { return InvalidSession, types.User{}, ""
return InvalidSession, types.User{}, ""
}
return Unauthorized, types.User{}, ""
} }
val := storeSession.Values["user"] val := storeSession.Values["user"]
var userSession = types.User{} var userSession = types.User{}
userSession, ok := val.(types.User) userSession, ok = val.(types.User)
if !ok { if !ok {
return Unauthorized, types.User{}, "" return Unauthorized, types.User{}, ""
} }