refactor: call database functions from app.Server.Database instead of directly from db

This commit is contained in:
2024-08-19 21:00:46 +07:00
parent 6a183f2c4e
commit fa2f4e8a87
18 changed files with 69 additions and 63 deletions

View File

@ -4,7 +4,7 @@ tmp_dir = "tmp"
[build] [build]
args_bin = [] args_bin = []
bin = "tmp\\main.exe" bin = "tmp\\main.exe --log true"
cmd = "go build -o ./tmp/main.exe ." cmd = "go build -o ./tmp/main.exe ."
delay = 1000 delay = 1000
exclude_dir = ["assets", "tmp", "vendor", "testdata", "uploads"] exclude_dir = ["assets", "tmp", "vendor", "testdata", "uploads"]

View File

@ -12,7 +12,7 @@ var Admin App
type App struct { type App struct {
http.Server http.Server
DB *db.Database Database db.Database
Logger *logger.AggregatedLogger Logger *logger.AggregatedLogger
Mail *email.SmtpServer Mail *email.SmtpServer
} }
@ -24,7 +24,7 @@ func NewClientServer(addr string, handler http.Handler, logger logger.Aggregated
Handler: handler, Handler: handler,
}, },
Logger: &logger, Logger: &logger,
DB: &database, Database: database,
Mail: &mail, Mail: &mail,
} }
} }
@ -37,7 +37,7 @@ func NewAdminServer(addr string, handler http.Handler, database db.Database) App
}, },
// TODO: Remove the dummy struct // TODO: Remove the dummy struct
Logger: &logger.AggregatedLogger{}, Logger: &logger.AggregatedLogger{},
DB: &database, Database: database,
Mail: &email.SmtpServer{}, Mail: &email.SmtpServer{},
} }
} }

17
cache/cache.go vendored
View File

@ -3,7 +3,6 @@ package cache
import ( import (
"fmt" "fmt"
"github.com/fossyy/filekeeper/app" "github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/db"
"github.com/fossyy/filekeeper/utils" "github.com/fossyy/filekeeper/utils"
"github.com/google/uuid" "github.com/google/uuid"
"sync" "sync"
@ -74,8 +73,8 @@ func init() {
for _, file := range fileCache { for _, file := range fileCache {
file.mu.Lock() file.mu.Lock()
if currentTime.Sub(file.AccessAt) > time.Minute*1 { if currentTime.Sub(file.AccessAt) > time.Minute*1 {
db.DB.UpdateUploadedByte(file.UploadedByte, file.ID.String()) app.Server.Database.UpdateUploadedByte(file.UploadedByte, file.ID.String())
db.DB.UpdateUploadedChunk(file.UploadedChunk, file.ID.String()) app.Server.Database.UpdateUploadedChunk(file.UploadedChunk, file.ID.String())
delete(fileCache, file.ID.String()) delete(fileCache, file.ID.String())
cacheClean++ cacheClean++
} }
@ -92,7 +91,7 @@ func GetUser(email string) (*UserWithExpired, error) {
return user, nil return user, nil
} }
userData, err := db.DB.GetUser(email) userData, err := app.Server.Database.GetUser(email)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -122,7 +121,7 @@ func GetFile(id string) (*FileWithExpired, error) {
return file, nil return file, nil
} }
uploadData, err := db.DB.GetFile(id) uploadData, err := app.Server.Database.GetFile(id)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -149,7 +148,7 @@ func (file *FileWithExpired) UpdateProgress(index int64, size int64) {
} }
func GetUserFile(name, ownerID string) (*FileWithExpired, error) { func GetUserFile(name, ownerID string) (*FileWithExpired, error) {
fileData, err := db.DB.GetUserFile(name, ownerID) fileData, err := app.Server.Database.GetUserFile(name, ownerID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -163,9 +162,9 @@ func GetUserFile(name, ownerID string) (*FileWithExpired, error) {
} }
func (file *FileWithExpired) FinalizeFileUpload() { func (file *FileWithExpired) FinalizeFileUpload() {
db.DB.UpdateUploadedByte(file.UploadedByte, file.ID.String()) app.Server.Database.UpdateUploadedByte(file.UploadedByte, file.ID.String())
db.DB.UpdateUploadedChunk(file.UploadedChunk, file.ID.String()) app.Server.Database.UpdateUploadedChunk(file.UploadedChunk, file.ID.String())
db.DB.FinalizeFileUpload(file.ID.String()) app.Server.Database.FinalizeFileUpload(file.ID.String())
delete(fileCache, file.ID.String()) delete(fileCache, file.ID.String())
return return
} }

View File

@ -12,8 +12,6 @@ import (
"strings" "strings"
) )
var DB Database
type mySQLdb struct { type mySQLdb struct {
*gorm.DB *gorm.DB
} }

View File

@ -7,7 +7,6 @@ import (
"fmt" "fmt"
"github.com/fossyy/filekeeper/app" "github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/cache" "github.com/fossyy/filekeeper/cache"
"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"
"github.com/fossyy/filekeeper/session" "github.com/fossyy/filekeeper/session"
@ -145,7 +144,7 @@ func GET(w http.ResponseWriter, r *http.Request) {
return return
} }
if !db.DB.IsEmailRegistered(oauthUser.Email) { if !app.Server.Database.IsEmailRegistered(oauthUser.Email) {
code := utils.GenerateRandomString(64) code := utils.GenerateRandomString(64)
googleOauthSetupHandler.SetupUser[code] = &googleOauthSetupHandler.UnregisteredUser{ googleOauthSetupHandler.SetupUser[code] = &googleOauthSetupHandler.UnregisteredUser{
Code: code, Code: code,

View File

@ -3,7 +3,6 @@ package googleOauthSetupHandler
import ( import (
"fmt" "fmt"
"github.com/fossyy/filekeeper/app" "github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/db"
signinHandler "github.com/fossyy/filekeeper/handler/signin" signinHandler "github.com/fossyy/filekeeper/handler/signin"
"github.com/fossyy/filekeeper/session" "github.com/fossyy/filekeeper/session"
"github.com/fossyy/filekeeper/types" "github.com/fossyy/filekeeper/types"
@ -112,7 +111,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
Password: hashedPassword, Password: hashedPassword,
} }
err = db.DB.CreateUser(&newUser) err = app.Server.Database.CreateUser(&newUser)
if err != nil { if err != nil {
component := signupView.Main("Filekeeper - Sign up Page", types.Message{ component := signupView.Main("Filekeeper - Sign up Page", types.Message{
Code: 0, Code: 0,

View File

@ -5,14 +5,13 @@ import (
"github.com/fossyy/filekeeper/view/client/download" "github.com/fossyy/filekeeper/view/client/download"
"net/http" "net/http"
"github.com/fossyy/filekeeper/db"
"github.com/fossyy/filekeeper/types" "github.com/fossyy/filekeeper/types"
"github.com/fossyy/filekeeper/utils" "github.com/fossyy/filekeeper/utils"
) )
func GET(w http.ResponseWriter, r *http.Request) { func GET(w http.ResponseWriter, r *http.Request) {
userSession := r.Context().Value("user").(types.User) userSession := r.Context().Value("user").(types.User)
files, err := db.DB.GetFiles(userSession.UserID.String()) files, err := app.Server.Database.GetFiles(userSession.UserID.String())
if err != nil { if err != nil {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
return return

View File

@ -5,13 +5,11 @@ import (
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
"github.com/fossyy/filekeeper/db"
) )
func GET(w http.ResponseWriter, r *http.Request) { func GET(w http.ResponseWriter, r *http.Request) {
fileID := r.PathValue("id") fileID := r.PathValue("id")
file, err := db.DB.GetFile(fileID) file, err := app.Server.Database.GetFile(fileID)
if err != nil { if err != nil {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
app.Server.Logger.Error(err.Error()) app.Server.Logger.Error(err.Error())

View File

@ -3,7 +3,6 @@ package forgotPasswordVerifyHandler
import ( import (
"github.com/fossyy/filekeeper/app" "github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/cache" "github.com/fossyy/filekeeper/cache"
"github.com/fossyy/filekeeper/db"
forgotPasswordHandler "github.com/fossyy/filekeeper/handler/forgotPassword" forgotPasswordHandler "github.com/fossyy/filekeeper/handler/forgotPassword"
"github.com/fossyy/filekeeper/session" "github.com/fossyy/filekeeper/session"
"github.com/fossyy/filekeeper/types" "github.com/fossyy/filekeeper/types"
@ -83,7 +82,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
return return
} }
err = db.DB.UpdateUserPassword(data.User.Email, hashedPassword) err = app.Server.Database.UpdateUserPassword(data.User.Email, hashedPassword)
if err != nil { if err != nil {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
app.Server.Logger.Error(err.Error()) app.Server.Logger.Error(err.Error())

View File

@ -11,7 +11,6 @@ import (
"sync" "sync"
"time" "time"
"github.com/fossyy/filekeeper/db"
"github.com/fossyy/filekeeper/types" "github.com/fossyy/filekeeper/types"
"github.com/fossyy/filekeeper/types/models" "github.com/fossyy/filekeeper/types/models"
"github.com/fossyy/filekeeper/utils" "github.com/fossyy/filekeeper/utils"
@ -102,7 +101,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
Password: hashedPassword, Password: hashedPassword,
} }
if registered := db.DB.IsUserRegistered(userEmail, username); registered { if registered := app.Server.Database.IsUserRegistered(userEmail, username); registered {
component := signupView.Main("Filekeeper - Sign up Page", types.Message{ component := signupView.Main("Filekeeper - Sign up Page", types.Message{
Code: 0, Code: 0,
Message: "Email or Username has been registered", Message: "Email or Username has been registered",

View File

@ -5,7 +5,6 @@ import (
signupView "github.com/fossyy/filekeeper/view/client/signup" signupView "github.com/fossyy/filekeeper/view/client/signup"
"net/http" "net/http"
"github.com/fossyy/filekeeper/db"
signupHandler "github.com/fossyy/filekeeper/handler/signup" signupHandler "github.com/fossyy/filekeeper/handler/signup"
"github.com/fossyy/filekeeper/types" "github.com/fossyy/filekeeper/types"
) )
@ -19,7 +18,7 @@ func GET(w http.ResponseWriter, r *http.Request) {
return return
} }
err := db.DB.CreateUser(data.User) err := app.Server.Database.CreateUser(data.User)
if err != nil { if err != nil {
component := signupView.Main("Filekeeper - Sign up Page", types.Message{ component := signupView.Main("Filekeeper - Sign up Page", types.Message{
Code: 0, Code: 0,

View File

@ -10,7 +10,6 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"github.com/fossyy/filekeeper/db"
"github.com/fossyy/filekeeper/types" "github.com/fossyy/filekeeper/types"
"github.com/fossyy/filekeeper/types/models" "github.com/fossyy/filekeeper/types/models"
"github.com/google/uuid" "github.com/google/uuid"
@ -93,7 +92,7 @@ func handleNewUpload(user types.User, file types.FileInfo) (models.File, error)
Done: false, Done: false,
} }
err = db.DB.CreateFile(&newFile) err = app.Server.Database.CreateFile(&newFile)
if err != nil { if err != nil {
app.Server.Logger.Error(err.Error()) app.Server.Logger.Error(err.Error())
return models.File{}, err return models.File{}, err

View File

@ -1,8 +1,8 @@
package userHandlerResetPassword package userHandlerResetPassword
import ( import (
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/cache" "github.com/fossyy/filekeeper/cache"
"github.com/fossyy/filekeeper/db"
"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"
@ -31,7 +31,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
return return
} }
err = db.DB.UpdateUserPassword(user.Email, hashPassword) err = app.Server.Database.UpdateUserPassword(user.Email, hashPassword)
if err != nil { if err != nil {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
return return

View File

@ -4,13 +4,13 @@ import (
"bytes" "bytes"
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/cache" "github.com/fossyy/filekeeper/cache"
"github.com/fossyy/filekeeper/view/client/user/totp" "github.com/fossyy/filekeeper/view/client/user/totp"
"image/png" "image/png"
"net/http" "net/http"
"time" "time"
"github.com/fossyy/filekeeper/db"
"github.com/fossyy/filekeeper/types" "github.com/fossyy/filekeeper/types"
"github.com/skip2/go-qrcode" "github.com/skip2/go-qrcode"
"github.com/xlzd/gotp" "github.com/xlzd/gotp"
@ -71,7 +71,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
return return
} }
if totp.Verify(code, time.Now().Unix()) { if totp.Verify(code, time.Now().Unix()) {
if err := db.DB.InitializeTotp(userSession.Email, secret); err != nil { if err := app.Server.Database.InitializeTotp(userSession.Email, secret); err != nil {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
return return
} }

View File

@ -1,6 +1,7 @@
package logger package logger
import ( import (
"flag"
"fmt" "fmt"
"io" "io"
"log" "log"
@ -8,6 +9,9 @@ import (
"time" "time"
) )
var logFlag *bool
var infoLoggerWriter io.Writer
type AggregatedLogger struct { type AggregatedLogger struct {
infoLogger *log.Logger infoLogger *log.Logger
warnLogger *log.Logger warnLogger *log.Logger
@ -16,6 +20,9 @@ type AggregatedLogger struct {
} }
func init() { func init() {
logFlag = flag.Bool("log", false, "Enable logging")
flag.Parse()
if _, err := os.Stat("log"); os.IsNotExist(err) { if _, err := os.Stat("log"); os.IsNotExist(err) {
os.Mkdir("log", os.ModePerm) os.Mkdir("log", os.ModePerm)
} }
@ -25,15 +32,23 @@ func Logger() *AggregatedLogger {
currentTime := time.Now() currentTime := time.Now()
formattedTime := currentTime.Format("2006-01-02-15-04") formattedTime := currentTime.Format("2006-01-02-15-04")
file, err := os.OpenFile(fmt.Sprintf("log/log-%s.log", formattedTime), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) file, err := os.OpenFile(fmt.Sprintf("log/log-%s.log", formattedTime), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
multiLogger := io.MultiWriter(os.Stdout, file)
if err != nil { if err != nil {
return &AggregatedLogger{} return &AggregatedLogger{}
} }
flag := log.Ldate | log.Ltime
multiLogger := io.MultiWriter(os.Stdout, file) if *logFlag {
infoLogger := log.New(file, "INFO: ", flag) infoLoggerWriter = multiLogger
warnLogger := log.New(multiLogger, "WARN: ", flag) } else {
errorLogger := log.New(multiLogger, "ERROR: ", flag) infoLoggerWriter = file
panicLogger := log.New(multiLogger, "PANIC: ", flag) }
slug := log.Ldate | log.Ltime
infoLogger := log.New(infoLoggerWriter, "INFO: ", slug)
warnLogger := log.New(multiLogger, "WARN: ", slug)
errorLogger := log.New(multiLogger, "ERROR: ", slug)
panicLogger := log.New(multiLogger, "PANIC: ", slug)
return &AggregatedLogger{ return &AggregatedLogger{
infoLogger: infoLogger, infoLogger: infoLogger,

19
main.go
View File

@ -7,9 +7,9 @@ import (
"github.com/fossyy/filekeeper/email" "github.com/fossyy/filekeeper/email"
"github.com/fossyy/filekeeper/logger" "github.com/fossyy/filekeeper/logger"
"github.com/fossyy/filekeeper/middleware" "github.com/fossyy/filekeeper/middleware"
"github.com/fossyy/filekeeper/routes" "github.com/fossyy/filekeeper/routes/admin"
"github.com/fossyy/filekeeper/routes/client"
"github.com/fossyy/filekeeper/utils" "github.com/fossyy/filekeeper/utils"
"net/http"
"strconv" "strconv"
) )
@ -24,24 +24,15 @@ func main() {
dbName := utils.Getenv("DB_NAME") dbName := utils.Getenv("DB_NAME")
database := db.NewPostgresDB(dbUser, dbPass, dbHost, dbPort, dbName, db.DisableSSL) database := db.NewPostgresDB(dbUser, dbPass, dbHost, dbPort, dbName, db.DisableSSL)
db.DB = database
smtpPort, _ := strconv.Atoi(utils.Getenv("SMTP_PORT")) smtpPort, _ := strconv.Atoi(utils.Getenv("SMTP_PORT"))
mailServer := email.NewSmtpServer(utils.Getenv("SMTP_HOST"), smtpPort, utils.Getenv("SMTP_USER"), utils.Getenv("SMTP_PASSWORD")) mailServer := email.NewSmtpServer(utils.Getenv("SMTP_HOST"), smtpPort, utils.Getenv("SMTP_USER"), utils.Getenv("SMTP_PASSWORD"))
app.Server = app.NewClientServer(clientAddr, middleware.Handler(routes.SetupRoutes()), *logger.Logger(), database, mailServer) app.Server = app.NewClientServer(clientAddr, middleware.Handler(client.SetupRoutes()), *logger.Logger(), database, mailServer)
app.Admin = app.NewAdminServer(adminAddr, middleware.Handler(admin.SetupRoutes()), database)
//TODO: Move admin route to its own folder
testRoute := http.NewServeMux()
testRoute.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
return
})
app.Admin = app.NewAdminServer(adminAddr, testRoute, database)
go func() { go func() {
fmt.Printf("Admin Web App Listening on http://%s\n\n", app.Admin.Addr) fmt.Printf("Admin Web App Listening on http://%s\n", app.Admin.Addr)
err := app.Admin.ListenAndServe() err := app.Admin.ListenAndServe()
if err != nil { if err != nil {
panic(err) panic(err)

12
routes/admin/routes.go Normal file
View File

@ -0,0 +1,12 @@
package admin
import "net/http"
func SetupRoutes() *http.ServeMux {
handler := http.NewServeMux()
handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
return
})
return handler
}

View File

@ -1,4 +1,4 @@
package routes package client
import ( import (
googleOauthHandler "github.com/fossyy/filekeeper/handler/auth/google" googleOauthHandler "github.com/fossyy/filekeeper/handler/auth/google"