| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- package middleware
- import (
- "net/http"
- "github.com/gorilla/sessions"
- "github.com/labstack/echo/v4"
- )
- const (
- SessionName = "goflare"
- UserIDKey = "user_id"
- )
- func RequireAuth(store sessions.Store) echo.MiddlewareFunc {
- return func(next echo.HandlerFunc) echo.HandlerFunc {
- return func(c echo.Context) error {
- sess, err := GetSession(c, store)
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": "session error"})
- }
- userID, ok := sess.Values[UserIDKey]
- if !ok || userID == nil {
- return c.JSON(http.StatusUnauthorized, map[string]string{"error": "not authenticated"})
- }
- c.Set(UserIDKey, userID)
- return next(c)
- }
- }
- }
- func GetSession(c echo.Context, store sessions.Store) (*sessions.Session, error) {
- sess, err := store.Get(c.Request(), SessionName)
- if err != nil {
- // Cookie can't be decoded (e.g. secret changed). gorilla/sessions
- // still returns a new empty session. Clear its values and the
- // IsNew flag is already true, so callers proceed as if no session
- // existed. The stale cookie gets overwritten on the next Save().
- for k := range sess.Values {
- delete(sess.Values, k)
- }
- return sess, nil
- }
- return sess, nil
- }
|