bin/models/models.go

81 lines
1.6 KiB
Go
Raw Normal View History

2023-09-11 23:26:50 +02:00
package models
import (
"reflect"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
type File struct {
gorm.Model
PageKey string `gorm:"index:idx_pagekey,unique;unique"`
AdminKey string `gorm:"index:idx_adminkey"`
// The "virtual" filename.
Filename string
// The description of the file submission.
Description string
Language string
// The contents of the file must be valid text.
Data string
UserID uint
User User
}
type User struct {
gorm.Model
DisplayName string
Email string `gorm:"unique"`
Salt string
HashedPassword []byte
}
func (u *User) MatchesPassword(password string) bool {
combined := append([]byte(u.Salt), []byte(password)...)
return bcrypt.CompareHashAndPassword(u.HashedPassword, []byte(combined)) == nil
}
func DatabaseMigrations(db *gorm.DB) {
tables := []interface{}{
File{},
User{},
}
logrus.Infoln("Running database migrations.")
for _, table := range tables {
name := reflect.TypeOf(table).Name()
err := db.AutoMigrate(&table)
if err != nil {
logrus.WithError(err).WithField("table", name).Fatalln("Migration failed.")
} else {
logrus.WithField("table", name).Infoln("Migration successful.")
}
}
logrus.Infoln("Migrations ran successfully.")
}
func CreateNewBin(db *gorm.DB, text, name, description, language, key, adminKey string) (File, error) {
bin := File{
Filename: name,
Description: description,
Language: language,
PageKey: key,
AdminKey: adminKey,
Data: text,
}
result := db.Create(&bin)
if result.Error != nil {
return File{}, result.Error
}
return bin, nil
}