2022-05-30 16:24:59 +02:00
|
|
|
package admin
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/golang-jwt/jwt"
|
2022-05-31 10:35:49 +02:00
|
|
|
"github.com/grassrootseconomics/cic-go/meta"
|
2022-05-30 16:24:59 +02:00
|
|
|
"github.com/jackc/pgx/v4/pgxpool"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
"github.com/nleof/goyesql"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
)
|
|
|
|
|
|
|
|
type api struct {
|
|
|
|
db *pgxpool.Pool
|
|
|
|
q goyesql.Queries
|
2022-05-31 10:35:49 +02:00
|
|
|
m *meta.CicMeta
|
2022-05-30 16:24:59 +02:00
|
|
|
jwtKey []byte
|
|
|
|
}
|
|
|
|
|
2022-05-31 10:35:49 +02:00
|
|
|
func InitAdminApi(e *echo.Echo, db *pgxpool.Pool, queries goyesql.Queries, metaClient *meta.CicMeta, jwtKey string) {
|
|
|
|
api := newApi(db, queries, metaClient, jwtKey)
|
2022-05-30 16:24:59 +02:00
|
|
|
|
|
|
|
auth := e.Group(("/auth"))
|
|
|
|
g := e.Group("/admin")
|
|
|
|
|
|
|
|
auth.Use(api.dwCoreMiddleware)
|
|
|
|
auth.POST("/login", sendLoginJwtCookie)
|
|
|
|
auth.POST("/logout", sendLogoutCookie)
|
|
|
|
|
|
|
|
g.Use(api.dwCoreMiddleware)
|
|
|
|
g.Use(api.verifyAuthMiddleware)
|
|
|
|
|
2022-05-31 10:35:49 +02:00
|
|
|
g.GET("/meta-proxy/:address", handleMetaProxy)
|
2022-05-30 16:24:59 +02:00
|
|
|
}
|
|
|
|
|
2022-05-31 10:35:49 +02:00
|
|
|
func newApi(db *pgxpool.Pool, queries goyesql.Queries, metaClient *meta.CicMeta, jwtKey string) *api {
|
|
|
|
log.Info().Msgf("%s inj", jwtKey)
|
2022-05-30 16:24:59 +02:00
|
|
|
return &api{
|
|
|
|
db: db,
|
|
|
|
q: queries,
|
2022-05-31 10:35:49 +02:00
|
|
|
m: metaClient,
|
2022-05-30 16:24:59 +02:00
|
|
|
jwtKey: []byte(jwtKey),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *api) dwCoreMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
|
|
|
c.Set("api", &api{
|
|
|
|
db: a.db,
|
|
|
|
q: a.q,
|
2022-05-31 10:35:49 +02:00
|
|
|
m: a.m,
|
2022-05-30 16:24:59 +02:00
|
|
|
jwtKey: a.jwtKey,
|
|
|
|
})
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *api) verifyAuthMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
|
|
|
cookie, err := c.Cookie("_ge_auth")
|
|
|
|
if err != nil {
|
|
|
|
return c.String(http.StatusForbidden, "auth cookie missing")
|
|
|
|
}
|
|
|
|
|
|
|
|
claims := &jwtClaims{}
|
|
|
|
|
|
|
|
token, err := jwt.ParseWithClaims(cookie.Value, claims, func(token *jwt.Token) (interface{}, error) {
|
|
|
|
return a.jwtKey, nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
2022-05-31 10:35:49 +02:00
|
|
|
return c.String(http.StatusUnauthorized, "jwt validation failed")
|
2022-05-30 16:24:59 +02:00
|
|
|
}
|
|
|
|
if !token.Valid {
|
|
|
|
return c.String(http.StatusUnauthorized, "jwt invalid")
|
|
|
|
}
|
|
|
|
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
}
|