-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoauth2.go
83 lines (69 loc) · 2.13 KB
/
oauth2.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
package main
import (
"fmt"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/types"
)
func (m *Migrator) MigrateUsersOAuth2() error {
collection, err := m.pbApp.FindCollectionByNameOrId("users")
if err != nil {
return err
}
// check for older duplicates to ignore from the import
// (in PocketBase a single auth record can be linked to only one OAuth2 account from the same provider).
toIgnore := []string{}
toIgnoreErr := m.oldDB.Select("min(id)").
From("UserAuth").
GroupBy("userId", "source").
Having(dbx.NewExp("count(id) > 1")).
Column(&toIgnore)
if toIgnoreErr != nil {
return fmt.Errorf("failed to fetch UserAuth duplicates: %w", toIgnoreErr)
}
limit := 1000
items := make([]*v2UserAuth, 0, limit)
for i := 0; ; i++ {
q := m.oldDB.Select("*").
From("UserAuth").
OrderBy("id asc").
Where(dbx.NotIn("id", list.ToInterfaceSlice(toIgnore)...)).
Limit(int64(limit)).
Offset(int64(i * limit))
if err := q.All(&items); err != nil {
return err
}
for _, item := range items {
itemId := fmt.Sprintf("%s%d", v2Prefix, item.Id)
var ea *core.ExternalAuth
if ea, _ = m.pbApp.FindFirstExternalAuthByExpr(dbx.HashExp{"id": itemId}); ea != nil {
// already migrated -> check its updated date for changes
updated, _ := types.ParseDateTime(item.UpdatedAt)
if updated.Time().Unix() == ea.GetDateTime("updated").Time().Unix() {
continue
}
} else {
ea = core.NewExternalAuth(m.pbApp)
ea.MarkAsNew()
ea.Id = itemId
}
createdAt, _ := types.ParseDateTime(item.CreatedAt)
ea.SetRaw("created", createdAt)
updatedAt, _ := types.ParseDateTime(item.UpdatedAt)
ea.SetRaw("updated", updatedAt)
ea.SetCollectionRef(collection.Id)
ea.SetRecordRef(fmt.Sprintf("%s%d", v2Prefix, item.UserId))
ea.SetProvider(item.Source)
ea.SetProviderId(item.SourceId)
if err := m.pbApp.SaveNoValidate(ea); err != nil {
return fmt.Errorf("failed to save %q: %w", ea.Id, err)
}
}
if len(items) < limit {
break // no more items
}
items = items[:0]
}
return nil
}