Skip to content

Commit

Permalink
[change] Add UserAuthMiddleware to handle user authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
Firdavs9512 committed Mar 26, 2024
1 parent a393e2a commit 4a46c58
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
36 changes: 32 additions & 4 deletions app/http/middleware/userAuth.go
Original file line number Diff line number Diff line change
@@ -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{
//
}
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

0 comments on commit 4a46c58

Please sign in to comment.