-
Notifications
You must be signed in to change notification settings - Fork 2
/
plugin_test.go
363 lines (341 loc) · 8.29 KB
/
plugin_test.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
356
357
358
359
360
361
362
363
package pocketbase_plugin_telegram_auth
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/tests"
)
const testDataDir = "./test/test_pb_data"
func TestPlugin_Validate(t *testing.T) {
type fields struct {
app core.App
options *Options
}
scenarios := []struct {
name string
fields fields
wantErr bool
}{
{
name: "Options is nil",
fields: fields{
app: nil,
options: nil,
},
wantErr: true,
},
{
name: "Options is empty",
fields: fields{
app: nil,
options: &Options{},
},
wantErr: true,
},
{
name: "Options BotToken is empty",
fields: fields{
app: nil,
options: &Options{
BotToken: "",
CollectionKey: "users",
},
},
wantErr: true,
},
{
name: "Options CollectionKey is empty",
fields: fields{
app: nil,
options: &Options{
BotToken: "BOT_TOKEN",
CollectionKey: "",
},
},
wantErr: true,
},
{
name: "Options is filled",
fields: fields{
app: nil,
options: &Options{
BotToken: "BOT_TOKEN",
CollectionKey: "users",
},
},
wantErr: false,
},
}
for _, tt := range scenarios {
t.Run(tt.name, func(t *testing.T) {
p := &Plugin{
app: tt.fields.app,
options: tt.fields.options,
}
if err := p.Validate(); (err != nil) != tt.wantErr {
t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestPlugin_GetCollection(t *testing.T) {
testApp, err := tests.NewTestApp(testDataDir)
if err != nil {
t.Fatal("Cannot initialize test app", err)
}
defer testApp.Cleanup()
type fields struct {
app core.App
options *Options
collection *models.Collection
}
scenarios := []struct {
name string
fields fields
wantErr bool
collectionNil bool
}{
{
name: "Collection not exists",
fields: fields{
app: testApp,
options: &Options{
CollectionKey: "invalid_collection",
},
},
wantErr: true,
collectionNil: true,
},
{
name: "Collection stored in plugin",
fields: fields{
app: testApp,
options: &Options{
CollectionKey: "invalid_collection",
},
collection: &models.Collection{},
},
wantErr: false,
collectionNil: false,
},
{
name: "Collection exists",
fields: fields{
app: testApp,
options: &Options{
CollectionKey: "users",
},
},
wantErr: false,
collectionNil: false,
},
}
for _, tt := range scenarios {
t.Run(tt.name, func(t *testing.T) {
p := &Plugin{
app: tt.fields.app,
options: tt.fields.options,
collection: tt.fields.collection,
}
if collection, err := p.GetCollection(); (err != nil) != tt.wantErr {
t.Errorf("getCollection() error = %v, wantErr %v", err, tt.wantErr)
} else if collection == nil && !tt.collectionNil {
t.Errorf("getCollection() collection is nil")
}
})
}
}
func TestPlugin_GetForm(t *testing.T) {
testApp, err := tests.NewTestApp(testDataDir)
if err != nil {
t.Fatal("Cannot initialize test app", err)
}
defer testApp.Cleanup()
type fields struct {
app core.App
options *Options
}
scenarios := []struct {
name string
fields fields
wantErr bool
}{
{
name: "Collection not exists",
fields: fields{
app: testApp,
options: &Options{
CollectionKey: "invalid_collection",
},
},
wantErr: true,
},
{
name: "Collection not auth",
fields: fields{
app: testApp,
options: &Options{
CollectionKey: "not_auth_collection",
},
},
wantErr: true,
},
{
name: "Collection is valid",
fields: fields{
app: testApp,
options: &Options{
CollectionKey: "users",
},
},
wantErr: false,
},
}
for _, tt := range scenarios {
t.Run(tt.name, func(t *testing.T) {
p := &Plugin{
app: tt.fields.app,
options: tt.fields.options,
}
if _, err := p.GetForm(nil); (err != nil) != tt.wantErr {
t.Errorf("getCollection() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestPlugin_MustRegister(t *testing.T) {
// setup the test ApiScenario app instance
setupTestApp := func(options *Options) func(*testing.T) *tests.TestApp {
return func(t *testing.T) *tests.TestApp {
testApp, err := tests.NewTestApp(testDataDir)
if err != nil {
t.Fatalf("Cannot initialize test app: %v", err)
return nil
}
MustRegister(testApp, options)
return testApp
}
}
scenarios := []tests.ApiScenario{
{
Name: "Collection not exists",
Method: http.MethodPost,
Url: "/api/collections/invalid_collection/auth-with-telegram",
ExpectedStatus: 404,
ExpectedContent: []string{`{"code":404,"message":"Collection not found.","data":{}}`},
TestAppFactory: setupTestApp(&Options{
CollectionKey: "invalid_collection",
BotToken: "test_bot_token",
}),
},
{
Name: "Collection not auth type",
Method: http.MethodPost,
Url: "/api/collections/not_auth_collection/auth-with-telegram",
ExpectedStatus: 400,
ExpectedContent: []string{`{"code":400,"message":"Wrong collection type. not_auth_collection should be auth collection.","data":{}}`},
TestAppFactory: setupTestApp(&Options{
CollectionKey: "not_auth_collection",
BotToken: "test_bot_token",
}),
},
{
Name: "Data is empty",
Method: http.MethodPost,
Url: "/api/collections/users/auth-with-telegram",
ExpectedStatus: 400,
ExpectedContent: []string{`{"code":400,"message":"Failed to authenticate.","data":{"data":{"code":"validation_required","message":"Cannot be blank."}}}`},
TestAppFactory: setupTestApp(&Options{
CollectionKey: "users",
BotToken: "test_bot_token",
}),
},
{
Name: "Valid data user not exists",
Method: http.MethodPost,
Url: "/api/collections/users/auth-with-telegram",
Body: getBodyFromTgTestData(tgTestData{
QueryId: "test_query_id",
AuthDate: 1,
User: tgUser{
Id: 1,
FirstName: "test_first_name",
LastName: "test_last_name",
Username: "test_username",
LanguageCode: "test_language",
},
}, "test_bot_token"),
ExpectedStatus: 200,
ExpectedContent: []string{`{"meta":{"id":"1","name":"test_first_name test_last_name","username":"test_username"`},
ExpectedEvents: map[string]int{"OnModelAfterCreate": 2, "OnModelBeforeCreate": 2, "OnRecordAuthRequest": 1},
TestAppFactory: setupTestApp(&Options{
CollectionKey: "users",
BotToken: "test_bot_token",
}),
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
type tgTestData struct {
QueryId string `json:"query_id"`
User tgUser `json:"user"`
AuthDate int `json:"auth_date"`
Hash string `json:"hash"`
}
type tgUser struct {
Id int `json:"id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Username string `json:"username"`
LanguageCode string `json:"language_code"`
}
func (u *tgUser) json() string {
jsonData, _ := json.Marshal(u)
return string(jsonData)
}
func (u *tgUser) encode() string {
return url.QueryEscape(u.json())
}
func getBodyFromTgTestData(data tgTestData, botToken string) io.Reader {
genHash, err := getWebappHash(data, botToken)
if err != nil {
panic(err)
}
return strings.NewReader(fmt.Sprintf(`{"data": "query_id=%s&user=%s&auth_date=%d&hash=%s"}`, data.QueryId, data.User.encode(), data.AuthDate, genHash))
}
func getWebappHash(data tgTestData, token string) (string, error) {
strs := []string{
fmt.Sprintf("auth_date=%d", data.AuthDate),
fmt.Sprintf("user=%s", data.User.json()),
fmt.Sprintf("query_id=%s", data.QueryId),
}
sort.Strings(strs)
var imploded = ""
for _, s := range strs {
if imploded != "" {
imploded += "\n"
}
imploded += s
}
secretKey := hmac.New(sha256.New, []byte("WebAppData"))
if _, err := io.WriteString(secretKey, token); err != nil {
return "", err
}
resultHash := hmac.New(sha256.New, secretKey.Sum(nil))
if _, err := io.WriteString(resultHash, imploded); err != nil {
return "", err
}
return hex.EncodeToString(resultHash.Sum(nil)), nil
}