summaryrefslogtreecommitdiff
path: root/app/middleware/token_auth.go
blob: 08e302e08183c8a11744cfadb7d5248792390f1e (plain)
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
package middleware

import (
	"net/http"
	"strings"
	"time"

	"code.crute.us/mcrute/ssh-proxy/app/models"
	"github.com/labstack/echo/v4"
	"golang.org/x/exp/slices"
)

const authorizedSession = "__ssh-proxy_authorized_session"

func GetAuthorizedSession(c echo.Context) *models.AuthSession {
	ses := c.Get(authorizedSession)
	if ses != nil {
		return ses.(*models.AuthSession)
	}
	return nil
}

type TokenAuthMiddleware struct {
	Logger        echo.Logger
	RequiredScope string
	AuthSessions  models.AuthSessionStore
}

func (m *TokenAuthMiddleware) Middleware(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		authHeader := strings.SplitN(c.Request().Header.Get("Authorization"), " ", 2)

		if len(authHeader) != 2 || strings.ToLower(authHeader[0]) != "bearer" {
			return c.JSON(http.StatusBadRequest, models.Oauth2Error{
				Type:        models.ErrInvalidRequest,
				Description: "invalid authorization header",
			})
		}

		session, err := m.AuthSessions.GetByAccessCode(c.Request().Context(), authHeader[1])
		if err != nil {
			return c.JSON(http.StatusUnauthorized, models.Oauth2Error{
				Type: models.ErrAccessDenied,
			})
		}

		if time.Now().After(session.Expires) {
			return c.JSON(http.StatusUnauthorized, models.Oauth2Error{
				Type: models.ErrAccessDenied,
			})
		}

		if !slices.Contains(session.Scope, m.RequiredScope) {
			return c.JSON(http.StatusUnauthorized, models.Oauth2Error{
				Type: models.ErrAccessDenied,
			})
		}

		if session.IsRegistration {
			return c.JSON(http.StatusUnauthorized, models.Oauth2Error{
				Type: models.ErrAccessDenied,
			})
		}

		c.Set(authorizedSession, session)

		return next(c)
	}
}