-
Notifications
You must be signed in to change notification settings - Fork 0
/
firebase.go
65 lines (54 loc) · 1.58 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
package auth
import (
"context"
"errors"
errs "github.com/pkg/errors"
"log"
"net/http"
"os"
"strings"
firebase "firebase.google.com/go"
fbauth "firebase.google.com/go/auth"
"github.com/gin-gonic/gin"
"google.golang.org/api/option"
)
const (
FirebaseContextVal = "FIREBASE_ID_TOKEN"
)
var (
firebaseConfigFile = os.Getenv("FIREBASE_CONFIG_FILE")
)
// load firebase configuration and create the auth client
// expecting env variable FIREBASE_CONFIG_FILE
func InitAuth() (*fbauth.Client, error) {
if firebaseConfigFile == "" {
return nil, errors.New("FIREBASE_CONFIG_FILE required")
}
opt := option.WithCredentialsFile(firebaseConfigFile)
app, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
return nil, errs.Wrap(err, "error initializing app, creating fb app")
}
client, errAuth := app.Auth(context.Background())
if errAuth != nil {
return nil, errs.Wrap(err, "error initializing auth, creating fb client")
}
return client, nil
}
// use id_token provided in Authorization: Bearer [ID_TOKEN]
func VerifyToken(c *gin.Context, client *fbauth.Client) (int, string, error) {
authHeader := c.Request.Header.Get(authorizationHeader)
token := strings.Replace(authHeader, "Bearer ", "", 1)
idtoken, err := client.VerifyIDToken(c, token)
if err != nil {
return http.StatusUnauthorized, "not authenticated", errs.Wrap(err, "failed to verify token")
}
claims := idtoken.Claims
if admin, ok := claims["admin"]; ok {
if admin.(bool) {
return 0, "", nil
}
}
log.Println("not admin")
return http.StatusForbidden, "not admin", errors.New("not admin")
}