Add session middleware

This commit is contained in:
ekzyis 2024-07-12 15:30:41 +02:00
parent 2653e816bb
commit 9a92444eee
3 changed files with 39 additions and 19 deletions

View File

@ -1,33 +1,41 @@
package middleware
import (
"database/sql"
"net/http"
"git.ekzyis.com/ekzyis/delphi.market/server/router/context"
"git.ekzyis.com/ekzyis/delphi.market/types"
"github.com/labstack/echo/v4"
)
func Session(sc context.Context) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// TODO: implement session middleware
// var (
// cookie *http.Cookie
// err error
// s *db.Session
// u *db.User
// )
// if cookie, err = c.Cookie("session"); err != nil {
// // cookie not found
// return next(c)
// }
// s = &db.Session{SessionId: cookie.Value}
// if err = sc.Db.FetchSession(s); err == nil {
// // session found
// c.Set("session", *u)
// } else if err != sql.ErrNoRows {
// return err
// }
var (
db = sc.Db
ctx = c.Request().Context()
cookie *http.Cookie
err error
u = types.User{}
)
if cookie, err = c.Cookie("session"); err != nil {
// cookie not found
return next(c)
}
if err = db.QueryRowContext(
ctx,
""+
"SELECT u.id, u.created_at, COALESCE(u.ln_pubkey, ''), COALESCE(u.nostr_pubkey, ''), u.msats "+
"FROM sessions s LEFT JOIN users u ON u.id = s.user_id "+
"WHERE s.id = $1",
cookie.Value).
Scan(&u.Id, &u.CreatedAt, &u.LnPubkey, &u.NostrPubkey, &u.Msats); err == nil {
// session found
c.Set("session", u)
} else if err != sql.ErrNoRows {
return err
}
return next(c)
}
}

View File

@ -5,12 +5,13 @@ import (
"git.ekzyis.com/ekzyis/delphi.market/server/router/context"
"git.ekzyis.com/ekzyis/delphi.market/server/router/handler"
"git.ekzyis.com/ekzyis/delphi.market/server/router/middleware"
)
type Context = context.Context
func Init(e *echo.Echo, sc Context) {
// e.Use(middleware.Session(sc))
e.Use(middleware.Session(sc))
e.GET("/", handler.HandleIndex(sc))
e.GET("/about", handler.HandleAbout(sc))

11
types/types.go Normal file
View File

@ -0,0 +1,11 @@
package types
import "time"
type User struct {
Id int
CreatedAt time.Time
LnPubkey string
NostrPubkey string
Msats int64
}