/
user.go
375 lines (308 loc) · 11.3 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
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
364
365
366
367
368
369
370
371
372
373
374
375
package model
import (
"encoding/json"
"strings"
"time"
"errors"
gh "github.com/google/go-github/github"
"github.com/jinzhu/gorm"
"github.com/tinyci/ci-agents/ci-gen/grpc/types"
"github.com/tinyci/ci-agents/utils"
topTypes "github.com/tinyci/ci-agents/types"
)
// Capability is a type of access gating mechanism. If present on the user
// account access is granted, otherwise not.
type Capability string
const (
// CapabilityModifyCI is required for modifying CI properties such as adding or removing a repo.
CapabilityModifyCI Capability = "modify:ci"
// CapabilityModifyUser allows you to modify users; including caps.
CapabilityModifyUser Capability = "modify:user"
// CapabilitySubmit allows manual submissions
CapabilitySubmit Capability = "submit"
// CapabilityCancel allows cancels
CapabilityCancel Capability = "cancel"
)
var (
// AllCapabilities comprises the superuser account's list of capabilities.
AllCapabilities = []Capability{CapabilityModifyCI, CapabilityModifyUser, CapabilitySubmit, CapabilityCancel}
// TokenCryptKey is the standard token crypt key.
// NOTE: the default is only used by tests; it is overwritten on service boot; see config/auth.go.
TokenCryptKey = []byte{1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8}
)
// UserError is the encapsulation of many errors that need to be presented to
// the user.
type UserError struct {
ID int64 `gorm:"primary key" json:"id"`
UserID int64 `json:"-"`
Error string `json:"error"`
}
// NewUserErrorFromProto converts a user error from proto to canonical representation
func NewUserErrorFromProto(ue *types.UserError) *UserError {
return &UserError{
ID: ue.Id,
UserID: ue.UserID,
Error: ue.Error,
}
}
// ToProto converts the usererror to its protocol buffer representation.
func (ue UserError) ToProto() *types.UserError {
return &types.UserError{
Id: ue.ID,
UserID: ue.UserID,
Error: ue.Error,
}
}
// User is a user record.
type User struct {
ID int64 `gorm:"primary_key" json:"id"`
Username string `gorm:"unique" json:"username"`
LastScannedRepos *time.Time `json:"last_scanned_repos,omitempty"`
Errors []UserError `json:"errors,omitempty"`
Subscribed []*Repository `gorm:"many2many:subscriptions;preload:false" json:"subscribed,omitempty"`
LoginToken []byte `json:"-"`
TokenJSON []byte `gorm:"column:token;not null" json:"-"`
Token *topTypes.OAuthToken `json:"-"`
}
// SetToken sets the token's byte stream, and encrypts it.
func (u *User) SetToken() error {
var err error
u.TokenJSON, err = topTypes.EncryptToken(TokenCryptKey, u.Token)
return err
}
// FetchToken retrieves the token from the db, decrypting it if necessary.
func (u *User) FetchToken() error {
if u.Token != nil {
return nil
}
var err error
u.Token, err = topTypes.DecryptToken(TokenCryptKey, u.TokenJSON)
return err
}
// NewUserFromProto converts a proto user to a real user.
func NewUserFromProto(u *types.User) (*User, error) {
errs := []UserError{}
if len(u.Errors) != 0 {
for _, e := range u.Errors {
errs = append(errs, *NewUserErrorFromProto(e))
}
}
token := &topTypes.OAuthToken{}
if u.TokenJSON != nil {
if err := json.Unmarshal(u.TokenJSON, token); err != nil {
return nil, err
}
}
return &User{
ID: u.Id,
Username: u.Username,
LastScannedRepos: MakeTime(u.LastScannedRepos, true),
Errors: errs,
TokenJSON: u.TokenJSON,
Token: token,
}, nil
}
// MakeUsers converts a proto userlist to a model one.
func MakeUsers(users []*types.User) ([]*User, error) {
ret := []*User{}
for _, user := range users {
u, err := NewUserFromProto(user)
if err != nil {
return nil, err
}
ret = append(ret, u)
}
return ret, nil
}
// MakeUserList returns the inverse of MakeUsers.
func MakeUserList(users []*User) []*types.User {
ret := []*types.User{}
for _, user := range users {
ret = append(ret, user.ToProto())
}
return ret
}
// ToProto converts the user struct to a protobuf capable one
func (u *User) ToProto() *types.User {
errors := []*types.UserError{}
for _, e := range u.Errors {
errors = append(errors, e.ToProto())
}
if u.Token != nil {
u.TokenJSON, _ = json.Marshal(u.Token)
}
return &types.User{
Id: u.ID,
Username: u.Username,
LastScannedRepos: MakeTimestamp(u.LastScannedRepos),
Errors: errors,
TokenJSON: u.TokenJSON,
}
}
// CreateUser initializes a user struct and writes it to the db.
func (m *Model) CreateUser(username string, token *topTypes.OAuthToken) (*User, error) {
u := &User{Username: username, Token: token}
return u, m.WrapError(m.Create(u), "creating user")
}
// FindUserByID finds the user by integer ID.
func (m *Model) FindUserByID(id int64) (*User, error) {
u := &User{}
return u, m.WrapError(m.Where("id = ?", id).First(u), "finding user by id")
}
// FindUserByName finds a user by unique key username.
func (m *Model) FindUserByName(username string) (*User, error) {
u := &User{}
return u, m.WrapError(m.Where("username = ?", username).First(u), "finding user by name")
}
// FindUserByNameWithSubscriptions finds a user by unique key username. It also fetches the subscriptions for the user.
func (m *Model) FindUserByNameWithSubscriptions(username, search string) (*User, error) {
u := &User{}
if search == "" {
return u, m.WrapError(m.Preload("Subscribed").Where("username = ?", username).First(u), "preloading subscriptions with user")
}
return u, m.WrapError(m.Preload("Subscribed", "name like ?", "%"+search+"%").Where("username = ?", username).First(u), "preloading subscriptions with user")
}
// DeleteError deletes a given error for a user.
func (m *Model) DeleteError(u *User, id int64) error {
return m.WrapError(m.Where("id = ?", id).Delete(u.Errors), "deleting errors for user")
}
// AddSubscriptionsForUser adds the repositories to the subscriptions table. Access is
// validated at the API level, not here.
func (m *Model) AddSubscriptionsForUser(u *User, repos []*Repository) error {
return m.Model(u).Association("Subscribed").Append(repos).Error
}
// RemoveSubscriptionForUser removes an item from the subscriptions table.
func (m *Model) RemoveSubscriptionForUser(u *User, repo *Repository) error {
return m.Model(u).Association("Subscribed").Delete(repo).Error
}
// AddError adds an error to the error list.
func (u *User) AddError(err error) {
u.Errors = append(u.Errors, UserError{Error: err.Error()})
}
// AfterFind is a gorm hook to unmarshal the Token JSON after finding the record.
func (u *User) AfterFind(tx *gorm.DB) error {
if err := u.FetchToken(); err != nil {
return err
}
if err := u.Validate(); err != nil {
return utils.WrapError(err, "reading user id %d (%q)", u.ID, u.Username)
}
return nil
}
// BeforeCreate just calls BeforeSave.
func (u *User) BeforeCreate(tx *gorm.DB) error {
return u.BeforeSave(tx)
}
// BeforeSave is a gorm hook to marshal the Token JSON before saving the record
func (u *User) BeforeSave(tx *gorm.DB) error {
if err := u.ValidateWrite(); err != nil {
return utils.WrapError(err, "saving user %q", u.Username)
}
if err := u.SetToken(); err != nil {
return err
}
return nil
}
// ValidateWrite is for write-only validations.
func (u *User) ValidateWrite() error {
if u.Token == nil || u.Token.Token == "" {
return errors.New("cannot be written because the oauth credentials are not valid")
}
return u.Validate()
}
// Validate validates the user record to ensure it can be written.
func (u *User) Validate() error {
if u.Username == "" {
return errors.New("username is empty")
}
return nil
}
func (m *Model) mkRepositoryFromGithub(repo *gh.Repository, owner *User, autoCreated bool) *Repository {
return &Repository{
Name: repo.GetFullName(),
Private: repo.GetPrivate(),
Disabled: true, // created repos are disabled by default
Github: repo,
Owner: owner,
AutoCreated: autoCreated,
}
}
// SaveRepositories saves github repositories; it sets the *User provided to
// the owner of it.
func (m *Model) SaveRepositories(repos []*gh.Repository, username string, autoCreated bool) error {
owner, err := m.FindUserByName(username)
if err != nil {
return err
}
for _, repo := range repos {
_, err := m.GetRepositoryByName(repo.GetFullName())
if err != nil {
localRepo := m.mkRepositoryFromGithub(repo, owner, autoCreated)
if err := m.WrapError(m.Create(localRepo), "creating repository"); err != nil {
return utils.WrapError(err, "could not create repository %q", repo.GetFullName())
}
}
}
t := time.Now()
owner.LastScannedRepos = &t
return m.WrapError(m.Save(owner), "saving owner cache data")
}
// ListSubscribedTasksForUser lists all tasks related to the subscribed repositories
// for the user.
func (m *Model) ListSubscribedTasksForUser(userID, page, perPage int64) ([]*Task, error) {
tasks := []*Task{}
call := m.Limit(perPage).Offset(page*perPage).
Joins("inner join submissions on submissions.id = tasks.submission_id").
Joins("inner join refs on refs.id = submissions.base_ref_id or refs.id = submissions.head_ref_id").
Joins("inner join subscriptions on subscriptions.repository_id = refs.repository_id").
Where("subscriptions.user_id = ?", userID).Find(&tasks)
return tasks, m.WrapError(call, "locating user's subscribed tasks")
}
// AddCapabilityToUser adds a capability to a user account.
func (m *Model) AddCapabilityToUser(u *User, cap Capability) error {
return m.WrapError(m.Exec("insert into user_capabilities (user_id, name) values (?, ?)", u.ID, cap), "adding capability for user")
}
// RemoveCapabilityFromUser removes a capability from a user account.
func (m *Model) RemoveCapabilityFromUser(u *User, cap Capability) error {
return m.WrapError(m.Exec("delete from user_capabilities where user_id = ? and name = ?", u.ID, cap), "removing capability from user")
}
// GetCapabilities returns the capabilities the supplied user account has.
func (m *Model) GetCapabilities(u *User, fixedCaps map[string][]string) ([]Capability, error) {
caps := map[string]struct{}{}
if fc, ok := fixedCaps[u.Username]; ok {
for _, cap := range fc {
caps[cap] = struct{}{}
}
}
dbCaps := []struct {
Name string `gorm:"name"`
}{}
err := m.WrapError(m.Raw("select name from user_capabilities where user_id = ?", u.ID).Scan(&dbCaps), "retrieving capabilities for user")
if err != nil {
return nil, err
}
for _, cap := range dbCaps {
caps[cap.Name] = struct{}{}
}
realCaps := []Capability{}
for cap := range caps {
realCaps = append(realCaps, Capability(cap))
}
return realCaps, nil
}
// HasCapability returns true if the user is capable of performing the operation.
func (m *Model) HasCapability(u *User, cap Capability, fixedCaps map[string][]string) (bool, error) {
// if we have fixed caps, we consult that table only; these are overrides for
// users that exist within the configuration file for the datasvc.
if caps, ok := fixedCaps[u.Username]; ok {
for _, thisCap := range caps {
if strings.TrimSpace(thisCap) == strings.TrimSpace(string(cap)) {
return true, nil
}
}
return false, nil
}
var slice []int64
err := m.WrapError(m.Raw("select 1 from user_capabilities where user_id = ? and name = ?", u.ID, cap).Find(&slice), "checking capabilities for user")
return len(slice) > 0, err
}