gophertype/pkg/models/app_settings.go

73 lines
1.2 KiB
Go

package models
import (
"crypto/rand"
"encoding/base64"
"github.com/jinzhu/gorm"
)
// AppSetting singleton holds the app configuration.
type AppSetting struct {
gorm.Model
// Site information
Title string
Description string
Email string // primary email for notifications
NSFW bool
BaseURL string
// Blog settings
PostsPerPage int
// Mail settings
MailEnabled bool
MailSender string
MailHost string
MailPort int
MailUsername string
MailPassword string
// Security
SecretKey string `json:"-"`
}
// GetSettings gets or creates the App Settings.
func GetSettings() AppSetting {
var s AppSetting
r := DB.First(&s)
if r.Error != nil {
s = AppSetting{
Title: "Untitled Site",
Description: "Just another web blog.",
SecretKey: MakeSecretKey(),
}
}
if s.SecretKey == "" {
s.SecretKey = MakeSecretKey()
}
return s
}
// Save the settings to DB.
func (s AppSetting) Save() error {
if DB.NewRecord(s) {
r := DB.Create(&s)
return r.Error
}
r := DB.Save(&s)
return r.Error
}
// MakeSecretKey generates a secret key for signing HTTP cookies.
func MakeSecretKey() string {
keyLength := 32
b := make([]byte, keyLength)
rand.Read(b)
return base64.URLEncoding.EncodeToString(b)
}