opengist/internal/db/admin_setting.go
Jade Lovelace 22052bd38f
Add a setting to allow anonymous access to individual gists while still RequireLogin everywhere else (#229)
* Add a setting to allow accessing individual gists without auth

This is a middle ground between the existing setting "Require Login",
which requires login to do anything at all, and having it off, which
shows a public list of gists and more generally allows discovering info
about the users/gists of the instance without login.

The idea of this setting is that it is "require login" for everything
except individual gists.

Fixes #228.


Co-authored-by: Thomas Miceli <tho.miceli@gmail.com>
2024-05-12 23:40:11 +02:00

83 lines
1.8 KiB
Go

package db
import (
"gorm.io/gorm/clause"
)
type AdminSetting struct {
Key string `gorm:"uniqueIndex"`
Value string
}
const (
SettingDisableSignup = "disable-signup"
SettingRequireLogin = "require-login"
SettingAllowGistsWithoutLogin = "allow-gists-without-login"
SettingDisableLoginForm = "disable-login-form"
SettingDisableGravatar = "disable-gravatar"
)
func GetSetting(key string) (string, error) {
var setting AdminSetting
err := db.Where("key = ?", key).First(&setting).Error
return setting.Value, err
}
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
}
func UpdateSetting(key string, value string) error {
return db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "key"}}, // key column
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 {
if !IsUniqueConstraintViolation(err) {
return err
}
}
}
return nil
}
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
}