87 lines
2.0 KiB
Go
87 lines
2.0 KiB
Go
package repository
|
|
|
|
import (
|
|
"errors"
|
|
"esauth"
|
|
"fmt"
|
|
"math/rand/v2"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type AuthSchema struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewAuthSchema(db *gorm.DB) *AuthSchema {
|
|
return &AuthSchema{db: db}
|
|
}
|
|
|
|
func (r AuthSchema) CreateUser(user *esauth.User) (int64, error) {
|
|
if user.Username != "" {
|
|
userF := esauth.User{}
|
|
err := r.db.Find(&userF, "username = ?", user.Username).Error
|
|
if (err == nil) && (userF.Id > 0) && (userF.Id != user.Id) {
|
|
logrus.Warnf("Same username USER: %d (%s) -> %s", userF.Id, user.FirstName, userF.Username)
|
|
user.Username += fmt.Sprintf("%d", (rand.IntN(999999) + 1))
|
|
return r.CreateUser(user)
|
|
}
|
|
}
|
|
err := r.db.Create(&user).Error
|
|
return user.Id, err
|
|
}
|
|
|
|
func (r AuthSchema) SaveUser(user *esauth.User) (int64, error) {
|
|
if user.Username != "" {
|
|
userF := esauth.User{}
|
|
err := r.db.Find(&userF, "username = ?", user.Username).Error
|
|
if (err == nil) && (userF.Id >= 0) && (userF.Id != user.Id) {
|
|
return -1, errors.New("username already used")
|
|
}
|
|
}
|
|
err := r.db.Save(user).Error
|
|
return user.Id, err
|
|
}
|
|
|
|
func (r AuthSchema) GetUser(id int64) (esauth.User, error) {
|
|
user := esauth.User{}
|
|
err := r.db.Find(&user, "id = ?", id).Error
|
|
if user.Id == -1 {
|
|
err = fmt.Errorf("unknown user %d", id)
|
|
}
|
|
return user, err
|
|
}
|
|
|
|
func (r AuthSchema) FindUser(query, param string) (esauth.User, error) {
|
|
user := esauth.User{}
|
|
err := r.db.Find(&user, query, param).Error
|
|
return user, err
|
|
}
|
|
|
|
func (r AuthSchema) GetUsers(start, limit int) []int64 {
|
|
result := []esauth.User{}
|
|
r.db.Select("id").Limit(limit).Offset(start).Find(&result)
|
|
var ans = make([]int64, len(result))
|
|
for i, res := range result {
|
|
ans[i] = res.Id
|
|
}
|
|
return ans
|
|
}
|
|
|
|
func (r AuthSchema) GetUsersCount() int64 {
|
|
var count int64 = 0
|
|
r.db.Model(&esauth.User{}).Count(&count)
|
|
return count
|
|
}
|
|
|
|
func (r AuthSchema) DeleteUser(id int64) error {
|
|
user := esauth.User{}
|
|
err := r.db.Find(&user, "id = ?", id).Error
|
|
if user.Id == -1 {
|
|
err = fmt.Errorf("unknown user %d", id)
|
|
}
|
|
r.db.Delete(user)
|
|
return err
|
|
}
|