-
Notifications
You must be signed in to change notification settings - Fork 8
/
firebase_auth.go
74 lines (67 loc) · 1.81 KB
/
firebase_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
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
package ginfirebaseauth
import (
"context"
"net/http"
"strings"
firebase "firebase.google.com/go"
"firebase.google.com/go/auth"
"github.com/gin-gonic/gin"
"google.golang.org/api/option"
)
const valName = "FIREBASE_ID_TOKEN"
// FirebaseAuthMiddleware is middleware for Firebase Authentication
type FirebaseAuthMiddleware struct {
cli *auth.Client
unAuthorized func(c *gin.Context)
}
// New is constructor of the middleware
func New(credFileName string, unAuthorized func(c *gin.Context)) (*FirebaseAuthMiddleware, error) {
opt := option.WithCredentialsFile(credFileName)
app, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
return nil, err
}
auth, err := app.Auth(context.Background())
if err != nil {
return nil, err
}
return &FirebaseAuthMiddleware{
cli: auth,
unAuthorized: unAuthorized,
}, nil
}
// MiddlewareFunc is function to verify token
func (fam *FirebaseAuthMiddleware) MiddlewareFunc() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.Request.Header.Get("Authorization")
_, token, found := strings.Cut(authHeader, " ")
if !found {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"status": http.StatusForbidden,
"message": http.StatusText(http.StatusForbidden),
})
return
}
idToken, err := fam.cli.VerifyIDToken(context.Background(), token)
if err != nil {
if fam.unAuthorized != nil {
fam.unAuthorized(c)
} else {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"status": http.StatusUnauthorized,
"message": http.StatusText(http.StatusUnauthorized),
})
}
}
c.Set(valName, idToken)
c.Next()
}
}
// ExtractClaims extracts claims
func ExtractClaims(c *gin.Context) *auth.Token {
idToken, ok := c.Get(valName)
if !ok {
return new(auth.Token)
}
return idToken.(*auth.Token)
}