Finalize 2FA implementation

This commit is contained in:
2024-06-20 08:49:49 +07:00
parent 0e16d59df9
commit c5185d5107
8 changed files with 87 additions and 77 deletions

50
cache/cache.go vendored
View File

@ -44,6 +44,27 @@ func init() {
fileCache = make(map[string]*FileWithExpired) fileCache = make(map[string]*FileWithExpired)
ticker := time.NewTicker(time.Minute) 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 [user] [%s] initiated at %02d:%02d:%02d", cleanID, currentTime.Hour(), currentTime.Minute(), currentTime.Second()))
for _, user := range userCache {
user.mu.Lock()
if currentTime.Sub(user.AccessAt) > time.Hour*8 {
delete(userCache, user.Email)
cacheClean++
}
user.mu.Unlock()
}
log.Info(fmt.Sprintf("Cache cleanup [user] [%s] completed: %d entries removed. Finished at %s", cleanID, cacheClean, time.Since(currentTime)))
}
}()
go func() { go func() {
for { for {
<-ticker.C <-ticker.C
@ -68,6 +89,35 @@ func init() {
}() }()
} }
func GetUser(email string) (*UserWithExpired, error) {
if user, ok := userCache[email]; ok {
return user, nil
}
userData, err := db.DB.GetUser(email)
if err != nil {
return nil, err
}
userCache[email] = &UserWithExpired{
UserID: userData.UserID,
Username: userData.Username,
Email: userData.Email,
Password: userData.Password,
Totp: userData.Totp,
AccessAt: time.Now(),
}
return userCache[email], nil
}
func DeleteUser(email string) {
userCache[email].mu.Lock()
defer userCache[email].mu.Unlock()
delete(userCache, email)
}
func GetFile(id string) (*FileWithExpired, error) { func GetFile(id string) (*FileWithExpired, error) {
if file, ok := fileCache[id]; ok { if file, ok := fileCache[id]; ok {
file.AccessAt = time.Now() file.AccessAt = time.Now()

View File

@ -5,6 +5,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"github.com/fossyy/filekeeper/cache"
"github.com/fossyy/filekeeper/db" "github.com/fossyy/filekeeper/db"
googleOauthSetupHandler "github.com/fossyy/filekeeper/handler/auth/google/setup" googleOauthSetupHandler "github.com/fossyy/filekeeper/handler/auth/google/setup"
signinHandler "github.com/fossyy/filekeeper/handler/signin" signinHandler "github.com/fossyy/filekeeper/handler/signin"
@ -156,7 +157,7 @@ func GET(w http.ResponseWriter, r *http.Request) {
return return
} }
user, err := db.DB.GetUser(oauthUser.Email) user, err := cache.GetUser(oauthUser.Email)
if err != nil { if err != nil {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)

View File

@ -3,61 +3,19 @@ package totpHandler
import ( import (
"errors" "errors"
"fmt" "fmt"
"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"
totpView "github.com/fossyy/filekeeper/view/totp" totpView "github.com/fossyy/filekeeper/view/totp"
"github.com/google/uuid"
"github.com/xlzd/gotp" "github.com/xlzd/gotp"
"net/http" "net/http"
"strings" "strings"
"sync"
"time" "time"
) )
type TotpInfo struct {
ID string
UserID uuid.UUID
Secret string
Email string
Username string
CreateTime time.Time
mu sync.Mutex
}
var TotpInfoList = make(map[string]*TotpInfo)
var log *logger.AggregatedLogger
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 [TOTP] [%s] initiated at %02d:%02d:%02d", cleanID, currentTime.Hour(), currentTime.Minute(), currentTime.Second()))
for _, data := range TotpInfoList {
data.mu.Lock()
if currentTime.Sub(data.CreateTime) > time.Minute*10 {
delete(TotpInfoList, data.ID)
cacheClean++
}
data.mu.Unlock()
}
log.Info(fmt.Sprintf("Cache cleanup [TOTP] [%s] completed: %d entries removed. Finished at %s", cleanID, cacheClean, time.Since(currentTime)))
}
}()
}
func GET(w http.ResponseWriter, r *http.Request) { func GET(w http.ResponseWriter, r *http.Request) {
_, ok := TotpInfoList[r.PathValue("id")] _, user, _ := session.GetSession(r)
if !ok { if user.Authenticated || user.Totp == "" {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
return return
} }
@ -73,20 +31,18 @@ func GET(w http.ResponseWriter, r *http.Request) {
func POST(w http.ResponseWriter, r *http.Request) { func POST(w http.ResponseWriter, r *http.Request) {
r.ParseForm() r.ParseForm()
code := r.Form.Get("code") code := r.Form.Get("code")
data, ok := TotpInfoList[r.PathValue("id")] _, user, key := session.GetSession(r)
if !ok { totp := gotp.NewDefaultTOTP(user.Totp)
w.WriteHeader(http.StatusNotFound)
return
}
fmt.Println(data)
totp := gotp.NewDefaultTOTP(data.Secret)
if totp.Verify(code, time.Now().Unix()) { if totp.Verify(code, time.Now().Unix()) {
storeSession := session.Create() storeSession, err := session.Get(key)
if err != nil {
return
}
storeSession.Values["user"] = types.User{ storeSession.Values["user"] = types.User{
UserID: data.UserID, UserID: user.UserID,
Email: data.Email, Email: user.Email,
Username: data.Username, Username: user.Username,
Totp: "",
Authenticated: true, Authenticated: true,
} }
userAgent := r.Header.Get("User-Agent") userAgent := r.Header.Get("User-Agent")
@ -103,7 +59,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
} }
storeSession.Save(w) storeSession.Save(w)
session.AddSessionInfo(data.Email, &sessionInfo) session.AddSessionInfo(user.Email, &sessionInfo)
cookie, err := r.Cookie("redirect") cookie, err := r.Cookie("redirect")
if errors.Is(err, http.ErrNoCookie) { if errors.Is(err, http.ErrNoCookie) {

View File

@ -5,7 +5,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"github.com/fossyy/filekeeper/db" "github.com/fossyy/filekeeper/cache"
"github.com/google/uuid" "github.com/google/uuid"
"net/http" "net/http"
"strconv" "strconv"
@ -87,7 +87,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
emailForm := r.Form.Get("email") emailForm := r.Form.Get("email")
user, err := db.DB.GetUser(emailForm) user, err := cache.GetUser(emailForm)
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
component := forgotPasswordView.Main("Filekeeper - Forgot Password Page", types.Message{ component := forgotPasswordView.Main("Filekeeper - Forgot Password Page", types.Message{
Code: 0, Code: 0,

View File

@ -1,6 +1,7 @@
package forgotPasswordVerifyHandler package forgotPasswordVerifyHandler
import ( import (
"github.com/fossyy/filekeeper/cache"
"github.com/fossyy/filekeeper/db" "github.com/fossyy/filekeeper/db"
forgotPasswordHandler "github.com/fossyy/filekeeper/handler/forgotPassword" forgotPasswordHandler "github.com/fossyy/filekeeper/handler/forgotPassword"
"github.com/fossyy/filekeeper/logger" "github.com/fossyy/filekeeper/logger"
@ -97,6 +98,8 @@ func POST(w http.ResponseWriter, r *http.Request) {
session.RemoveAllSessions(data.User.Email) session.RemoveAllSessions(data.User.Email)
cache.DeleteUser(data.User.Email)
component := forgotPasswordView.ChangeSuccess("Filekeeper - Forgot Password Page") component := forgotPasswordView.ChangeSuccess("Filekeeper - Forgot Password Page")
err = component.Render(r.Context(), w) err = component.Render(r.Context(), w)
if err != nil { if err != nil {

View File

@ -3,17 +3,14 @@ package signinHandler
import ( import (
"errors" "errors"
"github.com/a-h/templ" "github.com/a-h/templ"
"github.com/fossyy/filekeeper/db" "github.com/fossyy/filekeeper/cache"
totpHandler "github.com/fossyy/filekeeper/handler/auth/totp"
"net/http"
"strings"
"time"
"github.com/fossyy/filekeeper/logger" "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"
signinView "github.com/fossyy/filekeeper/view/signin" signinView "github.com/fossyy/filekeeper/view/signin"
"net/http"
"strings"
) )
var log *logger.AggregatedLogger var log *logger.AggregatedLogger
@ -81,7 +78,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
} }
email := r.Form.Get("email") email := r.Form.Get("email")
password := r.Form.Get("password") password := r.Form.Get("password")
userData, err := db.DB.GetUser(email) userData, err := cache.GetUser(email)
if err != nil { if err != nil {
component := signinView.Main("Filekeeper - Sign in Page", types.Message{ component := signinView.Main("Filekeeper - Sign in Page", types.Message{
Code: 0, Code: 0,
@ -99,16 +96,16 @@ 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) {
if userData.Totp != "" { if userData.Totp != "" {
id := utils.GenerateRandomString(32) storeSession := session.Create()
totpHandler.TotpInfoList[id] = &totpHandler.TotpInfo{ storeSession.Values["user"] = types.User{
ID: id, UserID: userData.UserID,
UserID: userData.UserID, Email: email,
Secret: userData.Totp, Username: userData.Username,
Email: userData.Email, Totp: userData.Totp,
Username: userData.Username, Authenticated: false,
CreateTime: time.Now(),
} }
http.Redirect(w, r, "/auth/totp/"+id, http.StatusSeeOther) storeSession.Save(w)
http.Redirect(w, r, "/auth/totp", http.StatusSeeOther)
return return
} }

View File

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"github.com/fossyy/filekeeper/cache"
userTotpSetupView "github.com/fossyy/filekeeper/view/user/totp" userTotpSetupView "github.com/fossyy/filekeeper/view/user/totp"
"image/png" "image/png"
"net/http" "net/http"
@ -63,7 +64,9 @@ func POST(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
return return
} }
cache.DeleteUser(userSession.Email)
fmt.Fprint(w, "Authentication successful! Access granted.") fmt.Fprint(w, "Authentication successful! Access granted.")
return
} else { } else {
uri := totp.ProvisioningUri(userSession.Email, "filekeeper") uri := totp.ProvisioningUri(userSession.Email, "filekeeper")

View File

@ -50,7 +50,7 @@ func SetupRoutes() *http.ServeMux {
} }
}) })
authRouter.HandleFunc("/totp/{id}", func(w http.ResponseWriter, r *http.Request) { authRouter.HandleFunc("/totp", func(w http.ResponseWriter, r *http.Request) {
switch r.Method { switch r.Method {
case http.MethodGet: case http.MethodGet:
middleware.Guest(totpHandler.GET, w, r) middleware.Guest(totpHandler.GET, w, r)