Parent directory

auth.go

994 bytes
 1package auth
 2
 3import (
 4	"net/http"
 5
 6	"github.com/gin-gonic/gin"
 7)
 8
 9// PageAuthMiddleware will authenticate against a static auth token
10func PageAuthMiddleware(authToken string) gin.HandlerFunc {
11	return func(c *gin.Context) {
12		tokenCookie, err := c.Request.Cookie("token")
13		if err != nil {
14			c.Redirect(http.StatusFound, "/auth")
15			c.Abort()
16			return
17		}
18		if tokenCookie.Value != authToken {
19			c.Redirect(http.StatusFound, "/auth")
20			c.Abort()
21			return
22		}
23
24		c.Next()
25	}
26}
27
28// APIAuthMiddleware will authenticate API endpoints against a static auth token
29func APIAuthMiddleware(authToken string) gin.HandlerFunc {
30	return func(c *gin.Context) {
31		token, ok := c.Request.Header["Authorization"]
32		if !ok || len(token) != 1 {
33			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing Authorization header"})
34			return
35		}
36		if token[0] != authToken {
37			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid auth token"})
38			return
39		}
40
41		c.Next()
42	}
43}