This repository has been archived by the owner on Jul 12, 2023. It is now read-only.
/
firebase.go
355 lines (305 loc) · 10.4 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
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
// Copyright 2020 Google LLC
//
// 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"
"fmt"
firebaseinternal "github.com/google/exposure-notifications-verification-server/internal/firebase"
"github.com/sethvargo/go-password/password"
firebase "firebase.google.com/go"
"firebase.google.com/go/auth"
"github.com/gorilla/sessions"
)
const (
sessionKeyFirebaseCookie = sessionKey("firebaseCookie")
)
type firebaseAuth struct {
firebaseAuth *auth.Client
firebaseInternal *firebaseinternal.Client
}
// NewFirebase creates a new auth provider for firebase.
func NewFirebase(ctx context.Context, config *firebase.Config) (Provider, error) {
app, err := firebase.NewApp(ctx, config)
if err != nil {
return nil, fmt.Errorf("failed to create firebase app: %w", err)
}
auth, err := app.Auth(ctx)
if err != nil {
return nil, fmt.Errorf("failed to configure firebase auth: %w", err)
}
internal, err := firebaseinternal.New(ctx)
if err != nil {
return nil, fmt.Errorf("failed to configure firebase client: %w", err)
}
return &firebaseAuth{
firebaseAuth: auth,
firebaseInternal: internal,
}, nil
}
// CheckRevoked checks if the users auth has been revoked.
func (f *firebaseAuth) CheckRevoked(ctx context.Context, session *sessions.Session) error {
raw, err := sessionGet(session, sessionKeyFirebaseCookie)
if err != nil {
f.ClearSession(ctx, session)
return err
}
cookie, ok := raw.(string)
if !ok || cookie == "" {
f.ClearSession(ctx, session)
return ErrSessionMissing
}
if _, err := f.firebaseAuth.VerifySessionCookieAndCheckRevoked(ctx, cookie); err != nil {
f.ClearSession(ctx, session)
return err
}
return nil
}
// StoreSession stores information about the session.
func (f *firebaseAuth) StoreSession(ctx context.Context, session *sessions.Session, i *SessionInfo) error {
if i == nil || i.Data == nil {
f.ClearSession(ctx, session)
return ErrSessionInfoMissing
}
idToken, ok := i.Data["id_token"].(string)
if !ok {
f.ClearSession(ctx, session)
return fmt.Errorf("missing id_token: %w", ErrSessionInfoMissing)
}
// Convert ID token to long-lived cookie
cookie, err := f.firebaseAuth.SessionCookie(ctx, idToken, i.TTL)
if err != nil {
f.ClearSession(ctx, session)
return err
}
// Set cookie
if err := sessionSet(session, sessionKeyFirebaseCookie, cookie); err != nil {
f.ClearSession(ctx, session)
return err
}
return nil
}
// ClearSession removes any session information for this auth.
func (f *firebaseAuth) ClearSession(ctx context.Context, session *sessions.Session) {
sessionClear(session, sessionKeyFirebaseCookie)
}
// CreateUser creates a user in the upstream auth system with the given name and
// email. It returns true if the user was created or false if the user already
// exists.
func (f *firebaseAuth) CreateUser(ctx context.Context, name, email, pass string, emailer InviteUserEmailFunc) (bool, error) {
// Attempt to get the user by email. If that returns successfully, it means
// the user exists.
user, err := f.firebaseAuth.GetUserByEmail(ctx, email)
if err != nil && !auth.IsUserNotFound(err) {
return false, fmt.Errorf("failed lookup firebase user: %w", err)
}
if user == nil {
// If the password is empty, generate one.
if pass == "" {
pass, err = password.Generate(24, 8, 8, false, true)
if err != nil {
return false, fmt.Errorf("failed to generate password: %w", err)
}
}
// Create the user.
userToCreate := (&auth.UserToCreate{}).
Email(email).
Password(pass).
DisplayName(name)
if _, err = f.firebaseAuth.CreateUser(ctx, userToCreate); err != nil {
return false, fmt.Errorf("failed to create firebase user: %w", err)
}
}
// Send the welcome email. Use the defined mailer if given, otherwise fallback
// to firebase default.
if emailer != nil {
inviteLink, err := f.passwordResetLink(ctx, email)
if err != nil {
return true, err
}
if err := emailer(ctx, inviteLink); err != nil {
return true, fmt.Errorf("failed to send new user invitation email: %w", err)
}
} else {
if err := f.firebaseInternal.SendNewUserInvitation(ctx, email); err != nil {
return true, fmt.Errorf("failed to send new user invitation firebase email: %w", err)
}
}
return true, nil
}
// EmailAddress extracts the users email from the session.
func (f *firebaseAuth) EmailAddress(ctx context.Context, session *sessions.Session) (string, error) {
data, err := f.loadCookie(ctx, session)
if err != nil {
return "", err
}
return data.Email, nil
}
// EmailVerified returns true if the current user is verified, false otherwise.
func (f *firebaseAuth) EmailVerified(ctx context.Context, session *sessions.Session) (bool, error) {
data, err := f.loadCookie(ctx, session)
if err != nil {
return false, err
}
return data.EmailVerified, nil
}
// MFAEnabled returns whether MFA is enabled on the account.
func (f *firebaseAuth) MFAEnabled(ctx context.Context, session *sessions.Session) (bool, error) {
data, err := f.loadCookie(ctx, session)
if err != nil {
return false, err
}
return data.MFAEnabled, nil
}
// ChangePassword changes the users password. The data must be an oobCode as a
// string.
func (f *firebaseAuth) ChangePassword(ctx context.Context, newPassword string, data interface{}) error {
code, ok := data.(string)
if !ok {
return fmt.Errorf("missing or invalid oobCode")
}
if _, err := f.firebaseInternal.ChangePasswordWithCode(ctx, code, newPassword); err != nil {
return err
}
return nil
}
// SendResetPasswordEmail resets the password for the given user. If the user does not
// exist, an error is returned.
func (f *firebaseAuth) SendResetPasswordEmail(ctx context.Context, email string, emailer ResetPasswordEmailFunc) error {
// Send the reset email. Use SMTP emailer if defined, otherwise fallback to
// the firebase default mailer.
if emailer != nil {
resetLink, err := f.passwordResetLink(ctx, email)
if err != nil {
return err
}
if err := emailer(ctx, resetLink); err != nil {
return fmt.Errorf("failed to send password reset email: %w", err)
}
} else {
if err := f.firebaseInternal.SendNewUserInvitation(ctx, email); err != nil {
return fmt.Errorf("failed to send password reset firebase email: %w", err)
}
}
return nil
}
// VerifyPasswordResetCode verifies the password reset code and returns the
// email address for the user.
func (f *firebaseAuth) VerifyPasswordResetCode(ctx context.Context, code string) (string, error) {
email, err := f.firebaseInternal.VerifyPasswordResetCode(ctx, code)
if err != nil {
return "", err
}
return email, nil
}
// SendEmailVerificationEmail sends an message to the currently authenticated
// user, asking them to verify ownership of the email address.
func (f *firebaseAuth) SendEmailVerificationEmail(ctx context.Context, email string, data interface{}, emailer EmailVerificationEmailFunc) error {
// Send the reset email. Use SMTP emailer if defined, otherwise fallback to
// the firebase default mailer.
if emailer != nil {
verifyLink, err := f.emailVerificationLink(ctx, email)
if err != nil {
return err
}
if err := emailer(ctx, verifyLink); err != nil {
return fmt.Errorf("failed to send email verification email: %w", err)
}
} else {
if data == nil {
return fmt.Errorf("firebase requires a fresh ID token to send email verifications")
}
idToken, ok := data.(string)
if !ok {
return fmt.Errorf("id token must be a string")
}
if err := f.firebaseInternal.SendEmailVerification(ctx, idToken); err != nil {
return fmt.Errorf("failed to send email verification firebase email: %w", err)
}
}
return nil
}
// passwordResetLink generates and returns the password reset link for the given
// email (user).
func (f *firebaseAuth) passwordResetLink(ctx context.Context, email string) (string, error) {
reset, err := f.firebaseAuth.PasswordResetLink(ctx, email)
if err != nil {
return "", fmt.Errorf("failed to generate password reset link: %w", err)
}
return reset, nil
}
// emailVerificationLink generates an email verification link for the given
// email.
func (f *firebaseAuth) emailVerificationLink(ctx context.Context, email string) (string, error) {
verify, err := f.firebaseAuth.EmailVerificationLink(ctx, email)
if err != nil {
return "", fmt.Errorf("failed to generate email verification link: %w", err)
}
return verify, nil
}
type firebaseCookieData struct {
Email string
EmailVerified bool
MFAEnabled bool
}
// dataFromCookie extracts the information from the provided firebase cookie, if
// it exists.
func (f *firebaseAuth) dataFromCookie(ctx context.Context, cookie string) (*firebaseCookieData, error) {
token, err := f.firebaseAuth.VerifySessionCookie(ctx, cookie)
if err != nil {
return nil, fmt.Errorf("failed to verify firebase cookie: %w", err)
}
if token.Claims == nil {
return nil, fmt.Errorf("token claims are empty")
}
// Email
email, ok := token.Claims["email"].(string)
if !ok {
return nil, fmt.Errorf("token claims for email are not a string")
}
// Email verified
emailVerified, ok := token.Claims["email_verified"].(bool)
if !ok {
return nil, fmt.Errorf("token claims for email_verified are not a bool")
}
// MFA
firebase, ok := token.Claims["firebase"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("token claims for firebase are missing")
}
_, mfaEnabled := firebase["sign_in_second_factor"]
return &firebaseCookieData{
Email: email,
EmailVerified: emailVerified,
MFAEnabled: mfaEnabled,
}, nil
}
// loadCookie loads and parses the firebase cookie from the session.
func (f *firebaseAuth) loadCookie(ctx context.Context, session *sessions.Session) (*firebaseCookieData, error) {
raw, err := sessionGet(session, sessionKeyFirebaseCookie)
if err != nil {
f.ClearSession(ctx, session)
return nil, err
}
cookie, ok := raw.(string)
if !ok || cookie == "" {
f.ClearSession(ctx, session)
return nil, ErrSessionMissing
}
data, err := f.dataFromCookie(ctx, cookie)
if err != nil {
f.ClearSession(ctx, session)
return nil, err
}
return data, nil
}