-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
42 lines (35 loc) · 857 Bytes
/
auth.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
package middleware
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// Auth middleware using JWT
func Auth(callback func(*gin.Context, string) error) gin.HandlerFunc {
return func(c *gin.Context) {
// get authorization header
headerStr := strings.TrimSpace(c.GetHeader("authorization"))
if headerStr == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "bearer token required",
})
return
}
// check for bearer
authHeaders := strings.Split(headerStr, " ")
if len(authHeaders) != 2 {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "invalid authorization token",
})
}
// validate token
err := callback(c, authHeaders[1])
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": err.Error(),
})
}
// continue
c.Next()
}
}