2021-07-09 06:11:11 +00:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2021-10-18 08:31:17 +00:00
|
|
|
"jokes-bapak2-api/app/core/administrator"
|
2021-07-14 18:17:01 +00:00
|
|
|
|
2021-07-09 06:11:11 +00:00
|
|
|
phccrypto "github.com/aldy505/phc-crypto"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
2021-09-26 19:13:38 +00:00
|
|
|
"github.com/jackc/pgx/v4/pgxpool"
|
2021-07-09 06:11:11 +00:00
|
|
|
)
|
|
|
|
|
2021-10-18 08:31:17 +00:00
|
|
|
func RequireAuth(db *pgxpool.Pool) fiber.Handler {
|
2021-07-09 06:11:11 +00:00
|
|
|
return func(c *fiber.Ctx) error {
|
2021-09-26 19:13:38 +00:00
|
|
|
var auth Auth
|
2021-07-09 06:11:11 +00:00
|
|
|
err := c.BodyParser(&auth)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-10-18 08:31:17 +00:00
|
|
|
token, err := administrator.CheckKeyExists(db, c.Context(), auth.Key)
|
2021-07-09 06:11:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-07-14 18:17:01 +00:00
|
|
|
|
2021-10-18 08:31:17 +00:00
|
|
|
if token == "" {
|
|
|
|
return c.
|
|
|
|
Status(fiber.StatusForbidden).
|
|
|
|
JSON(Error{
|
|
|
|
Error: "Invalid key",
|
|
|
|
})
|
2021-07-09 06:11:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
crypto, err := phccrypto.Use(phccrypto.Argon2, phccrypto.Config{})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-07-14 18:17:01 +00:00
|
|
|
verify, err := crypto.Verify(token, auth.Token)
|
2021-07-09 06:11:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if verify {
|
2021-10-18 08:31:17 +00:00
|
|
|
id, err := administrator.GetUserID(db, c.Context(), auth.Key)
|
2021-07-14 18:17:01 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Locals("userID", id)
|
|
|
|
return c.Next()
|
2021-07-09 06:11:11 +00:00
|
|
|
}
|
2021-07-09 12:13:19 +00:00
|
|
|
|
2021-08-04 10:14:33 +00:00
|
|
|
return c.
|
|
|
|
Status(fiber.StatusForbidden).
|
2021-09-26 19:13:38 +00:00
|
|
|
JSON(Error{
|
2021-08-04 10:14:33 +00:00
|
|
|
Error: "Invalid key",
|
|
|
|
})
|
2021-07-09 06:11:11 +00:00
|
|
|
}
|
|
|
|
}
|