-
Notifications
You must be signed in to change notification settings - Fork 0
/
firebase.go
76 lines (66 loc) · 1.8 KB
/
firebase.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
75
76
package middleware
import (
"context"
"log"
"net/http"
"strings"
firebase "firebase.google.com/go"
"firebase.google.com/go/auth"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"google.golang.org/api/option"
)
const valName = "FIREBASE_ID_TOKEN"
// FirebaseAuthMiddleware contains methods verifying JWT token
type FirebaseAuthMiddleware struct {
fbase *firebase.App
skipper middleware.Skipper
}
// NewFireBaseAuthMiddleware is middleware authentication with firebase
func NewFireBaseAuthMiddleware(credFilePath string, skipper middleware.Skipper) (*FirebaseAuthMiddleware, error) {
opt := option.WithCredentialsFile(credFilePath)
app, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
return nil, err
}
if skipper == nil {
skipper = middleware.DefaultSkipper
}
return &FirebaseAuthMiddleware{
fbase: app,
skipper: skipper,
}, nil
}
// Verify verifies token
func (f *FirebaseAuthMiddleware) Verify(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if f.skipper(c) {
return next(c)
}
r := c.Request()
token := strings.Replace(r.Header.Get(echo.HeaderAuthorization), "Bearer ", "", 1)
if token == "" {
return c.String(http.StatusUnauthorized, "Bad token")
}
client, err := f.fbase.Auth(context.Background())
if err != nil {
log.Println(err)
return c.String(http.StatusUnauthorized, "Bad token")
}
authToken, err := client.VerifyIDToken(context.Background(), token)
if err != nil {
log.Println(err)
return c.String(http.StatusUnauthorized, "Bad token")
}
c.Set(valName, authToken)
return next(c)
}
}
// ExtractClaims extracts claims
func ExtractClaims(c echo.Context) *auth.Token {
idToken := c.Get(valName)
if idToken == nil {
return new(auth.Token)
}
return idToken.(*auth.Token)
}