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 }