-
Notifications
You must be signed in to change notification settings - Fork 6
/
user.go
260 lines (225 loc) · 6.89 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
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
/*
Copyright 2021 Adevinta
*/
package store
import (
"strings"
"time"
"github.com/adevinta/errors"
"github.com/adevinta/vulcan-api/pkg/api"
"github.com/adevinta/vulcan-api/pkg/saml"
)
func (db vulcanitoStore) ListUsers() ([]*api.User, error) {
users := []*api.User{}
// Retrieve all teams
result := db.Conn.
Find(&users)
if result.Error != nil {
return nil, db.logError(errors.Database(result.Error))
}
return users, nil
}
// CreateUser inserts a new user in the database
func (db vulcanitoStore) CreateUser(user api.User) (*api.User, error) {
findUser := api.User{}
res := db.Conn.Find(&findUser, "lower(email) = ?", strings.ToLower(user.Email))
if len(findUser.ID) > 0 {
return nil, db.logError(errors.Duplicated("User already exists"))
}
if res.Error != nil {
if !db.NotFoundError(res.Error) {
return nil, db.logError(errors.Database(res.Error))
}
}
user.Email = strings.ToLower(user.Email)
res = db.Conn.Create(&user)
if res.Error != nil {
return nil, db.logError(errors.Create(res.Error))
}
return &user, nil
}
// UpdateUser modifies an existing user in the database
func (db vulcanitoStore) UpdateUser(user api.User) (*api.User, error) {
findUser := user
// Make UpdateUser transactional.
tx := db.Conn.Begin()
if tx.Error != nil {
return nil, db.logError(errors.Database(tx.Error))
}
res := tx.Find(&findUser)
if res.RowsAffected == 0 {
tx.Rollback()
return nil, db.logError(errors.NotFound("User does not exists"))
}
if res.Error != nil {
tx.Rollback()
if db.NotFoundError(res.Error) {
return nil, db.logError(errors.NotFound(res.Error))
}
return nil, db.logError(errors.Database(res.Error))
}
res = tx.Model(user).Update(&user)
if res.Error != nil {
tx.Rollback()
return nil, db.logError(errors.Update(res.Error))
}
// Reload updated user to return the entity properly updated with all fields.
updatedUser := user
res = tx.Find(&updatedUser)
if res.RowsAffected == 0 {
tx.Rollback()
return nil, db.logError(errors.NotFound("User does not exists"))
}
// Commit db transaction
if tx.Commit().Error != nil {
return nil, db.logError(errors.Database(tx.Error))
}
return &updatedUser, nil
}
// CreateUserIfNotExists ...
func (db vulcanitoStore) CreateUserIfNotExists(userData saml.UserData) error {
// Empty user
u := &api.User{}
// TODO: There are race conditions here that we should fix, for instance, if
// a user does not exist two goroutines could check for that in the next
// lines of code and then try to create the user, in which case one of them
// will fail with and unexpected error.
// Search database for a user with the email that Okta returned to us
res := db.Conn.Find(u, "lower(email) = ?", strings.ToLower(userData.Email))
if res.Error != nil {
if !db.NotFoundError(res.Error) {
return db.logError(errors.Database(res.Error))
}
}
now := time.Now()
// If there are no records with that email, then insert a new user.
if res.RowsAffected == 0 {
u.Firstname = userData.FirstName
u.Lastname = userData.LastName
u.Email = strings.ToLower(userData.Email)
u.LastLogin = &now
// Begin db transaction.
tx := db.Conn.Begin()
if tx.Error != nil {
return db.logError(errors.Database(tx.Error))
}
res = tx.Create(u)
if res.Error != nil {
tx.Rollback()
return db.logError(errors.Create(res.Error))
}
// PTVUL-913
// In order to make easier onboard process when a user is created
// we will check if is set as recipient for a team. If is set as
// recipient for a team, it will become member of that team.
// Eventually, we may want to modify this behavior.
r := []api.Recipient{}
recipients := tx.Find(&r, "lower(email) = ?", strings.ToLower(userData.Email))
teamsJoined := []string{}
if recipients.RowsAffected > 0 {
for _, recipient := range r {
membership := &api.UserTeam{
TeamID: recipient.TeamID,
UserID: u.ID,
Role: "member",
}
res = tx.Create(&membership)
teamsJoined = append(teamsJoined, recipient.TeamID)
if res.Error != nil {
tx.Rollback()
return db.logError(errors.Create(res.Error))
}
}
}
// Commit db transaction
if tx.Commit().Error != nil {
return db.logError(errors.Database(tx.Error))
}
if len(teamsJoined) > 0 {
db.logger.Log("user", u.Email, "userID", u.ID, "membership", strings.Join(teamsJoined, ",")) // nolint
}
return nil
}
// res.RowsAffected greater than zero, so we are checking if the attributes
// have changed on Okta
u.LastLogin = &now
if u.Firstname != userData.FirstName ||
u.Lastname != userData.LastName {
u.Firstname = userData.FirstName
u.Lastname = userData.LastName
}
res = db.Conn.Model(u).Update(u)
if res.Error != nil {
return db.logError(errors.Create(res.Error))
}
return nil
}
// FindUserByID query a user by his ID
func (db vulcanitoStore) FindUserByID(userID string) (*api.User, error) {
if userID == "" {
return nil, db.logError(errors.Validation(`ID is empty`))
}
user := &api.User{ID: userID}
res := db.Conn.Find(user)
if res.Error != nil {
if strings.HasPrefix(res.Error.Error(), `pq: invalid input syntax for type uuid`) {
return nil, db.logError(errors.Validation(`ID is malformed`))
}
if !db.NotFoundError(res.Error) {
return nil, db.logError(errors.Database(res.Error))
}
}
if res.RowsAffected == 0 {
return nil, db.logError(errors.NotFound("User does not exists"))
}
return user, nil
}
// FindUserByEmail query a user by his email
func (db vulcanitoStore) FindUserByEmail(email string) (*api.User, error) {
if email == "" {
return nil, db.logError(errors.Validation(`Email is empty`))
}
user := &api.User{}
res := db.Conn.Find(&user, "lower(email) = ?", strings.ToLower(email))
if res.Error != nil {
if !db.NotFoundError(res.Error) {
return nil, db.logError(errors.Database(res.Error))
}
}
if res.RowsAffected == 0 {
return nil, db.logError(errors.NotFound("User does not exists"))
}
return user, nil
}
func (db vulcanitoStore) DeleteUserByID(userID string) error {
if userID == "" {
return db.logError(errors.Validation(`ID is empty`))
}
tx := db.Conn.Begin()
if tx.Error != nil {
return errors.Database(tx.Error)
}
res := tx.Exec("DELETE FROM user_team WHERE user_id=?", userID)
if res.Error != nil && !db.NotFoundError(res.Error) {
// This is arguable in the sense that we could check for an error when
// rollbacking the transaction. We are not doing that because even if a
// transacction is explicitly rolledback postgres will automatically
// rollback it after certain amount of time or when the connection is
// close.
tx.Rollback()
return errors.Database(errors.Database(res.Error))
}
user := &api.User{ID: userID}
res = tx.Delete(user)
err := res.Error
if err != nil {
_ = db.logError(errors.Database(err)) // nolint
}
if res.RowsAffected == 0 {
return db.logError(errors.NotFound("User does not exists"))
}
if err := tx.Commit().Error; err != nil {
return db.logError(errors.Database(err))
}
return nil
}