2023-09-02 22:30:57 +00:00
|
|
|
package db
|
2023-04-16 22:17:06 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"gorm.io/gorm/clause"
|
|
|
|
)
|
|
|
|
|
|
|
|
type AdminSetting struct {
|
|
|
|
Key string `gorm:"uniqueIndex"`
|
|
|
|
Value string
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
2024-05-12 21:40:11 +00:00
|
|
|
SettingDisableSignup = "disable-signup"
|
|
|
|
SettingRequireLogin = "require-login"
|
|
|
|
SettingAllowGistsWithoutLogin = "allow-gists-without-login"
|
|
|
|
SettingDisableLoginForm = "disable-login-form"
|
|
|
|
SettingDisableGravatar = "disable-gravatar"
|
2023-04-16 22:17:06 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func GetSetting(key string) (string, error) {
|
|
|
|
var setting AdminSetting
|
|
|
|
err := db.Where("key = ?", key).First(&setting).Error
|
|
|
|
return setting.Value, err
|
|
|
|
}
|
|
|
|
|
2023-04-28 18:31:10 +00:00
|
|
|
func GetSettings() (map[string]string, error) {
|
|
|
|
var settings []AdminSetting
|
|
|
|
err := db.Find(&settings).Error
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
result := make(map[string]string)
|
|
|
|
for _, setting := range settings {
|
|
|
|
result[setting.Key] = setting.Value
|
|
|
|
}
|
|
|
|
|
|
|
|
return result, nil
|
|
|
|
}
|
|
|
|
|
2023-04-16 22:17:06 +00:00
|
|
|
func UpdateSetting(key string, value string) error {
|
|
|
|
return db.Clauses(clause.OnConflict{
|
2023-04-28 18:31:10 +00:00
|
|
|
Columns: []clause.Column{{Name: "key"}}, // key column
|
2023-04-16 22:17:06 +00:00
|
|
|
DoUpdates: clause.AssignmentColumns([]string{"value"}),
|
|
|
|
}).Create(&AdminSetting{
|
|
|
|
Key: key,
|
|
|
|
Value: value,
|
|
|
|
}).Error
|
|
|
|
}
|
|
|
|
|
|
|
|
func setSetting(key string, value string) error {
|
|
|
|
return db.Create(&AdminSetting{Key: key, Value: value}).Error
|
|
|
|
}
|
|
|
|
|
|
|
|
func initAdminSettings(settings map[string]string) error {
|
|
|
|
for key, value := range settings {
|
|
|
|
if err := setSetting(key, value); err != nil {
|
2023-04-17 12:25:39 +00:00
|
|
|
if !IsUniqueConstraintViolation(err) {
|
2023-04-16 22:17:06 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2024-05-12 21:40:11 +00:00
|
|
|
|
|
|
|
type DBAuthInfo struct{}
|
|
|
|
|
|
|
|
func (auth DBAuthInfo) RequireLogin() (bool, error) {
|
|
|
|
s, err := GetSetting(SettingRequireLogin)
|
|
|
|
if err != nil {
|
|
|
|
return true, err
|
|
|
|
}
|
|
|
|
return s == "1", nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (auth DBAuthInfo) AllowGistsWithoutLogin() (bool, error) {
|
|
|
|
s, err := GetSetting(SettingAllowGistsWithoutLogin)
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
return s == "1", nil
|
|
|
|
}
|