From 4a46c58b5e7501b3416ef51b40f1372c6a53c882 Mon Sep 17 00:00:00 2001 From: Firdavs Date: Tue, 26 Mar 2024 21:43:23 +0300 Subject: [PATCH] [change] Add UserAuthMiddleware to handle user authentication --- app/http/middleware/userAuth.go | 36 +++++++++++++++++++++++++++++---- app/http/server.go | 2 ++ 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/app/http/middleware/userAuth.go b/app/http/middleware/userAuth.go index e092f94..caebfc6 100644 --- a/app/http/middleware/userAuth.go +++ b/app/http/middleware/userAuth.go @@ -1,9 +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{ -// -} \ No newline at end of file +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!"})