summaryrefslogtreecommitdiff
path: root/web/middleware/api_auth.go
blob: b85429749ee9046a966d0ef1bde7deb156f9577f (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
package middleware

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

const API_AUTH_USER_KEY = "APIAuthUserKey"

func ApiAuthMiddleware(c *gin.Context) {
	cfg := GetServerConfig(c)

	auth := strings.Split(c.Request.Header.Get("Authorization"), " ")

	if len(auth) != 2 || auth[0] != "Bearer" {
		c.AbortWithStatus(http.StatusUnauthorized)
		return
	}

	if user, ok := cfg.ApiSecrets[auth[1]]; ok {
		c.Set(API_AUTH_USER_KEY, user)
	} else {
		c.AbortWithStatus(http.StatusUnauthorized)
		return
	}

	c.Next()
}

func GetAPIAuthUser(c *gin.Context) string {
	return c.GetString(API_AUTH_USER_KEY)
}