forked from firebase/firebase-admin-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
219 lines (190 loc) · 6.52 KB
/
db.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
// Copyright 2018 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 db contains functions for accessing the Firebase Realtime Database.
package db
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"runtime"
"strings"
"github.com/armando1793/firebase-admin-go/internal"
"golang.org/x/oauth2"
"google.golang.org/api/option"
)
const userAgentFormat = "Firebase/HTTP/%s/%s/AdminGo"
const invalidChars = "[].#$"
const authVarOverride = "auth_variable_override"
const emulatorDatabaseEnvVar = "FIREBASE_DATABASE_EMULATOR_HOST"
const emulatorNamespaceParam = "ns"
// errInvalidURL tells whether the given database url is invalid
// It is invalid if it is malformed, or not of the format "host:port"
var errInvalidURL = errors.New("invalid database url")
var emulatorToken = &oauth2.Token{
AccessToken: "owner",
}
// Client is the interface for the Firebase Realtime Database service.
type Client struct {
hc *internal.HTTPClient
dbURLConfig *dbURLConfig
authOverride string
}
type dbURLConfig struct {
// BaseURL can be either:
// - a production url (https://foo-bar.firebaseio.com/)
// - an emulator url (http://localhost:9000)
BaseURL string
// Namespace is used in for the emulator to specify the databaseName
// To specify a namespace on your url, pass ns=<database_name> (localhost:9000/?ns=foo-bar)
Namespace string
}
// NewClient creates a new instance of the Firebase Database Client.
//
// This function can only be invoked from within the SDK. Client applications should access the
// Database service through firebase.App.
func NewClient(ctx context.Context, c *internal.DatabaseConfig) (*Client, error) {
urlConfig, isEmulator, err := parseURLConfig(c.URL)
if err != nil {
return nil, err
}
var ao []byte
if c.AuthOverride == nil || len(c.AuthOverride) > 0 {
ao, err = json.Marshal(c.AuthOverride)
if err != nil {
return nil, err
}
}
opts := append([]option.ClientOption{}, c.Opts...)
if isEmulator {
ts := oauth2.StaticTokenSource(emulatorToken)
opts = append(opts, option.WithTokenSource(ts))
}
ua := fmt.Sprintf(userAgentFormat, c.Version, runtime.Version())
opts = append(opts, option.WithUserAgent(ua))
hc, _, err := internal.NewHTTPClient(ctx, opts...)
if err != nil {
return nil, err
}
hc.CreateErrFn = handleRTDBError
return &Client{
hc: hc,
dbURLConfig: urlConfig,
authOverride: string(ao),
}, nil
}
// NewRef returns a new database reference representing the node at the specified path.
func (c *Client) NewRef(path string) *Ref {
segs := parsePath(path)
key := ""
if len(segs) > 0 {
key = segs[len(segs)-1]
}
return &Ref{
Key: key,
Path: "/" + strings.Join(segs, "/"),
client: c,
segs: segs,
}
}
func (c *Client) sendAndUnmarshal(
ctx context.Context, req *internal.Request, v interface{}) (*internal.Response, error) {
if strings.ContainsAny(req.URL, invalidChars) {
return nil, fmt.Errorf("invalid path with illegal characters: %q", req.URL)
}
req.URL = fmt.Sprintf("%s%s.json", c.dbURLConfig.BaseURL, req.URL)
if c.authOverride != "" {
req.Opts = append(req.Opts, internal.WithQueryParam(authVarOverride, c.authOverride))
}
if c.dbURLConfig.Namespace != "" {
req.Opts = append(req.Opts, internal.WithQueryParam(emulatorNamespaceParam, c.dbURLConfig.Namespace))
}
return c.hc.DoAndUnmarshal(ctx, req, v)
}
func parsePath(path string) []string {
var segs []string
for _, s := range strings.Split(path, "/") {
if s != "" {
segs = append(segs, s)
}
}
return segs
}
func handleRTDBError(resp *internal.Response) error {
err := internal.NewFirebaseError(resp)
var p struct {
Error string `json:"error"`
}
json.Unmarshal(resp.Body, &p)
if p.Error != "" {
err.String = fmt.Sprintf("http error status: %d; reason: %s", resp.Status, p.Error)
}
return err
}
// parseURLConfig returns the dbURLConfig for the database
// dbURL may be either:
// - a production url (https://foo-bar.firebaseio.com/)
// - an emulator URL (localhost:9000/?ns=foo-bar)
//
// The following rules will apply for determining the output:
// - If the url does not use an https scheme it will be assumed to be an emulator url and be used.
// - else If the FIREBASE_DATABASE_EMULATOR_HOST environment variable is set it will be used.
// - else the url will be assumed to be a production url and be used.
func parseURLConfig(dbURL string) (*dbURLConfig, bool, error) {
parsedURL, err := url.ParseRequestURI(dbURL)
if err == nil && parsedURL.Scheme != "https" {
cfg, err := parseEmulatorHost(dbURL, parsedURL)
return cfg, true, err
}
environmentEmulatorURL := os.Getenv(emulatorDatabaseEnvVar)
if environmentEmulatorURL != "" {
parsedURL, err = url.ParseRequestURI(environmentEmulatorURL)
if err != nil {
return nil, false, fmt.Errorf("%s: %w", environmentEmulatorURL, errInvalidURL)
}
cfg, err := parseEmulatorHost(environmentEmulatorURL, parsedURL)
return cfg, true, err
}
if err != nil {
return nil, false, fmt.Errorf("%s: %w", dbURL, errInvalidURL)
}
return &dbURLConfig{
BaseURL: dbURL,
Namespace: "",
}, false, nil
}
func parseEmulatorHost(rawEmulatorHostURL string, parsedEmulatorHost *url.URL) (*dbURLConfig, error) {
if strings.Contains(rawEmulatorHostURL, "//") {
return nil, fmt.Errorf(`invalid %s: "%s". It must follow format "host:port": %w`, emulatorDatabaseEnvVar, rawEmulatorHostURL, errInvalidURL)
}
baseURL := strings.Replace(rawEmulatorHostURL, fmt.Sprintf("?%s", parsedEmulatorHost.RawQuery), "", -1)
if parsedEmulatorHost.Scheme != "http" {
baseURL = fmt.Sprintf("http://%s", baseURL)
}
namespace := parsedEmulatorHost.Query().Get(emulatorNamespaceParam)
if namespace == "" {
if strings.Contains(rawEmulatorHostURL, ".") {
namespace = strings.Split(rawEmulatorHostURL, ".")[0]
}
if namespace == "" {
return nil, fmt.Errorf(`invalid database URL: "%s". Database URL must be a valid URL to a Firebase Realtime Database instance (include ?ns=<db-name> query param)`, parsedEmulatorHost)
}
}
return &dbURLConfig{
BaseURL: baseURL,
Namespace: namespace,
}, nil
}