This repository has been archived by the owner on Jul 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
firebase.go
268 lines (207 loc) · 6.24 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
package firebase
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
firebase "firebase.google.com/go/v4"
"firebase.google.com/go/v4/auth"
"github.com/morning-night-dream/platform-app/internal/adapter/external"
"github.com/morning-night-dream/platform-app/pkg/log"
"google.golang.org/api/option"
)
type Firebase struct{}
func New() *Firebase {
return &Firebase{}
}
func (fb *Firebase) Of(
secret string,
endpoint string,
apiKey string,
) (*external.Auth, error) {
opt := option.WithCredentialsJSON([]byte(secret))
app, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
log.Log().Fatal("error initializing app", log.ErrorField(err))
}
auth, err := app.Auth(context.Background())
if err != nil {
return nil, fmt.Errorf("error create auth client: %w", err)
}
if endpoint == "" {
return nil, fmt.Errorf("firebase api endpoint is empty")
}
if apiKey == "" {
return nil, fmt.Errorf("firebase api key is empty")
}
return &external.Auth{
Endpoint: endpoint,
APIKey: apiKey,
HTTPClient: http.DefaultClient,
FirebaseAuth: auth,
}, nil
}
// TODO 以下は削除して問題ない
// @see https://firebase.google.com/docs/reference/rest/auth
type APIRestClient struct {
*http.Client
Endpoint string
APIKey string
}
type Client struct {
admin *auth.Client
api *APIRestClient
}
func NewClient(secret string, endpoint string, key string) *Client {
opt := option.WithCredentialsJSON([]byte(secret))
app, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
log.Log().Fatal("error initializing app", log.ErrorField(err))
}
admin, err := app.Auth(context.Background())
if err != nil {
log.Log().Fatal("error create auth client", log.ErrorField(err))
}
if endpoint == "" {
log.Log().Fatal("error firebase api endpoint is empty")
}
if key == "" {
log.Log().Fatal("error firebase api key is empty")
}
api := &APIRestClient{
Client: &http.Client{},
Endpoint: endpoint,
APIKey: key,
}
return &Client{
admin: admin,
api: api,
}
}
func (c *Client) CreateUser(ctx context.Context, userID, email, password string) error {
params := (&auth.UserToCreate{}).
UID(userID).
Email(email).
EmailVerified(false).
Password(password).
Disabled(false)
if _, err := c.admin.CreateUser(ctx, params); err != nil {
log.GetLogCtx(ctx).Warn("faile to create user", log.ErrorField(err))
return err
}
return nil
}
type SignInRequest struct {
Email string `json:"email"`
Password string `json:"password"`
ReturnSecureToken bool `json:"returnSecureToken"`
}
type SignInResponse struct {
ExpiresIn string `json:"expiresIn"`
LocalID string `json:"localId"`
IDToken string `json:"idToken"`
RefreshToken string `json:"refreshToken"`
}
func (f *Client) Login(ctx context.Context, email, password string) (SignInResponse, error) {
// https://firebase.google.com/docs/reference/rest/auth#section-sign-in-email-password
url := fmt.Sprintf("%s/v1/accounts:signInWithPassword?key=%s", f.api.Endpoint, f.api.APIKey)
req := SignInRequest{
Email: email,
Password: password,
ReturnSecureToken: true,
}
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(req)
if err != nil {
log.GetLogCtx(ctx).Warn("failed to encode json", log.ErrorField(err))
return SignInResponse{}, err
}
res, err := f.api.Post(url, "application/json", &buf)
if err != nil {
log.GetLogCtx(ctx).Warn("failed to post "+url, log.ErrorField(err))
return SignInResponse{}, err
}
if res.StatusCode != http.StatusOK {
message, err := io.ReadAll(res.Body)
if err != nil {
log.GetLogCtx(ctx).Warn("faile to read body", log.ErrorField(err))
message = []byte(fmt.Sprintf("could not laod message caused by %v", err))
}
return SignInResponse{}, fmt.Errorf("firebase error. status code is %d, message is %v", res.StatusCode, string(message))
}
var response SignInResponse
if err := json.NewDecoder(res.Body).Decode(&response); err != nil {
log.GetLogCtx(ctx).Warn("failed to decode json", log.ErrorField(err))
return SignInResponse{}, err
}
// 試しにfirebaseのセッショントークンを作ってみたコード
// cookie, err := f.admin.SessionCookie(ctx, response.IDToken, time.Hour*24*5)
// if err != nil {
// return SignInResponse{}, err
// }
// log.Printf("session cookie: %s", cookie)
return response, nil
}
type RefreshRequest struct {
GrantType string `json:"grant_type"`
RefreshToken string `json:"refresh_token"`
}
type RefreshResponse struct {
ExpiresIn string `json:"expires_in"`
TokenType string `json:"token_type"`
RefreshToken string `json:"refresh_token"`
IDToken string `json:"id_token"`
UserID string `json:"user_id"`
ProjectID string `json:"project_id"`
}
func (f *Client) RefreshToken(ctx context.Context, refresh string) (string, error) {
// https://firebase.google.com/docs/reference/rest/auth#section-refresh-token
url := fmt.Sprintf("%s/v1/token?key=%s", f.api.Endpoint, f.api.APIKey)
req := RefreshRequest{
GrantType: "refresh_token",
RefreshToken: refresh,
}
var body bytes.Buffer
if err := json.NewEncoder(&body).Encode(req); err != nil {
return "", err
}
res, err := f.api.Post(url, "application/json", &body)
if err != nil {
return "", err
}
if res.StatusCode != http.StatusOK {
message, err := io.ReadAll(res.Body)
if err != nil {
message = []byte(fmt.Sprintf("could not load message caused by %v", err))
}
return "", fmt.Errorf("firebase error. status code is %d, message is %v", res.StatusCode, string(message))
}
var response RefreshResponse
if err := json.NewDecoder(res.Body).Decode(&response); err != nil {
return "", err
}
return response.RefreshToken, nil
}
func (f *Client) ChangePassword(ctx context.Context, uid, password string) error {
params := (&auth.UserToUpdate{}).
Password(password)
if _, err := f.admin.UpdateUser(ctx, uid, params); err != nil {
return err
}
return nil
}
func (f *Client) VerifyIDToken(ctx context.Context, idToken string) error {
_, err := f.admin.VerifyIDToken(ctx, idToken)
if err != nil {
return err
}
return nil
}
func (f *Client) DeleteUser(ctx context.Context, uid string) error {
if err := f.admin.DeleteUser(ctx, uid); err != nil {
return err
}
return nil
}