diff --git a/app/http/middleware/userAuth.go b/app/http/middleware/userAuth.go new file mode 100644 index 0000000..caebfc6 --- /dev/null +++ b/app/http/middleware/userAuth.go @@ -0,0 +1,37 @@ +package middleware + +import ( + "github.com/Firdavs9512/qk-server/app/models" + "github.com/Firdavs9512/qk-server/config" + "github.com/kataras/iris/v12" +) + +type RequestHeader struct { + Authorization string `header:"Authorization,required"` +} + +func UserAuthMiddleware() iris.Handler { + return func(ctx iris.Context) { + var requestHeader RequestHeader + if err := ctx.ReadHeaders(&requestHeader); err != nil { + ctx.StatusCode(iris.StatusBadRequest) + ctx.JSON(iris.Map{"message": "Invalid request"}) + return + } + + if requestHeader.Authorization == "" { + ctx.StatusCode(iris.StatusUnauthorized) + ctx.JSON(iris.Map{"message": "Unauthorized"}) + return + } + + var token models.AuthToken + if err := config.Database.DB.Where("token = ?", requestHeader.Authorization).First(&token).Error; err != nil { + ctx.StatusCode(iris.StatusUnauthorized) + ctx.JSON(iris.Map{"message": "Unauthorized"}) + return + } + + ctx.Next() + } +} diff --git a/app/http/server.go b/app/http/server.go index e0c430b..a53a257 100644 --- a/app/http/server.go +++ b/app/http/server.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/Firdavs9512/qk-server/app/http/controllers" + "github.com/Firdavs9512/qk-server/app/http/middleware" "github.com/Firdavs9512/qk-server/config" "github.com/kataras/iris/v12" "github.com/kataras/iris/v12/mvc" @@ -19,6 +20,7 @@ func (s *Server) Start() { // Configure Application.Use(iris.LimitRequestBodySize(config.App.MaxFileSize)) + Application.Use(middleware.UserAuthMiddleware()) Application.Get("/", func(ctx iris.Context) { ctx.JSON(iris.Map{"message": "Ok!"}) diff --git a/app/models/AuthTokens.go b/app/models/AuthTokens.go new file mode 100644 index 0000000..67d05da --- /dev/null +++ b/app/models/AuthTokens.go @@ -0,0 +1,9 @@ +package models + +import "gorm.io/gorm" + +type AuthToken struct { + gorm.Model + Name string + Token string +} diff --git a/config/database.go b/config/database.go index aa2ec0b..4aeaa9d 100644 --- a/config/database.go +++ b/config/database.go @@ -3,7 +3,6 @@ package config import ( "fmt" - "github.com/Firdavs9512/qk-server/app/models" "gorm.io/driver/sqlite" "gorm.io/gorm" ) @@ -43,8 +42,5 @@ func (d *DatabaseType) Init() { panic("failed to connect database") } - // Migrate the schema - d.DB.AutoMigrate(&models.Files{}, &models.Settings{}) - fmt.Println("Database connected!") } diff --git a/core/configInit.go b/core/configInit.go index bea6a0c..5bd64b9 100644 --- a/core/configInit.go +++ b/core/configInit.go @@ -1,11 +1,15 @@ package core import ( + "fmt" "strconv" "github.com/Firdavs9512/qk-server/app/http" "github.com/Firdavs9512/qk-server/app/models" "github.com/Firdavs9512/qk-server/config" + "github.com/Firdavs9512/qk-server/utils" + "github.com/fatih/color" + "gorm.io/gorm" ) // Local config files initialization in database @@ -18,8 +22,8 @@ func ConfigInit() { // Application host var host *models.Settings - config.Database.DB.Where("key = ?", "app_host").First(&host) - if host == nil { + hResult := config.Database.DB.Where("key = ?", "app_host").First(&host) + if hResult.Error == gorm.ErrRecordNotFound { config.Database.DB.Create(&models.Settings{ Key: "app_host", Value: config.App.AppHost, @@ -31,8 +35,8 @@ func ConfigInit() { // Application port var port *models.Settings - config.Database.DB.Where("key = ?", "app_port").First(&port) - if port == nil { + pResult := config.Database.DB.Where("key = ?", "app_port").First(&port) + if pResult.Error == gorm.ErrRecordNotFound { config.Database.DB.Create(&models.Settings{ Key: "app_port", Value: strconv.Itoa(config.App.AppPort), @@ -48,8 +52,8 @@ func ConfigInit() { // Application version var version *models.Settings - config.Database.DB.Where("key = ?", "app_version").First(&version) - if version == nil { + vResult := config.Database.DB.Where("key = ?", "app_version").First(&version) + if vResult.Error == gorm.ErrRecordNotFound { config.Database.DB.Create(&models.Settings{ Key: "app_version", Value: config.App.Version, @@ -61,8 +65,8 @@ func ConfigInit() { // Application Upload URL var uploadUrl *models.Settings - config.Database.DB.Where("key = ?", "upload_url").First(&uploadUrl) - if uploadUrl == nil { + uResult := config.Database.DB.Where("key = ?", "upload_url").First(&uploadUrl) + if uResult.Error == gorm.ErrRecordNotFound { config.Database.DB.Create(&models.Settings{ Key: "upload_url", Value: config.App.UploadUrl, @@ -72,6 +76,19 @@ func ConfigInit() { appConfig.UploadUrl = uploadUrl.Value } + // Check auth token if not exists create one + var count int64 + config.Database.DB.Model(&models.AuthToken{}).Count(&count) + if count == 0 { + token := utils.RandomString(32) + config.Database.DB.Create(&models.AuthToken{ + Token: token, + Name: "Default", + }) + + fmt.Printf("Default Auth Token: %s\n", color.HiYellowString(token)) + } + // Set the new config config.App = appConfig diff --git a/core/installation.go b/core/installation.go index 99d8030..a22d64f 100644 --- a/core/installation.go +++ b/core/installation.go @@ -10,6 +10,11 @@ import ( func StartInitiation() { // Init database config.Database.Init() + // Migrate database models + Migrate() + + // Init config + ConfigInit() // Init file directory InitDirectory() diff --git a/core/migration.go b/core/migration.go new file mode 100644 index 0000000..b739c51 --- /dev/null +++ b/core/migration.go @@ -0,0 +1,14 @@ +package core + +import ( + "github.com/Firdavs9512/qk-server/app/models" + "github.com/Firdavs9512/qk-server/config" +) + +func Migrate() { + config.Database.DB.AutoMigrate( + &models.AuthToken{}, + &models.Settings{}, + &models.Files{}, + ) +} diff --git a/test/database/FilesModel_test.go b/test/database/FilesModel_test.go index 48ce181..6c7b683 100644 --- a/test/database/FilesModel_test.go +++ b/test/database/FilesModel_test.go @@ -5,11 +5,15 @@ import ( "testing" "github.com/Firdavs9512/qk-server/config" + "github.com/Firdavs9512/qk-server/core" ) func TestFilesModel(t *testing.T) { config.Database.Init() + // Migrate database models + core.Migrate() + // Files model exists if !config.Database.DB.Migrator().HasTable("files") { t.Errorf("Table files does not exist") diff --git a/utils/randomGenerator.go b/utils/randomGenerator.go new file mode 100644 index 0000000..0b7cf38 --- /dev/null +++ b/utils/randomGenerator.go @@ -0,0 +1,12 @@ +package utils + +import "math/rand" + +func RandomString(length int) string { + const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + b := make([]byte, length) + for i := range b { + b[i] = charset[rand.Intn(len(charset))] + } + return string(b) +}