Add Redis support for session and user management

This commit is contained in:
2024-09-08 00:03:43 +07:00
parent b9ac29d301
commit 2c5de2b336
26 changed files with 642 additions and 548 deletions

View File

@ -6,15 +6,14 @@ import (
"errors"
"fmt"
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/cache"
googleOauthSetupHandler "github.com/fossyy/filekeeper/handler/auth/google/setup"
signinHandler "github.com/fossyy/filekeeper/handler/signin"
"github.com/fossyy/filekeeper/session"
"github.com/fossyy/filekeeper/types"
"github.com/fossyy/filekeeper/utils"
"github.com/redis/go-redis/v9"
"net/http"
"net/url"
"sync"
"time"
)
@ -46,49 +45,22 @@ type OauthUser struct {
VerifiedEmail bool `json:"verified_email"`
}
type CsrfToken struct {
Token string
CreateTime time.Time
mu sync.Mutex
}
var CsrfTokens map[string]*CsrfToken
func init() {
CsrfTokens = make(map[string]*CsrfToken)
ticker := time.NewTicker(time.Minute)
go func() {
for {
<-ticker.C
currentTime := time.Now()
cacheClean := 0
cleanID := utils.GenerateRandomString(10)
app.Server.Logger.Info(fmt.Sprintf("Cache cleanup [csrf_token] [%s] initiated at %02d:%02d:%02d", cleanID, currentTime.Hour(), currentTime.Minute(), currentTime.Second()))
for _, data := range CsrfTokens {
data.mu.Lock()
if currentTime.Sub(data.CreateTime) > time.Minute*10 {
delete(CsrfTokens, data.Token)
cacheClean++
}
data.mu.Unlock()
}
app.Server.Logger.Info(fmt.Sprintf("Cache cleanup [csrf_token] [%s] completed: %d entries removed. Finished at %s", cleanID, cacheClean, time.Since(currentTime)))
}
}()
}
func GET(w http.ResponseWriter, r *http.Request) {
if _, ok := CsrfTokens[r.URL.Query().Get("state")]; !ok {
//csrf token mismatch error
_, err := app.Server.Cache.GetCache(r.Context(), "CsrfTokens:"+r.URL.Query().Get("state"))
if err != nil {
if errors.Is(err, redis.Nil) {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusInternalServerError)
return
}
delete(CsrfTokens, r.URL.Query().Get("state"))
err = app.Server.Cache.DeleteCache(r.Context(), "CsrfTokens:"+r.URL.Query().Get("state"))
if err != nil {
http.Redirect(w, r, fmt.Sprintf("/signin?error=%s", "csrf_token_error"), http.StatusFound)
return
}
if err := r.URL.Query().Get("error"); err != "" {
http.Redirect(w, r, fmt.Sprintf("/signin?error=%s", err), http.StatusFound)
@ -146,16 +118,23 @@ func GET(w http.ResponseWriter, r *http.Request) {
if !app.Server.Database.IsEmailRegistered(oauthUser.Email) {
code := utils.GenerateRandomString(64)
googleOauthSetupHandler.SetupUser[code] = &googleOauthSetupHandler.UnregisteredUser{
user := googleOauthSetupHandler.UnregisteredUser{
Code: code,
Email: oauthUser.Email,
CreateTime: time.Now(),
}
newGoogleSetupJSON, _ := json.Marshal(user)
err = app.Server.Cache.SetCache(r.Context(), "GoogleSetup:"+code, newGoogleSetupJSON, time.Minute*15)
if err != nil {
fmt.Println("Error setting up Google Setup:", err)
return
}
http.Redirect(w, r, fmt.Sprintf("/auth/google/setup/%s", code), http.StatusSeeOther)
return
}
user, err := cache.GetUser(oauthUser.Email)
user, err := app.Server.Service.GetUser(r.Context(), oauthUser.Email)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
@ -163,12 +142,15 @@ func GET(w http.ResponseWriter, r *http.Request) {
return
}
storeSession := session.Create()
storeSession.Values["user"] = types.User{
storeSession, err := session.Create(types.User{
UserID: user.UserID,
Email: oauthUser.Email,
Username: user.Username,
Authenticated: true,
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
userAgent := r.Header.Get("User-Agent")

View File

@ -1,17 +1,31 @@
package googleOauthHandler
import (
"encoding/json"
"fmt"
"github.com/fossyy/filekeeper/app"
googleOauthCallbackHandler "github.com/fossyy/filekeeper/handler/auth/google/callback"
"github.com/fossyy/filekeeper/utils"
"net/http"
"time"
)
type CsrfToken struct {
Token string
CreateTime time.Time
}
func GET(w http.ResponseWriter, r *http.Request) {
token, err := utils.GenerateCSRFToken()
googleOauthCallbackHandler.CsrfTokens[token] = &googleOauthCallbackHandler.CsrfToken{Token: token, CreateTime: time.Now()}
csrfToken := CsrfToken{
Token: token,
CreateTime: time.Now(),
}
newCsrfToken, err := json.Marshal(csrfToken)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
app.Server.Cache.SetCache(r.Context(), "CsrfTokens:"+token, newCsrfToken, time.Minute*15)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
app.Server.Logger.Error(err.Error())

View File

@ -1,7 +1,8 @@
package googleOauthSetupHandler
import (
"fmt"
"encoding/json"
"errors"
"github.com/fossyy/filekeeper/app"
signinHandler "github.com/fossyy/filekeeper/handler/signin"
"github.com/fossyy/filekeeper/session"
@ -11,8 +12,8 @@ import (
"github.com/fossyy/filekeeper/view/client/auth"
signupView "github.com/fossyy/filekeeper/view/client/signup"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"net/http"
"sync"
"time"
)
@ -20,50 +21,26 @@ type UnregisteredUser struct {
Code string
Email string
CreateTime time.Time
mu sync.Mutex
}
var SetupUser map[string]*UnregisteredUser
func init() {
SetupUser = make(map[string]*UnregisteredUser)
ticker := time.NewTicker(time.Minute)
go func() {
for {
<-ticker.C
currentTime := time.Now()
cacheClean := 0
cleanID := utils.GenerateRandomString(10)
app.Server.Logger.Info(fmt.Sprintf("Cache cleanup [GoogleSetup] [%s] initiated at %02d:%02d:%02d", cleanID, currentTime.Hour(), currentTime.Minute(), currentTime.Second()))
for _, data := range SetupUser {
data.mu.Lock()
if currentTime.Sub(data.CreateTime) > time.Minute*10 {
delete(SetupUser, data.Code)
cacheClean++
}
data.mu.Unlock()
}
app.Server.Logger.Info(fmt.Sprintf("Cache cleanup [GoogleSetup] [%s] completed: %d entries removed. Finished at %s", cleanID, cacheClean, time.Since(currentTime)))
}
}()
}
func GET(w http.ResponseWriter, r *http.Request) {
code := r.PathValue("code")
if _, ok := SetupUser[code]; !ok {
http.Redirect(w, r, "/signup", http.StatusSeeOther)
_, err := app.Server.Cache.GetCache(r.Context(), "GoogleSetup:"+code)
if err != nil {
if errors.Is(err, redis.Nil) {
http.Redirect(w, r, "/signup", http.StatusSeeOther)
return
}
w.WriteHeader(http.StatusInternalServerError)
app.Server.Logger.Error(err.Error())
return
}
component := authView.GoogleSetup("Filekeeper - Setup Page", types.Message{
Code: 3,
Message: "",
})
err := component.Render(r.Context(), w)
err = component.Render(r.Context(), w)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
app.Server.Logger.Error(err.Error())
@ -73,12 +50,22 @@ func GET(w http.ResponseWriter, r *http.Request) {
func POST(w http.ResponseWriter, r *http.Request) {
code := r.PathValue("code")
unregisteredUser, ok := SetupUser[code]
if !ok {
cache, err := app.Server.Cache.GetCache(r.Context(), "GoogleSetup:"+code)
if errors.Is(err, redis.Nil) {
http.Error(w, "Unauthorized Action", http.StatusUnauthorized)
return
}
err := r.ParseForm()
var unregisteredUser UnregisteredUser
err = json.Unmarshal([]byte(cache), &unregisteredUser)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
app.Server.Logger.Error(err.Error())
return
}
err = r.ParseForm()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
app.Server.Logger.Error(err.Error())
@ -126,14 +113,15 @@ func POST(w http.ResponseWriter, r *http.Request) {
return
}
delete(SetupUser, code)
storeSession := session.Create()
storeSession.Values["user"] = types.User{
storeSession, err := session.Create(types.User{
UserID: userID,
Email: unregisteredUser.Email,
Username: username,
Authenticated: true,
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
userAgent := r.Header.Get("User-Agent")

View File

@ -38,14 +38,18 @@ func POST(w http.ResponseWriter, r *http.Request) {
if totp.Verify(code, time.Now().Unix()) {
storeSession, err := session.Get(key)
if err != nil {
return
}
storeSession.Values["user"] = types.User{
err = storeSession.Change(types.User{
UserID: user.UserID,
Email: user.Email,
Username: user.Username,
Authenticated: true,
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if err != nil {
return
}
userAgent := r.Header.Get("User-Agent")
browserInfo, osInfo := ParseUserAgent(userAgent)