forked from firebase/firebase-admin-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
import_users.go
278 lines (240 loc) · 7.33 KB
/
import_users.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// Copyright 2019 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package auth
import (
"context"
"encoding/base64"
"errors"
"fmt"
"firebase.google.com/go/internal"
)
const maxImportUsers = 1000
// UserImportOption is an option for the ImportUsers() function.
type UserImportOption interface {
applyTo(req map[string]interface{}) error
}
// UserImportResult represents the result of an ImportUsers() call.
type UserImportResult struct {
SuccessCount int
FailureCount int
Errors []*ErrorInfo
}
// ErrorInfo represents an error encountered while importing a single user account.
//
// The Index field corresponds to the index of the failed user in the users array that was passed
// to ImportUsers().
type ErrorInfo struct {
Index int
Reason string
}
// ImportUsers imports an array of users to Firebase Auth.
//
// No more than 1000 users can be imported in a single call. If at least one user specifies a
// password, a UserImportHash must be specified as an option.
func (c *baseClient) ImportUsers(
ctx context.Context, users []*UserToImport, opts ...UserImportOption) (*UserImportResult, error) {
if len(users) == 0 {
return nil, errors.New("users list must not be empty")
}
if len(users) > maxImportUsers {
return nil, fmt.Errorf("users list must not contain more than %d elements", maxImportUsers)
}
var validatedUsers []map[string]interface{}
hashRequired := false
for _, u := range users {
vu, err := u.validatedUserInfo()
if err != nil {
return nil, err
}
if pw, ok := vu["passwordHash"]; ok && pw != "" {
hashRequired = true
}
validatedUsers = append(validatedUsers, vu)
}
req := map[string]interface{}{
"users": validatedUsers,
}
for _, opt := range opts {
if err := opt.applyTo(req); err != nil {
return nil, err
}
}
if hashRequired {
if algo, ok := req["hashAlgorithm"]; !ok || algo == "" {
return nil, errors.New("hash algorithm option is required to import users with passwords")
}
}
var parsed struct {
Error []struct {
Index int `json:"index"`
Message string `json:"message"`
} `json:"error,omitempty"`
}
_, err := c.post(ctx, "/accounts:batchCreate", req, &parsed)
if err != nil {
return nil, err
}
result := &UserImportResult{
SuccessCount: len(users) - len(parsed.Error),
FailureCount: len(parsed.Error),
}
for _, e := range parsed.Error {
result.Errors = append(result.Errors, &ErrorInfo{
Index: int(e.Index),
Reason: e.Message,
})
}
return result, nil
}
// UserToImport represents a user account that can be bulk imported into Firebase Auth.
type UserToImport struct {
params map[string]interface{}
}
// UID setter. This field is required.
func (u *UserToImport) UID(uid string) *UserToImport {
return u.set("localId", uid)
}
// Email setter.
func (u *UserToImport) Email(email string) *UserToImport {
return u.set("email", email)
}
// DisplayName setter.
func (u *UserToImport) DisplayName(displayName string) *UserToImport {
return u.set("displayName", displayName)
}
// PhotoURL setter.
func (u *UserToImport) PhotoURL(url string) *UserToImport {
return u.set("photoUrl", url)
}
// PhoneNumber setter.
func (u *UserToImport) PhoneNumber(phoneNumber string) *UserToImport {
return u.set("phoneNumber", phoneNumber)
}
// Metadata setter.
func (u *UserToImport) Metadata(metadata *UserMetadata) *UserToImport {
u.set("createdAt", metadata.CreationTimestamp)
return u.set("lastLoginAt", metadata.LastLogInTimestamp)
}
// CustomClaims setter.
func (u *UserToImport) CustomClaims(claims map[string]interface{}) *UserToImport {
return u.set("customClaims", claims)
}
// Disabled setter.
func (u *UserToImport) Disabled(disabled bool) *UserToImport {
return u.set("disabled", disabled)
}
// EmailVerified setter.
func (u *UserToImport) EmailVerified(emailVerified bool) *UserToImport {
return u.set("emailVerified", emailVerified)
}
// PasswordHash setter. When set, a UserImportHash must be specified as an option to call
// ImportUsers().
func (u *UserToImport) PasswordHash(password []byte) *UserToImport {
return u.set("passwordHash", base64.RawURLEncoding.EncodeToString(password))
}
// PasswordSalt setter.
func (u *UserToImport) PasswordSalt(salt []byte) *UserToImport {
return u.set("salt", base64.RawURLEncoding.EncodeToString(salt))
}
func (u *UserToImport) set(key string, value interface{}) *UserToImport {
if u.params == nil {
u.params = make(map[string]interface{})
}
u.params[key] = value
return u
}
// UserProvider represents a user identity provider.
//
// One or more user providers can be specified for each user when importing in bulk.
// See UserToImport type.
type UserProvider struct {
UID string `json:"rawId"`
ProviderID string `json:"providerId"`
Email string `json:"email"`
DisplayName string `json:"displayName"`
PhotoURL string `json:"photoUrl"`
}
// ProviderData setter.
func (u *UserToImport) ProviderData(providers []*UserProvider) *UserToImport {
return u.set("providerUserInfo", providers)
}
func (u *UserToImport) validatedUserInfo() (map[string]interface{}, error) {
if len(u.params) == 0 {
return nil, fmt.Errorf("no parameters are set on the user to import")
}
info := make(map[string]interface{})
for k, v := range u.params {
info[k] = v
}
if err := validateUID(info["localId"].(string)); err != nil {
return nil, err
}
if email, ok := info["email"]; ok {
if err := validateEmail(email.(string)); err != nil {
return nil, err
}
}
if phone, ok := info["phoneNumber"]; ok {
if err := validatePhone(phone.(string)); err != nil {
return nil, err
}
}
if claims, ok := info["customClaims"]; ok {
claimsMap := claims.(map[string]interface{})
if len(claimsMap) > 0 {
cc, err := marshalCustomClaims(claimsMap)
if err != nil {
return nil, err
}
info["customAttributes"] = cc
}
delete(info, "customClaims")
}
if providers, ok := info["providerUserInfo"]; ok {
for _, p := range providers.([]*UserProvider) {
if p.UID == "" {
return nil, fmt.Errorf("user provdier must specify a uid")
}
if p.ProviderID == "" {
return nil, fmt.Errorf("user provider must specify a provider ID")
}
}
}
return info, nil
}
// WithHash returns a UserImportOption that specifies a hash configuration.
func WithHash(hash UserImportHash) UserImportOption {
return withHash{hash}
}
// UserImportHash represents a hash algorithm and the associated configuration that can be used to
// hash user passwords.
//
// A UserImportHash must be specified in the form of a UserImportOption when importing users with
// passwords. See ImportUsers() and WithHash() functions.
type UserImportHash interface {
Config() (internal.HashConfig, error)
}
type withHash struct {
hash UserImportHash
}
func (w withHash) applyTo(req map[string]interface{}) error {
conf, err := w.hash.Config()
if err != nil {
return err
}
for k, v := range conf {
req[k] = v
}
return nil
}