github.com/quickfeed/quickfeed@v0.0.0-20240507093252-ed8ca812a09c/database/gormdb_user.go (about) 1 package database 2 3 import "github.com/quickfeed/quickfeed/qf" 4 5 // CreateUser creates new user record. The first user is set as admin. 6 func (db *GormDB) CreateUser(user *qf.User) error { 7 if err := db.conn.Create(&user).Error; err != nil { 8 return err 9 } 10 // The first user defaults to admin user. 11 if user.ID == 1 { 12 user.IsAdmin = true 13 if err := db.UpdateUser(user); err != nil { 14 return err 15 } 16 } 17 return nil 18 } 19 20 // GetUser returns the given user. 21 func (db *GormDB) GetUser(userID uint64) (*qf.User, error) { 22 var user qf.User 23 if err := db.conn.First(&user, userID).Error; err != nil { 24 return nil, err 25 } 26 return &user, nil 27 } 28 29 // GetUserByRemoteIdentity returns the user for the given remote identity. 30 func (db *GormDB) GetUserByRemoteIdentity(scmRemoteID uint64) (*qf.User, error) { 31 var user qf.User 32 if err := db.conn. 33 Where(&qf.User{ScmRemoteID: scmRemoteID}). 34 First(&user).Error; err != nil { 35 return nil, err 36 } 37 return &user, nil 38 } 39 40 // GetUserByCourse returns the given user with enrollments matching the given course query. 41 func (db *GormDB) GetUserByCourse(query *qf.Course, login string) (*qf.User, error) { 42 var user qf.User 43 var course qf.Course 44 enrollmentStatuses := []qf.Enrollment_UserStatus{ 45 qf.Enrollment_STUDENT, 46 qf.Enrollment_TEACHER, 47 } 48 49 if err := db.conn.First(&course, query).Error; err != nil { 50 return nil, err 51 } 52 53 if err := db.conn. 54 Preload("Enrollments", "status in (?)", enrollmentStatuses). 55 First(&user, &qf.User{Login: login}).Error; err != nil { 56 return nil, err 57 } 58 for _, e := range user.Enrollments { 59 if e.CourseID == course.ID { 60 user.Enrollments = make([]*qf.Enrollment, 0) 61 return &user, nil 62 } 63 } 64 return nil, ErrNotEnrolled 65 } 66 67 // GetUserWithEnrollments returns the given user with enrollments. 68 func (db *GormDB) GetUserWithEnrollments(userID uint64) (*qf.User, error) { 69 var user qf.User 70 if err := db.conn. 71 Preload("Enrollments"). 72 Preload("Enrollments.Course"). 73 Preload("Enrollments.UsedSlipDays"). 74 First(&user, userID).Error; err != nil { 75 return nil, err 76 } 77 return &user, nil 78 } 79 80 // GetUsers fetches all users by provided IDs. 81 func (db *GormDB) GetUsers(userIDs ...uint64) ([]*qf.User, error) { 82 m := db.conn 83 if len(userIDs) > 0 { 84 m = m.Where(userIDs) 85 } 86 var users []*qf.User 87 if err := m.Find(&users).Error; err != nil { 88 return nil, err 89 } 90 return users, nil 91 } 92 93 // UpdateUser updates user information. 94 func (db *GormDB) UpdateUser(user *qf.User) error { 95 if err := db.conn.First(&qf.User{ID: user.GetID()}).Error; err != nil { 96 return err 97 } 98 return db.conn.Save(&user).Error 99 }