2021-07-09 06:11:11 +00:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-07-14 18:17:01 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"jokes-bapak2-api/app/v1/models"
|
|
|
|
"jokes-bapak2-api/app/v1/platform/database"
|
2021-07-09 06:11:11 +00:00
|
|
|
|
|
|
|
"github.com/Masterminds/squirrel"
|
|
|
|
phccrypto "github.com/aldy505/phc-crypto"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
|
|
)
|
|
|
|
|
|
|
|
var psql = squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar)
|
|
|
|
var db = database.New()
|
|
|
|
|
|
|
|
func RequireAuth() fiber.Handler {
|
|
|
|
return func(c *fiber.Ctx) error {
|
2021-07-17 09:06:33 +00:00
|
|
|
var auth models.Auth
|
2021-07-09 06:11:11 +00:00
|
|
|
err := c.BodyParser(&auth)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-07-14 18:17:01 +00:00
|
|
|
// Check if key exists
|
|
|
|
sql, args, err := psql.Select("token").From("administrators").Where(squirrel.Eq{"key": auth.Key}).ToSql()
|
2021-07-09 06:11:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-07-14 18:17:01 +00:00
|
|
|
|
2021-07-09 06:11:11 +00:00
|
|
|
var token string
|
|
|
|
err = db.QueryRow(context.Background(), sql, args...).Scan(&token)
|
|
|
|
if err != nil {
|
2021-07-14 18:17:01 +00:00
|
|
|
if err.Error() == "no rows in result set" {
|
2021-07-17 09:06:33 +00:00
|
|
|
return c.Status(fiber.StatusForbidden).JSON(models.Error{
|
2021-07-14 18:17:01 +00:00
|
|
|
Error: "Invalid key",
|
|
|
|
})
|
|
|
|
}
|
2021-07-09 06:11:11 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
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-07-14 18:17:01 +00:00
|
|
|
sql, args, err = psql.Update("administrator").Set("last_used", time.Now().UTC().Format(time.RFC3339)).ToSql()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = db.Query(context.Background(), sql, args...)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
sql, args, err = psql.Select("id").From("administrators").Where(squirrel.Eq{"key": auth.Key}).ToSql()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
var id int
|
|
|
|
err = db.QueryRow(context.Background(), sql, args...).Scan(&id)
|
|
|
|
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-07-17 09:06:33 +00:00
|
|
|
return c.Status(fiber.StatusForbidden).JSON(models.Error{
|
2021-07-09 12:13:19 +00:00
|
|
|
Error: "Invalid key",
|
2021-07-09 06:11:11 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|