github.com/billybanfield/evergreen@v0.0.0-20170525200750-eeee692790f7/model/user_lifecycle.go (about) 1 package model 2 3 import ( 4 "fmt" 5 "time" 6 7 "github.com/evergreen-ci/evergreen/db" 8 "github.com/evergreen-ci/evergreen/model/user" 9 "github.com/evergreen-ci/evergreen/util" 10 "gopkg.in/mgo.v2" 11 "gopkg.in/mgo.v2/bson" 12 ) 13 14 // AddUserPublicKey adds a public key to a user's saved key list 15 func AddUserPublicKey(userId, name, value string) error { 16 pubKey := user.PubKey{ 17 Name: name, 18 Key: value, 19 CreatedAt: time.Now(), 20 } 21 22 selector := bson.M{ 23 user.IdKey: userId, 24 fmt.Sprintf("%s.%s", user.PubKeysKey, user.PubKeyNameKey): bson.M{"$ne": pubKey.Name}, 25 } 26 update := bson.M{ 27 "$push": bson.M{ 28 user.PubKeysKey: pubKey, 29 }, 30 } 31 return user.UpdateOne(selector, update) 32 } 33 34 // SaveUserSettings updates the settings stored for the given user id. 35 func SaveUserSettings(userId string, settings user.UserSettings) error { 36 update := bson.M{"$set": bson.M{user.SettingsKey: settings}} 37 return user.UpdateOne(bson.M{user.IdKey: userId}, update) 38 } 39 40 // SetUserAPIKey updates the API key stored with a user. 41 func SetUserAPIKey(userId, newKey string) error { 42 update := bson.M{"$set": bson.M{user.APIKeyKey: newKey}} 43 return user.UpdateOne(bson.M{user.IdKey: userId}, update) 44 } 45 46 // GetOrCreateUser fetches a user with the given userId and returns it. If no document exists for 47 // that userId, inserts it along with the provided display name and email. 48 func GetOrCreateUser(userId, displayName, email string) (*user.DBUser, error) { 49 u := &user.DBUser{} 50 _, err := db.FindAndModify(user.Collection, bson.M{user.IdKey: userId}, nil, 51 mgo.Change{ 52 Update: bson.M{ 53 "$set": bson.M{ 54 user.DispNameKey: displayName, 55 user.EmailAddressKey: email, 56 }, 57 "$setOnInsert": bson.M{ 58 user.APIKeyKey: util.RandomString(), 59 }, 60 }, 61 ReturnNew: true, 62 Upsert: true, 63 }, u) 64 if err != nil { 65 return nil, err 66 } 67 return u, nil 68 }