-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.go
76 lines (60 loc) · 1.57 KB
/
middleware.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package auth
import (
"context"
"errors"
"net/http"
"github.com/labstack/echo/v4"
"github.com/sparkymat/archmark/dbx"
)
const (
UserKey = "user"
)
const (
sessionName = "archmark_session"
tokenKey = "auth_token"
)
var ErrTokenMissing = errors.New("token missing")
type ConfigService interface {
JWTSecret() string
ProxyAuthUsernameHeader() string
ProxyAuthNameHeader() string
}
type DatabaseService interface {
FetchUserByUsername(ctx context.Context, username string) (dbx.User, error)
CreateUser(ctx context.Context, arg dbx.CreateUserParams) (dbx.User, error)
}
const ClientNameKey = "client_name"
func Middleware(cfg ConfigService, db DatabaseService) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
err := sessionAuth(cfg, db, c)
if err == nil {
return next(c)
}
return c.Redirect(http.StatusSeeOther, "/login") //nolint:wrapcheck
}
}
}
func APIMiddleware(cfg ConfigService, db DatabaseService) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
err := sessionAuth(cfg, db, c)
if err == nil {
return next(c)
}
return c.Redirect(http.StatusSeeOther, "/login") //nolint:wrapcheck
}
}
}
func sessionAuth(cfg ConfigService, db DatabaseService, c echo.Context) error {
username, err := LoadUsernameFromSession(cfg, c)
if err != nil {
return err
}
user, err := db.FetchUserByUsername(c.Request().Context(), username)
if err != nil {
return err //nolint:wrapcheck
}
c.Set(UserKey, user)
return nil
}