Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/http server user auth secure #13

Merged
merged 9 commits into from
Mar 26, 2024
37 changes: 37 additions & 0 deletions app/http/middleware/userAuth.go
Original file line number Diff line number Diff line change
@@ -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()
}
}
2 changes: 2 additions & 0 deletions app/http/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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!"})
Expand Down
9 changes: 9 additions & 0 deletions app/models/AuthTokens.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package models

import "gorm.io/gorm"

type AuthToken struct {
gorm.Model
Name string
Token string
}
4 changes: 0 additions & 4 deletions config/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package config
import (
"fmt"

"github.com/Firdavs9512/qk-server/app/models"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
Expand Down Expand Up @@ -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!")
}
33 changes: 25 additions & 8 deletions core/configInit.go
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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,
Expand All @@ -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),
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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

Expand Down
5 changes: 5 additions & 0 deletions core/installation.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ import (
func StartInitiation() {
// Init database
config.Database.Init()
// Migrate database models
Migrate()

// Init config
ConfigInit()

// Init file directory
InitDirectory()
Expand Down
14 changes: 14 additions & 0 deletions core/migration.go
Original file line number Diff line number Diff line change
@@ -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{},
)
}
4 changes: 4 additions & 0 deletions test/database/FilesModel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
12 changes: 12 additions & 0 deletions utils/randomGenerator.go
Original file line number Diff line number Diff line change
@@ -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)
}
Loading