/
user.go
194 lines (181 loc) · 5.51 KB
/
user.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
package mongo
import (
"context"
"crypto/rand"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/reearth/reearth-marketplace/server/internal/infrastrcture/mongo/mongodoc"
"github.com/reearth/reearth-marketplace/server/internal/usecase/repo"
"github.com/reearth/reearth-marketplace/server/pkg/id"
"github.com/reearth/reearth-marketplace/server/pkg/user"
"github.com/reearth/reearthx/mongox"
"github.com/samber/lo"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"golang.org/x/text/language"
)
type userRepo struct {
client *mongox.ClientCollection
}
func NewUser(client *mongox.Client) repo.User {
r := &userRepo{client: client.WithCollection("user")}
r.init()
return r
}
func (u *userRepo) init() {
ctx := context.Background()
initIndexes(
ctx,
u.client,
nil,
[]string{"id", "oidcSub"},
)
lo.Must(u.client.Client().Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.D{{Key: "name", Value: 1}},
Options: options.Index().
SetUnique(true).
SetPartialFilterExpression(bson.M{"name": bson.M{"$gt": ""}}),
}))
}
func (u *userRepo) FindOrCreate(ctx context.Context, authInfo repo.AuthInfo) (*user.User, error) {
oidcSub := authInfo.Sub
newUser, err := user.New().
NewID().
Auth(user.AuthFromOIDCSub(oidcSub)).
Lang(language.Und).
Build()
if err != nil {
return nil, fmt.Errorf("new user: %w", err)
}
var userDoc mongodoc.UserDocument
newUserDoc, _ := mongodoc.NewUser(newUser)
if err := u.client.Client().
FindOneAndUpdate(ctx,
bson.M{"oidcSub": oidcSub},
bson.M{"$setOnInsert": newUserDoc},
options.FindOneAndUpdate().SetUpsert(true).SetReturnDocument(options.After),
).
Decode(&userDoc); err != nil {
return nil, fmt.Errorf("find user: %w", err)
}
isNewUser := userDoc.Name == ""
if isNewUser {
userName, err := makeInitialUserName(ctx, authInfo)
if err != nil {
return nil, fmt.Errorf("make initial user name: %w", err)
}
userDoc.Name = userName
if err := u.client.SaveOne(ctx, userDoc.ID, userDoc); err != nil {
if !mongo.IsDuplicateKeyError(err) {
return nil, fmt.Errorf("set initial user name: %w", err)
}
// fallback: use random user name
randomUserName, err := user.RandomName(rand.Reader, 8)
if err != nil {
return nil, fmt.Errorf("get random initial user name: %w", err)
}
userDoc.Name = randomUserName
if err := u.client.SaveOne(ctx, userDoc.ID, userDoc); err != nil {
return nil, fmt.Errorf("set random initial user name: %w", err)
}
}
}
return userDoc.Model()
}
func (u *userRepo) FindByIDs(ctx context.Context, ids id.UserIDList) ([]*user.User, error) {
if len(ids) == 0 {
return nil, nil
}
filter := bson.M{
"id": bson.M{
"$in": ids.Strings(),
},
}
c := mongodoc.UserConsumer{
Rows: make([]*user.User, 0, len(ids)),
}
if err := u.client.Find(ctx, filter, &c); err != nil {
return nil, err
}
return c.Rows, nil
}
func (u *userRepo) SaveAll(ctx context.Context, users []*user.User) error {
ids, docs := mongodoc.NewUsers(users)
if err := u.client.SaveAll(ctx, ids, docs); err != nil {
return err
}
return nil
}
func (u *userRepo) Save(ctx context.Context, user *user.User) error {
doc, uid := mongodoc.NewUser(user)
if err := u.client.SaveOne(ctx, uid, doc); err != nil {
return err
}
return nil
}
func makeInitialUserName(ctx context.Context, authInfo repo.AuthInfo) (string, error) {
userInfoEndpoint, err := resolveUserInfoEndpoint(ctx, authInfo.Iss)
if err != nil {
return "", fmt.Errorf("resolve userinfo_endpoint: %w", err)
}
ui, err := fetchUserInfo(ctx, userInfoEndpoint, authInfo.Token)
if err != nil {
return "", fmt.Errorf("fetch user name: %w", err)
}
if user.IsSafeName(ui.Name) {
return ui.Name, nil
}
// fallback: use local-part of email as user name
userName, _, _ := strings.Cut(ui.Email, "@")
if user.IsSafeName(userName) {
return userName, nil
}
return "", fmt.Errorf("cannot make valid initial user name")
}
func resolveUserInfoEndpoint(ctx context.Context, iss string) (string, error) {
configURL, err := url.JoinPath(iss, "/.well-known/openid-configuration")
if err != nil {
return "", fmt.Errorf("unsupported issuer: %w", err)
}
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, configURL, nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", fmt.Errorf("get openid-configuration: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("get openid-configuration: unexpected status: %d", resp.StatusCode)
}
var oidConfiguration struct {
UserInfoEndpoint string `json:"userinfo_endpoint"`
}
if err := json.NewDecoder(resp.Body).Decode(&oidConfiguration); err != nil {
return "", fmt.Errorf("get openid-configuration: invalid json: %w", err)
}
return oidConfiguration.UserInfoEndpoint, nil
}
type userInfo struct {
Name string `json:"name"`
Email string `json:"email"`
}
func fetchUserInfo(ctx context.Context, userInfoEndpoint string, token string) (*userInfo, error) {
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, userInfoEndpoint, nil)
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("get userinfo: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("get userinfo: unexpected status: %d", resp.StatusCode)
}
var ui userInfo
if err := json.NewDecoder(resp.Body).Decode(&ui); err != nil {
return nil, fmt.Errorf("get userinfo: invalid json: %w", err)
}
return &ui, nil
}