-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirebase.go
220 lines (185 loc) · 5.51 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package auth
import (
"fmt"
"log"
firebase "firebase.google.com/go"
fbauth "firebase.google.com/go/auth"
"github.com/gin-gonic/gin"
jgorm "github.com/jinzhu/gorm"
"github.com/spf13/viper"
"google.golang.org/api/option"
"github.com/bsinou/vitrnx-goback/conf"
"github.com/bsinou/vitrnx-goback/gorm"
"github.com/bsinou/vitrnx-goback/model"
)
var (
cfPath string
adminEmail = "Not a valid email, should be overwritten using conf"
anonymousEmail = "Not a valid email, should be overwritten using conf"
)
func init() {
}
// // Login delegates authentication to firebase.
// TODO this is not obvious: firebase does not ease direct auth with login / pwd from the go SDK
// I presume this is to insure they can collect end-user info (like IPADDRESS and client browser...) upon login
// func Login(ctx *gin.Context) error {
// client := fbClient(ctx)
// token, err := client.VerifyIDToken(jwt)
// if err != nil {
// log.Printf("error verifying ID token: %v\n", err)
// return err
// }
// // Store relevant user info in the context
// cs := token.Claims
// ctx.Set(model.KeyUserID, cs[model.FbKeyUserID].(string))
// // We use user email as name for the time being
// ctx.Set(model.KeyUserName, cs[model.FbKeyEmail].(string))
// ctx.Set(model.KeyEmailVerified, cs[model.FbKeyEmailVerified].(bool))
// WithClaims(ctx)
// return nil
// }
// PostLogin add vitrnx specific user info upon login
func PostLogin(ctx *gin.Context) {
// TODO implement this
meta, err := GetUserMeta(ctx)
if err != nil {
ctx.Error(err)
return
}
ctx.JSON(201, gin.H{"userMeta": meta})
}
// CheckCredentialAgainstFireBase simply validate the passed token against firebase.
func CheckCredentialAgainstFireBase(ctx *gin.Context, jwt string) error { //, uid
// credOption := option.WithCredentialsFile(credFilePath())
// fbApp, err := firebase.NewApp(ctx, nil, credOption)
// // TODO add retry
// if err != nil {
// return fmt.Errorf("cannot connect to firebase: %v", err)
// }
// fbClient, err := fbApp.Auth(ctx)
// if err != nil {
// return fmt.Errorf("error getting Auth client: %v", err)
// }
client, err := getFireBaseClient(ctx)
if err != nil {
return err
}
token, err := client.VerifyIDToken(ctx, jwt)
if err != nil {
return fmt.Errorf("JWT validation failed: %v", err)
}
// Store relevant user info in the context
cs := token.Claims
ctx.Set(model.KeyUserID, cs[model.FbKeyUserID].(string))
ctx.Set(model.KeyEmailVerified, cs[model.FbKeyEmailVerified].(bool))
return nil
}
// ListExistingUsers retrieves all users from firebase
func ListExistingUsers(ctx *gin.Context) error { //, uid
// credOption := option.WithCredentialsFile(credFilePath())
// fbApp, err := firebase.NewApp(ctx, nil, credOption)
// // TODO add retry
// if err != nil {
// return fmt.Errorf("cannot connect to firebase: %v", err)
// }
// fbClient, err := fbApp.Auth(ctx)
// if err != nil {
// return fmt.Errorf("error getting Auth client: %v", err)
// }
client, err := getFireBaseClient(ctx)
if err != nil {
return err
}
userIterator := client.Users(ctx, "")
if err != nil {
return fmt.Errorf("could not list users: %v", err)
}
// This must be enhanced, many shortcuts and hacks here...
db := gorm.GetConnection()
defer db.Close()
ae := viper.GetString(conf.KeyAdminEmail)
if ae != "" {
adminEmail = ae
}
an := viper.GetString(conf.KeyAnonymousEmail)
if an != "" {
anonymousEmail = an
}
for {
userRecord, err := userIterator.Next()
if err != nil {
if err.Error() == "no more items in iterator" {
fmt.Println("Sync with firebase done.")
break
}
return err
}
err = updateUser(db, userRecord)
if err != nil {
return err
}
}
if userIterator.PageInfo().Remaining() > 0 {
// TODO implement this
return fmt.Errorf("pagination is not implemented and user count "+
"is greater than what can fit in a page (%d users), missed %d users",
userIterator.PageInfo().MaxSize, userIterator.PageInfo().Remaining())
}
return nil
}
/* HELPER FUNCTIONS */
func getFireBaseClient(ctx *gin.Context) (*fbauth.Client, error) {
credOption := option.WithCredentialsFile(credFilePath())
fbApp, err := firebase.NewApp(ctx, nil, credOption)
// TODO add retry
if err != nil {
return nil, fmt.Errorf("cannot connect to firebase: %v", err)
}
client, err := fbApp.Auth(ctx)
if err != nil {
return nil, fmt.Errorf("error getting Auth client: %v", err)
}
return client, nil
}
// Update the user repository if necessary
// TODO clean this using channel
func updateUser(db *jgorm.DB, eur *fbauth.ExportedUserRecord) error {
var user model.User
err := db.Where(&model.User{UserID: eur.UID}).First(&user).Error
if err == nil {
// User already exist do nothing
return nil
}
if !jgorm.IsRecordNotFoundError(err) {
return err // Unexpected error
}
roleStr := "REGISTERED"
if eur.Email == adminEmail { // Create the admin user
roleStr = "ADMIN"
} else if eur.Email == anonymousEmail { // Create the admin user
roleStr = "ANONYMOUS"
}
user = model.User{
UserID: eur.UID,
Email: eur.Email,
Name: eur.DisplayName,
Roles: []model.Role{
{RoleID: roleStr},
},
}
// db.Set("gorm:association_autoupdate", false).Save(&user)
db.Set("gorm:association_autoupdate", false).Set("gorm:association_autocreate", false).Save(&user)
return nil
}
// Caches path to local Firebase API cert file
func credFilePath() string {
if cfPath != "" {
return cfPath
}
var err error
cfPath, err = conf.GetConfigFile("firebase-apiCert.json")
if err != nil {
log.Fatalf("no firebase API cert file found")
}
return cfPath
}