Skip to content

Commit

Permalink
feature add key auth #35 add auth
Browse files Browse the repository at this point in the history
  • Loading branch information
kynmh69 committed Apr 4, 2024
1 parent 044225f commit ba72450
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/middleware/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package middleware

import (
"github.com/kynmh69/go-ja-holidays/model"
"github.com/labstack/echo/v4"
mid "github.com/labstack/echo/v4/middleware"
)

func Auth() echo.MiddlewareFunc {
return mid.KeyAuthWithConfig(mid.KeyAuthConfig{
KeyLookup: "header:X-API-KEY",
Validator: func(auth string, c echo.Context) (bool, error) {
apiKey, err := model.GetApiKey(auth)
if err != nil {
return false, err
}
return auth == apiKey.Key, nil
},
})
}
1 change: 1 addition & 0 deletions src/middleware/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ func SetMiddleware(e *echo.Echo) {
e.Use(mid.Recover())
e.Use(mid.RequestID())
// e.Use(Redirect())
e.Use(Auth())
}
7 changes: 7 additions & 0 deletions src/model/api_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ func GetApiKeys() ([]ApiKey, error) {
return apiKeys, err
}

func GetApiKey(key string) (ApiKey, error) {
var apiKey ApiKey
db := database.GetDbConnection()
_, err := db.From(TABLE_API_KEY).Where(goqu.C(COLUMN_KEY).Eq(key)).ScanStruct(&apiKey)
return apiKey, err
}

func CreateApiKey(c echo.Context) error {
logger := c.Logger()
key := uuid.New()
Expand Down

0 comments on commit ba72450

Please sign in to comment.