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)

View File

@ -3,13 +3,14 @@ package forgotPasswordHandler
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/cache"
"github.com/fossyy/filekeeper/view/client/email"
"github.com/fossyy/filekeeper/view/client/forgotPassword"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"net/http"
"sync"
"time"
@ -27,35 +28,6 @@ type ForgotPassword struct {
CreateTime time.Time
}
var ListForgotPassword map[string]*ForgotPassword
var UserForgotPassword = make(map[string]string)
func init() {
ListForgotPassword = make(map[string]*ForgotPassword)
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 [Forgot Password] [%s] initiated at %02d:%02d:%02d", cleanID, currentTime.Hour(), currentTime.Minute(), currentTime.Second()))
for _, data := range ListForgotPassword {
data.mu.Lock()
if currentTime.Sub(data.CreateTime) > time.Minute*10 {
delete(ListForgotPassword, data.User.Email)
delete(UserForgotPassword, data.Code)
cacheClean++
}
data.mu.Unlock()
}
app.Server.Logger.Info(fmt.Sprintf("Cache cleanup [Forgot Password] [%s] completed: %d entries removed. Finished at %s", cleanID, cacheClean, time.Since(currentTime)))
}
}()
}
func GET(w http.ResponseWriter, r *http.Request) {
component := forgotPasswordView.Main("Filekeeper - Forgot Password Page", types.Message{
Code: 3,
@ -79,7 +51,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
emailForm := r.Form.Get("email")
user, err := cache.GetUser(emailForm)
user, err := app.Server.Service.GetUser(r.Context(), emailForm)
if errors.Is(err, gorm.ErrRecordNotFound) {
component := forgotPasswordView.Main("Filekeeper - Forgot Password Page", types.Message{
Code: 0,
@ -119,31 +91,48 @@ func POST(w http.ResponseWriter, r *http.Request) {
}
func verifyForgot(user *models.User) error {
var userData *ForgotPassword
var code string
var err error
code, err = app.Server.Cache.GetCache(context.Background(), "ForgotPasswordCode:"+user.Email)
if err != nil {
if errors.Is(err, redis.Nil) {
code = utils.GenerateRandomString(64)
userData = &ForgotPassword{
User: user,
Code: code,
CreateTime: time.Now(),
}
var buffer bytes.Buffer
data, ok := ListForgotPassword[user.Email]
if !ok {
code = utils.GenerateRandomString(64)
newForgotUser, err := json.Marshal(userData)
if err != nil {
return err
}
err = app.Server.Cache.SetCache(context.Background(), "ForgotPasswordCode:"+user.Email, code, time.Minute*15)
if err != nil {
return err
}
err = app.Server.Cache.SetCache(context.Background(), "ForgotPassword:"+userData.Code, newForgotUser, time.Minute*15)
if err != nil {
return err
}
} else {
return err
}
} else {
code = data.Code
storedCode, err := app.Server.Cache.GetCache(context.Background(), "ForgotPassword:"+code)
err = json.Unmarshal([]byte(storedCode), &userData)
if err != nil {
return err
}
}
err := emailView.ForgotPassword(user.Username, fmt.Sprintf("https://%s/forgot-password/verify/%s", utils.Getenv("DOMAIN"), code)).Render(context.Background(), &buffer)
var buffer bytes.Buffer
err = emailView.ForgotPassword(user.Username, fmt.Sprintf("https://%s/forgot-password/verify/%s", utils.Getenv("DOMAIN"), code)).Render(context.Background(), &buffer)
if err != nil {
return err
}
userData := &ForgotPassword{
User: user,
Code: code,
CreateTime: time.Now(),
}
UserForgotPassword[code] = user.Email
ListForgotPassword[user.Email] = userData
err = app.Server.Mail.Send(user.Email, "Password Change Request", buffer.String())
if err != nil {
return err

View File

@ -1,14 +1,16 @@
package forgotPasswordVerifyHandler
import (
"encoding/json"
"errors"
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/cache"
forgotPasswordHandler "github.com/fossyy/filekeeper/handler/forgotPassword"
"github.com/fossyy/filekeeper/session"
"github.com/fossyy/filekeeper/types"
"github.com/fossyy/filekeeper/utils"
"github.com/fossyy/filekeeper/view/client/forgotPassword"
signupView "github.com/fossyy/filekeeper/view/client/signup"
"github.com/redis/go-redis/v9"
"net/http"
)
@ -21,11 +23,13 @@ func init() {
func GET(w http.ResponseWriter, r *http.Request) {
code := r.PathValue("code")
email := forgotPasswordHandler.UserForgotPassword[code]
_, ok := forgotPasswordHandler.ListForgotPassword[email]
if !ok {
w.WriteHeader(http.StatusNotFound)
_, err := app.Server.Cache.GetCache(r.Context(), "ForgotPassword:"+code)
if err != nil {
if errors.Is(err, redis.Nil) {
w.WriteHeader(http.StatusNotFound)
return
}
w.WriteHeader(http.StatusInternalServerError)
return
}
@ -33,7 +37,7 @@ func GET(w http.ResponseWriter, r *http.Request) {
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())
@ -44,15 +48,20 @@ func GET(w http.ResponseWriter, r *http.Request) {
func POST(w http.ResponseWriter, r *http.Request) {
code := r.PathValue("code")
email := forgotPasswordHandler.UserForgotPassword[code]
data, ok := forgotPasswordHandler.ListForgotPassword[email]
if !ok {
data, err := app.Server.Cache.GetCache(r.Context(), "ForgotPassword:"+code)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
var userData *forgotPasswordHandler.ForgotPassword
err := r.ParseForm()
err = json.Unmarshal([]byte(data), &userData)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
err = r.ParseForm()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
app.Server.Logger.Error(err.Error())
@ -82,19 +91,19 @@ func POST(w http.ResponseWriter, r *http.Request) {
return
}
err = app.Server.Database.UpdateUserPassword(data.User.Email, hashedPassword)
err = app.Server.Database.UpdateUserPassword(userData.User.Email, hashedPassword)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
app.Server.Logger.Error(err.Error())
return
}
delete(forgotPasswordHandler.ListForgotPassword, data.User.Email)
delete(forgotPasswordHandler.UserForgotPassword, data.Code)
app.Server.Cache.DeleteCache(r.Context(), "ForgotPasswordCode:"+userData.User.Email)
app.Server.Cache.DeleteCache(r.Context(), "ForgotPassword:"+code)
session.RemoveAllSessions(data.User.Email)
session.RemoveAllSessions(userData.User.Email)
cache.DeleteUser(data.User.Email)
app.Server.Service.DeleteUser(userData.User.Email)
component := forgotPasswordView.ChangeSuccess("Filekeeper - Forgot Password Page")
err = component.Render(r.Context(), w)

View File

@ -5,7 +5,6 @@ import (
"net/http"
"github.com/fossyy/filekeeper/session"
"github.com/fossyy/filekeeper/types"
"github.com/fossyy/filekeeper/utils"
)
@ -25,7 +24,7 @@ func GET(w http.ResponseWriter, r *http.Request) {
}
storeSession.Delete()
session.RemoveSessionInfo(storeSession.Values["user"].(types.User).Email, cookie.Value)
session.RemoveSessionInfo(storeSession.Values.Email, cookie.Value)
http.SetCookie(w, &http.Cookie{
Name: utils.Getenv("SESSION_NAME"),

View File

@ -4,7 +4,6 @@ import (
"errors"
"github.com/a-h/templ"
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/cache"
"github.com/fossyy/filekeeper/session"
"github.com/fossyy/filekeeper/types"
"github.com/fossyy/filekeeper/utils"
@ -37,8 +36,8 @@ func init() {
"login_required": "You need to log in again to proceed. Please try logging in again.",
"account_selection_required": "Please select an account to proceed with the request.",
"consent_required": "Consent is required to proceed. Please provide consent to continue.",
"csrf_token_error": "The CSRF token is missing or invalid. Please refresh the page and try again.",
}
}
func GET(w http.ResponseWriter, r *http.Request) {
@ -77,7 +76,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
}
email := r.Form.Get("email")
password := r.Form.Get("password")
userData, err := cache.GetUser(email)
userData, err := app.Server.Service.GetUser(r.Context(), email)
if err != nil {
component := signinView.Main("Filekeeper - Sign in Page", types.Message{
Code: 0,
@ -95,27 +94,33 @@ func POST(w http.ResponseWriter, r *http.Request) {
if email == userData.Email && utils.CheckPasswordHash(password, userData.Password) {
if userData.Totp != "" {
storeSession := session.Create()
storeSession.Values["user"] = types.User{
storeSession, err := session.Create(types.User{
UserID: userData.UserID,
Email: email,
Username: userData.Username,
Totp: userData.Totp,
Authenticated: false,
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
storeSession.Save(w)
http.Redirect(w, r, "/auth/totp", http.StatusSeeOther)
return
}
storeSession := session.Create()
storeSession.Values["user"] = types.User{
storeSession, err := session.Create(types.User{
UserID: userData.UserID,
Email: email,
Username: userData.Username,
Authenticated: true,
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
userAgent := r.Header.Get("User-Agent")
browserInfo, osInfo := ParseUserAgent(userAgent)

View File

@ -5,6 +5,7 @@ import (
"context"
"fmt"
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/utils"
"github.com/fossyy/filekeeper/view/client/email"
signupView "github.com/fossyy/filekeeper/view/client/signup"
"net/http"
@ -13,7 +14,6 @@ import (
"github.com/fossyy/filekeeper/types"
"github.com/fossyy/filekeeper/types/models"
"github.com/fossyy/filekeeper/utils"
"github.com/google/uuid"
)

View File

@ -4,7 +4,6 @@ import (
"encoding/json"
"errors"
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/cache"
"io"
"net/http"
"os"
@ -31,7 +30,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
return
}
fileData, err := cache.GetUserFile(fileInfo.Name, userSession.UserID.String())
fileData, err := app.Server.Service.GetUserFile(fileInfo.Name, userSession.UserID.String())
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
upload, err := handleNewUpload(userSession, fileInfo)

View File

@ -1,15 +1,8 @@
package uploadHandler
import (
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/cache"
"github.com/fossyy/filekeeper/types"
filesView "github.com/fossyy/filekeeper/view/client/upload"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
)
func GET(w http.ResponseWriter, r *http.Request) {
@ -21,73 +14,74 @@ func GET(w http.ResponseWriter, r *http.Request) {
}
func POST(w http.ResponseWriter, r *http.Request) {
fileID := r.PathValue("id")
if err := r.ParseMultipartForm(32 << 20); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
userSession := r.Context().Value("user").(types.User)
uploadDir := "uploads"
if _, err := os.Stat(uploadDir); os.IsNotExist(err) {
if err := os.Mkdir(uploadDir, os.ModePerm); err != nil {
app.Server.Logger.Error("error getting upload info: " + err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
}
file, err := cache.GetFile(fileID)
if err != nil {
app.Server.Logger.Error("error getting upload info: " + err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
currentDir, _ := os.Getwd()
basePath := filepath.Join(currentDir, uploadDir)
saveFolder := filepath.Join(basePath, userSession.UserID.String(), file.ID.String())
if filepath.Dir(saveFolder) != filepath.Join(basePath, userSession.UserID.String()) {
app.Server.Logger.Error("invalid path")
w.WriteHeader(http.StatusInternalServerError)
return
}
fileByte, fileHeader, err := r.FormFile("chunk")
if err != nil {
app.Server.Logger.Error("error getting upload info: " + err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
defer fileByte.Close()
rawIndex := r.FormValue("index")
index, err := strconv.Atoi(rawIndex)
if err != nil {
return
}
file.UpdateProgress(int64(index), file.UploadedByte+int64(fileHeader.Size))
dst, err := os.OpenFile(filepath.Join(saveFolder, file.Name), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
app.Server.Logger.Error("error making upload folder: " + err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
defer dst.Close()
if _, err := io.Copy(dst, fileByte); err != nil {
app.Server.Logger.Error("error copying byte to file dst: " + err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
if file.UploadedByte >= file.Size {
file.FinalizeFileUpload()
return
}
return
//fileID := r.PathValue("id")
//if err := r.ParseMultipartForm(32 << 20); err != nil {
// w.WriteHeader(http.StatusInternalServerError)
// return
//}
//
//userSession := r.Context().Value("user").(types.User)
//
//uploadDir := "uploads"
//if _, err := os.Stat(uploadDir); os.IsNotExist(err) {
// if err := os.Mkdir(uploadDir, os.ModePerm); err != nil {
// app.Server.Logger.Error("error getting upload info: " + err.Error())
// w.WriteHeader(http.StatusInternalServerError)
// return
// }
//}
//
//file, err := app.Server.Service.GetFile(fileID)
//if err != nil {
// app.Server.Logger.Error("error getting upload info: " + err.Error())
// w.WriteHeader(http.StatusInternalServerError)
// return
//}
//
//currentDir, _ := os.Getwd()
//basePath := filepath.Join(currentDir, uploadDir)
//saveFolder := filepath.Join(basePath, userSession.UserID.String(), file.ID.String())
//
//if filepath.Dir(saveFolder) != filepath.Join(basePath, userSession.UserID.String()) {
// app.Server.Logger.Error("invalid path")
// w.WriteHeader(http.StatusInternalServerError)
// return
//}
//
//fileByte, fileHeader, err := r.FormFile("chunk")
//if err != nil {
// app.Server.Logger.Error("error getting upload info: " + err.Error())
// w.WriteHeader(http.StatusInternalServerError)
// return
//}
//defer fileByte.Close()
//
//rawIndex := r.FormValue("index")
//index, err := strconv.Atoi(rawIndex)
//if err != nil {
// return
//}
//
//file.UpdateProgress(int64(index), file.UploadedByte+int64(fileHeader.Size))
//
//dst, err := os.OpenFile(filepath.Join(saveFolder, file.Name), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
//if err != nil {
// app.Server.Logger.Error("error making upload folder: " + err.Error())
// w.WriteHeader(http.StatusInternalServerError)
// return
//}
//
//defer dst.Close()
//if _, err := io.Copy(dst, fileByte); err != nil {
// app.Server.Logger.Error("error copying byte to file dst: " + err.Error())
// w.WriteHeader(http.StatusInternalServerError)
// return
//}
//
//if file.UploadedByte >= file.Size {
// file.FinalizeFileUpload()
// return
//}
//return
}

View File

@ -2,7 +2,6 @@ package userHandlerResetPassword
import (
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/cache"
"github.com/fossyy/filekeeper/session"
"github.com/fossyy/filekeeper/types"
"github.com/fossyy/filekeeper/utils"
@ -14,7 +13,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
userSession := r.Context().Value("user").(types.User)
currentPassword := r.Form.Get("currentPassword")
password := r.Form.Get("password")
user, err := cache.GetUser(userSession.Email)
user, err := app.Server.Service.GetUser(r.Context(), userSession.Email)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
@ -38,7 +37,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
}
session.RemoveAllSessions(userSession.Email)
cache.DeleteUser(userSession.Email)
app.Server.Service.DeleteUser(userSession.Email)
http.Redirect(w, r, "/signin", http.StatusSeeOther)
return

View File

@ -11,15 +11,21 @@ func DELETE(w http.ResponseWriter, r *http.Request) {
_, mySession, _ := session.GetSession(r)
otherSession, _ := session.Get(id)
if session.GetSessionInfo(mySession.Email, otherSession.ID) == nil {
if _, err := session.GetSessionInfo(mySession.Email, otherSession.ID); err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
otherSession.Delete()
session.RemoveSessionInfo(mySession.Email, otherSession.ID)
component := userView.SessionTable(session.GetSessions(mySession.Email))
sessions, err := session.GetSessions(mySession.Email)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
component := userView.SessionTable(sessions)
err := component.Render(r.Context(), w)
err = component.Render(r.Context(), w)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return

View File

@ -5,7 +5,6 @@ import (
"encoding/base64"
"fmt"
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/cache"
"github.com/fossyy/filekeeper/view/client/user/totp"
"image/png"
"net/http"
@ -75,7 +74,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
return
}
cache.DeleteUser(userSession.Email)
app.Server.Service.DeleteUser(userSession.Email)
component := userTotpSetupView.Main("Filekeeper - 2FA Setup Page", base64Str, secret, userSession, types.Message{
Code: 1,
Message: "Your TOTP setup is complete! Your account is now more secure.",

View File

@ -17,24 +17,28 @@ var errorMessages = map[string]string{
func GET(w http.ResponseWriter, r *http.Request) {
var component templ.Component
userSession := r.Context().Value("user").(types.User)
sessions, err := session.GetSessions(userSession.Email)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if err := r.URL.Query().Get("error"); err != "" {
message, ok := errorMessages[err]
if !ok {
message = "Unknown error occurred. Please contact support at bagas@fossy.my.id for assistance."
}
component = userView.Main("Filekeeper - User Page", userSession, session.GetSessions(userSession.Email), types.Message{
component = userView.Main("Filekeeper - User Page", userSession, sessions, types.Message{
Code: 0,
Message: message,
})
} else {
component = userView.Main("Filekeeper - User Page", userSession, session.GetSessions(userSession.Email), types.Message{
component = userView.Main("Filekeeper - User Page", userSession, sessions, types.Message{
Code: 1,
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())