mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-04 07:06:36 +08:00
[优化] 改名
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type ApplyLog struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
NodeID string `json:"node_id" gorm:"index;size:64;not null"`
|
||||
Version string `json:"version" gorm:"size:32;not null"`
|
||||
Result string `json:"result" gorm:"size:32;not null"`
|
||||
Message string `json:"message" gorm:"size:1024"`
|
||||
Checksum string `json:"checksum" gorm:"size:64;not null;default:''"`
|
||||
MainConfigChecksum string `json:"main_config_checksum" gorm:"size:64;not null;default:''"`
|
||||
RouteConfigChecksum string `json:"route_config_checksum" gorm:"size:64;not null;default:''"`
|
||||
SupportFileCount int `json:"support_file_count" gorm:"not null;default:0"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func ListApplyLogs(nodeID string) (logs []*ApplyLog, err error) {
|
||||
query := DB.Order("id desc")
|
||||
if nodeID != "" {
|
||||
query = query.Where("node_id = ?", nodeID)
|
||||
}
|
||||
err = query.Find(&logs).Error
|
||||
return logs, err
|
||||
}
|
||||
|
||||
func GetLatestApplyLog(nodeID string) (*ApplyLog, error) {
|
||||
log := &ApplyLog{}
|
||||
err := DB.Where("node_id = ?", nodeID).Order("id desc").First(log).Error
|
||||
return log, err
|
||||
}
|
||||
|
||||
func GetLatestApplyLogsByNodeIDs(nodeIDs []string) (map[string]*ApplyLog, error) {
|
||||
result := make(map[string]*ApplyLog)
|
||||
if len(nodeIDs) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
var logs []*ApplyLog
|
||||
subQuery := DB.Model(&ApplyLog{}).
|
||||
Select("MAX(id) AS id").
|
||||
Where("node_id IN ?", nodeIDs).
|
||||
Group("node_id")
|
||||
if err := DB.Where("id IN (?)", subQuery).Find(&logs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, log := range logs {
|
||||
result[log.NodeID] = log
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type ConfigVersion struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
Version string `json:"version" gorm:"uniqueIndex;size:32;not null"`
|
||||
SnapshotJSON string `json:"snapshot_json" gorm:"type:text;not null"`
|
||||
MainConfig string `json:"main_config" gorm:"type:text;not null;default:''"`
|
||||
RenderedConfig string `json:"rendered_config" gorm:"type:text;not null"`
|
||||
SupportFilesJSON string `json:"support_files_json" gorm:"type:text;not null;default:'[]'"`
|
||||
Checksum string `json:"checksum" gorm:"size:64;not null"`
|
||||
IsActive bool `json:"is_active" gorm:"not null;default:false;index"`
|
||||
CreatedBy string `json:"created_by" gorm:"size:64;not null"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func ListConfigVersions() (versions []*ConfigVersion, err error) {
|
||||
err = DB.Order("id desc").Find(&versions).Error
|
||||
return versions, err
|
||||
}
|
||||
|
||||
func GetConfigVersionByID(id uint) (*ConfigVersion, error) {
|
||||
version := &ConfigVersion{}
|
||||
err := DB.First(version, id).Error
|
||||
return version, err
|
||||
}
|
||||
|
||||
func GetActiveConfigVersion() (*ConfigVersion, error) {
|
||||
version := &ConfigVersion{}
|
||||
err := DB.Where("is_active = ?", true).Order("id desc").First(version).Error
|
||||
return version, err
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"openflare/common"
|
||||
"os"
|
||||
"path"
|
||||
)
|
||||
|
||||
type File struct {
|
||||
Id int `json:"id"`
|
||||
Filename string `json:"filename" gorm:"index"`
|
||||
Description string `json:"description"`
|
||||
Uploader string `json:"uploader" gorm:"index"`
|
||||
UploaderId int `json:"uploader_id" gorm:"index"`
|
||||
Link string `json:"link" gorm:"unique;index"`
|
||||
UploadTime string `json:"upload_time"`
|
||||
DownloadCounter int `json:"download_counter"`
|
||||
}
|
||||
|
||||
func GetAllFiles(startIdx int, num int) ([]*File, error) {
|
||||
var files []*File
|
||||
var err error
|
||||
err = DB.Order("id desc").Limit(num).Offset(startIdx).Find(&files).Error
|
||||
return files, err
|
||||
}
|
||||
|
||||
func SearchFiles(keyword string) (files []*File, err error) {
|
||||
err = DB.Select([]string{"id", "filename", "description", "uploader", "uploader_id", "link", "upload_time", "download_counter"}).Where(
|
||||
"filename LIKE ? or uploader LIKE ? or uploader_id = ?", keyword+"%", keyword+"%", keyword).Find(&files).Error
|
||||
return files, err
|
||||
}
|
||||
|
||||
func (file *File) Insert() error {
|
||||
var err error
|
||||
err = DB.Create(file).Error
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete Make sure link is valid! Because we will use os.Remove to delete it!
|
||||
func (file *File) Delete() error {
|
||||
var err error
|
||||
err = DB.Delete(file).Error
|
||||
err = os.Remove(path.Join(common.UploadPath, file.Link))
|
||||
return err
|
||||
}
|
||||
|
||||
func UpdateDownloadCounter(link string) {
|
||||
DB.Model(&File{}).Where("link = ?", link).UpdateColumn("download_counter", gorm.Expr("download_counter + 1"))
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"log/slog"
|
||||
"openflare/common"
|
||||
"openflare/utils/security"
|
||||
"os"
|
||||
)
|
||||
|
||||
var DB *gorm.DB
|
||||
|
||||
func migrateProxyRouteEnableHTTPSColumn(db *gorm.DB) error {
|
||||
if !db.Migrator().HasTable(&ProxyRoute{}) {
|
||||
return nil
|
||||
}
|
||||
if db.Migrator().HasColumn(&ProxyRoute{}, "enable_https") || !db.Migrator().HasColumn(&ProxyRoute{}, "enable_http_s") {
|
||||
return nil
|
||||
}
|
||||
return db.Migrator().RenameColumn(&ProxyRoute{}, "enable_http_s", "enable_https")
|
||||
}
|
||||
|
||||
func createRootAccountIfNeed() error {
|
||||
var user User
|
||||
//if user.Status != common.UserStatusEnabled {
|
||||
if err := DB.First(&user).Error; err != nil {
|
||||
slog.Info("no user exists, create a root user", "username", "root")
|
||||
hashedPassword, err := security.Password2Hash("123456")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rootUser := User{
|
||||
Username: "root",
|
||||
Password: hashedPassword,
|
||||
Role: common.RoleRootUser,
|
||||
Status: common.UserStatusEnabled,
|
||||
DisplayName: "Root User",
|
||||
}
|
||||
DB.Create(&rootUser)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func CountTable(tableName string) (num int64) {
|
||||
DB.Table(tableName).Count(&num)
|
||||
return
|
||||
}
|
||||
|
||||
func InitDB() (err error) {
|
||||
var db *gorm.DB
|
||||
if os.Getenv("SQL_DSN") != "" {
|
||||
// Use MySQL
|
||||
db, err = gorm.Open(mysql.Open(os.Getenv("SQL_DSN")), &gorm.Config{
|
||||
PrepareStmt: true, // precompile SQL
|
||||
})
|
||||
} else {
|
||||
// Use SQLite
|
||||
db, err = gorm.Open(sqlite.Open(common.SQLitePath), &gorm.Config{
|
||||
PrepareStmt: true, // precompile SQL
|
||||
})
|
||||
slog.Info("SQL_DSN not set, using SQLite as database")
|
||||
}
|
||||
if err == nil {
|
||||
DB = db
|
||||
if err = migrateProxyRouteEnableHTTPSColumn(db); err != nil {
|
||||
return err
|
||||
}
|
||||
err := db.AutoMigrate(&File{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = db.AutoMigrate(&User{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = db.AutoMigrate(&Option{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = db.AutoMigrate(&ProxyRoute{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = db.AutoMigrate(&ConfigVersion{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = db.AutoMigrate(&Node{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = db.AutoMigrate(&NodeSystemProfile{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = db.AutoMigrate(&ApplyLog{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = db.AutoMigrate(&NodeMetricSnapshot{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = db.AutoMigrate(&NodeRequestReport{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = db.AutoMigrate(&NodeAccessLog{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = db.AutoMigrate(&NodeHealthEvent{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = db.AutoMigrate(&TLSCertificate{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = db.AutoMigrate(&ManagedDomain{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = createRootAccountIfNeed()
|
||||
return err
|
||||
} else {
|
||||
slog.Error("open database failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func CloseDB() error {
|
||||
sqlDB, err := DB.DB()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = sqlDB.Close()
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type ManagedDomain struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
Domain string `json:"domain" gorm:"uniqueIndex;size:255;not null"`
|
||||
CertID *uint `json:"cert_id"`
|
||||
Enabled bool `json:"enabled" gorm:"not null;default:true"`
|
||||
Remark string `json:"remark" gorm:"size:255"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func ListManagedDomains() (domains []*ManagedDomain, err error) {
|
||||
err = DB.Order("id desc").Find(&domains).Error
|
||||
return domains, err
|
||||
}
|
||||
|
||||
func ListEnabledManagedDomainsWithCertificate() (domains []*ManagedDomain, err error) {
|
||||
err = DB.Where("enabled = ? AND cert_id IS NOT NULL", true).Order("id desc").Find(&domains).Error
|
||||
return domains, err
|
||||
}
|
||||
|
||||
func GetManagedDomainByID(id uint) (*ManagedDomain, error) {
|
||||
domain := &ManagedDomain{}
|
||||
err := DB.First(domain, id).Error
|
||||
return domain, err
|
||||
}
|
||||
|
||||
func (domain *ManagedDomain) Insert() error {
|
||||
return DB.Create(domain).Error
|
||||
}
|
||||
|
||||
func (domain *ManagedDomain) Update() error {
|
||||
return DB.Save(domain).Error
|
||||
}
|
||||
|
||||
func (domain *ManagedDomain) Delete() error {
|
||||
return DB.Delete(domain).Error
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type Node struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
NodeID string `json:"node_id" gorm:"uniqueIndex;size:64;not null"`
|
||||
Name string `json:"name" gorm:"size:128;not null"`
|
||||
IP string `json:"ip" gorm:"size:64;not null"`
|
||||
GeoName string `json:"geo_name" gorm:"size:128"`
|
||||
GeoLatitude *float64 `json:"geo_latitude"`
|
||||
GeoLongitude *float64 `json:"geo_longitude"`
|
||||
GeoManualOverride bool `json:"geo_manual_override" gorm:"not null;default:false"`
|
||||
AgentToken string `json:"-" gorm:"size:128;index"`
|
||||
AutoUpdateEnabled bool `json:"auto_update_enabled" gorm:"not null;default:false"`
|
||||
UpdateRequested bool `json:"update_requested" gorm:"not null;default:false"`
|
||||
UpdateChannel string `json:"update_channel" gorm:"size:16;not null;default:'stable'"`
|
||||
UpdateTag string `json:"update_tag" gorm:"size:64"`
|
||||
RestartOpenrestyRequested bool `json:"restart_openresty_requested" gorm:"not null;default:false"`
|
||||
AgentVersion string `json:"agent_version" gorm:"size:64;not null"`
|
||||
NginxVersion string `json:"nginx_version" gorm:"size:64"`
|
||||
OpenrestyStatus string `json:"openresty_status" gorm:"size:16;not null;default:'unknown'"`
|
||||
OpenrestyMessage string `json:"openresty_message" gorm:"size:2048"`
|
||||
Status string `json:"status" gorm:"size:16;not null;default:'offline'"`
|
||||
CurrentVersion string `json:"current_version" gorm:"size:32"`
|
||||
LastSeenAt time.Time `json:"last_seen_at"`
|
||||
LastError string `json:"last_error" gorm:"size:1024"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func ListNodes() (nodes []*Node, err error) {
|
||||
err = DB.Order("id desc").Find(&nodes).Error
|
||||
return nodes, err
|
||||
}
|
||||
|
||||
func GetNodeByNodeID(nodeID string) (*Node, error) {
|
||||
node := &Node{}
|
||||
err := DB.Where("node_id = ?", nodeID).First(node).Error
|
||||
return node, err
|
||||
}
|
||||
|
||||
func GetNodeByID(id uint) (*Node, error) {
|
||||
node := &Node{}
|
||||
err := DB.First(node, id).Error
|
||||
return node, err
|
||||
}
|
||||
|
||||
func GetNodeByAgentToken(token string) (*Node, error) {
|
||||
node := &Node{}
|
||||
err := DB.Where("agent_token = ?", token).First(node).Error
|
||||
return node, err
|
||||
}
|
||||
|
||||
func (node *Node) Insert() error {
|
||||
return DB.Create(node).Error
|
||||
}
|
||||
|
||||
func (node *Node) Update() error {
|
||||
return DB.Save(node).Error
|
||||
}
|
||||
|
||||
func (node *Node) Delete() error {
|
||||
return DB.Delete(node).Error
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type NodeAccessLog struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
NodeID string `json:"node_id" gorm:"index;size:64;not null"`
|
||||
LoggedAt time.Time `json:"logged_at" gorm:"index"`
|
||||
RemoteAddr string `json:"remote_addr" gorm:"size:128"`
|
||||
Region string `json:"region" gorm:"size:128"`
|
||||
Host string `json:"host" gorm:"size:255"`
|
||||
Path string `json:"path" gorm:"size:2048"`
|
||||
StatusCode int `json:"status_code"`
|
||||
RawJSON string `json:"raw_json" gorm:"type:text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type NodeAccessLogRegionCount struct {
|
||||
Region string `json:"region"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
func ListNodeAccessLogs(nodeID string, since time.Time, offset int, limit int) (logs []*NodeAccessLog, err error) {
|
||||
query := DB.Order("logged_at desc, id desc")
|
||||
if nodeID != "" {
|
||||
query = query.Where("node_id = ?", nodeID)
|
||||
}
|
||||
if !since.IsZero() {
|
||||
query = query.Where("logged_at >= ?", since)
|
||||
}
|
||||
if offset > 0 {
|
||||
query = query.Offset(offset)
|
||||
}
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
err = query.Find(&logs).Error
|
||||
return logs, err
|
||||
}
|
||||
|
||||
func CountNodeAccessLogs(nodeID string, since time.Time) (totalRecords int64, totalIPs int64, err error) {
|
||||
query := DB.Model(&NodeAccessLog{})
|
||||
if nodeID != "" {
|
||||
query = query.Where("node_id = ?", nodeID)
|
||||
}
|
||||
if !since.IsZero() {
|
||||
query = query.Where("logged_at >= ?", since)
|
||||
}
|
||||
if err = query.Count(&totalRecords).Error; err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
if err = query.
|
||||
Where("remote_addr <> ''").
|
||||
Distinct("remote_addr").
|
||||
Count(&totalIPs).Error; err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
return totalRecords, totalIPs, nil
|
||||
}
|
||||
|
||||
func ListNodeAccessLogRegionCounts(nodeID string, since time.Time, limit int) (items []*NodeAccessLogRegionCount, err error) {
|
||||
query := DB.Model(&NodeAccessLog{}).
|
||||
Select("region as region, count(*) as count").
|
||||
Where("region <> ''")
|
||||
if nodeID != "" {
|
||||
query = query.Where("node_id = ?", nodeID)
|
||||
}
|
||||
if !since.IsZero() {
|
||||
query = query.Where("logged_at >= ?", since)
|
||||
}
|
||||
query = query.Group("region").Order("count desc, region asc")
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
err = query.Scan(&items).Error
|
||||
return items, err
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type NodeHealthEvent struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
NodeID string `json:"node_id" gorm:"index;size:64;not null"`
|
||||
EventType string `json:"event_type" gorm:"index;size:64;not null"`
|
||||
Severity string `json:"severity" gorm:"size:16;not null"`
|
||||
Status string `json:"status" gorm:"index;size:16;not null"`
|
||||
Message string `json:"message" gorm:"size:2048"`
|
||||
FirstTriggeredAt time.Time `json:"first_triggered_at" gorm:"index"`
|
||||
LastTriggeredAt time.Time `json:"last_triggered_at" gorm:"index"`
|
||||
ReportedAt time.Time `json:"reported_at" gorm:"index"`
|
||||
ResolvedAt *time.Time `json:"resolved_at" gorm:"index"`
|
||||
RawJSON string `json:"raw_json" gorm:"type:text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func GetActiveNodeHealthEvent(nodeID string, eventType string) (*NodeHealthEvent, error) {
|
||||
event := &NodeHealthEvent{}
|
||||
err := DB.Where("node_id = ? AND event_type = ? AND status = ?", nodeID, eventType, "active").First(event).Error
|
||||
return event, err
|
||||
}
|
||||
|
||||
func ListNodeHealthEvents(nodeID string, activeOnly bool, limit int) (events []*NodeHealthEvent, err error) {
|
||||
query := DB.Where("node_id = ?", nodeID).Order("last_triggered_at desc")
|
||||
if activeOnly {
|
||||
query = query.Where("status = ?", "active")
|
||||
}
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
err = query.Find(&events).Error
|
||||
return events, err
|
||||
}
|
||||
|
||||
func ListActiveNodeHealthEvents() (events []*NodeHealthEvent, err error) {
|
||||
err = DB.Where("status = ?", "active").Order("last_triggered_at desc").Find(&events).Error
|
||||
return events, err
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type NodeMetricSnapshot struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
NodeID string `json:"node_id" gorm:"index;size:64;not null"`
|
||||
CapturedAt time.Time `json:"captured_at" gorm:"index"`
|
||||
CPUUsagePercent float64 `json:"cpu_usage_percent"`
|
||||
MemoryUsedBytes int64 `json:"memory_used_bytes"`
|
||||
MemoryTotalBytes int64 `json:"memory_total_bytes"`
|
||||
StorageUsedBytes int64 `json:"storage_used_bytes"`
|
||||
StorageTotalBytes int64 `json:"storage_total_bytes"`
|
||||
DiskReadBytes int64 `json:"disk_read_bytes"`
|
||||
DiskWriteBytes int64 `json:"disk_write_bytes"`
|
||||
NetworkRxBytes int64 `json:"network_rx_bytes"`
|
||||
NetworkTxBytes int64 `json:"network_tx_bytes"`
|
||||
OpenrestyRxBytes int64 `json:"openresty_rx_bytes"`
|
||||
OpenrestyTxBytes int64 `json:"openresty_tx_bytes"`
|
||||
OpenrestyConnections int64 `json:"openresty_connections"`
|
||||
RawJSON string `json:"raw_json" gorm:"type:text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (snapshot *NodeMetricSnapshot) Insert() error {
|
||||
return DB.Create(snapshot).Error
|
||||
}
|
||||
|
||||
func ListNodeMetricSnapshots(nodeID string, since time.Time, limit int) (snapshots []*NodeMetricSnapshot, err error) {
|
||||
query := DB.Where("node_id = ?", nodeID).Order("captured_at desc")
|
||||
if !since.IsZero() {
|
||||
query = query.Where("captured_at >= ?", since)
|
||||
}
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
err = query.Find(&snapshots).Error
|
||||
return snapshots, err
|
||||
}
|
||||
|
||||
func ListMetricSnapshotsSince(since time.Time) (snapshots []*NodeMetricSnapshot, err error) {
|
||||
query := DB.Order("captured_at desc")
|
||||
if !since.IsZero() {
|
||||
query = query.Where("captured_at >= ?", since)
|
||||
}
|
||||
err = query.Find(&snapshots).Error
|
||||
return snapshots, err
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type NodeRequestReport struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
NodeID string `json:"node_id" gorm:"index;size:64;not null"`
|
||||
WindowStartedAt time.Time `json:"window_started_at" gorm:"index"`
|
||||
WindowEndedAt time.Time `json:"window_ended_at" gorm:"index"`
|
||||
RequestCount int64 `json:"request_count"`
|
||||
ErrorCount int64 `json:"error_count"`
|
||||
UniqueVisitorCount int64 `json:"unique_visitor_count"`
|
||||
StatusCodesJSON string `json:"status_codes_json" gorm:"type:text"`
|
||||
TopDomainsJSON string `json:"top_domains_json" gorm:"type:text"`
|
||||
SourceCountriesJSON string `json:"source_countries_json" gorm:"type:text"`
|
||||
RawJSON string `json:"raw_json" gorm:"type:text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (report *NodeRequestReport) Insert() error {
|
||||
return DB.Create(report).Error
|
||||
}
|
||||
|
||||
func ListNodeRequestReports(nodeID string, since time.Time, limit int) (reports []*NodeRequestReport, err error) {
|
||||
query := DB.Where("node_id = ?", nodeID).Order("window_ended_at desc")
|
||||
if !since.IsZero() {
|
||||
query = query.Where("window_ended_at >= ?", since)
|
||||
}
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
err = query.Find(&reports).Error
|
||||
return reports, err
|
||||
}
|
||||
|
||||
func ListRequestReportsSince(since time.Time) (reports []*NodeRequestReport, err error) {
|
||||
query := DB.Order("window_ended_at desc")
|
||||
if !since.IsZero() {
|
||||
query = query.Where("window_ended_at >= ?", since)
|
||||
}
|
||||
err = query.Find(&reports).Error
|
||||
return reports, err
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type NodeSystemProfile struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
NodeID string `json:"node_id" gorm:"uniqueIndex;size:64;not null"`
|
||||
Hostname string `json:"hostname" gorm:"size:255"`
|
||||
OSName string `json:"os_name" gorm:"size:128"`
|
||||
OSVersion string `json:"os_version" gorm:"size:128"`
|
||||
KernelVersion string `json:"kernel_version" gorm:"size:128"`
|
||||
Architecture string `json:"architecture" gorm:"size:64"`
|
||||
CPUModel string `json:"cpu_model" gorm:"size:255"`
|
||||
CPUCores int `json:"cpu_cores"`
|
||||
TotalMemoryBytes int64 `json:"total_memory_bytes"`
|
||||
TotalDiskBytes int64 `json:"total_disk_bytes"`
|
||||
UptimeSeconds int64 `json:"uptime_seconds"`
|
||||
ReportedAt time.Time `json:"reported_at" gorm:"index"`
|
||||
RawJSON string `json:"raw_json" gorm:"type:text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func GetNodeSystemProfile(nodeID string) (*NodeSystemProfile, error) {
|
||||
profile := &NodeSystemProfile{}
|
||||
err := DB.Where("node_id = ?", nodeID).First(profile).Error
|
||||
return profile, err
|
||||
}
|
||||
|
||||
func UpsertNodeSystemProfile(profile *NodeSystemProfile) error {
|
||||
if profile == nil {
|
||||
return nil
|
||||
}
|
||||
return DB.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "node_id"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{
|
||||
"hostname",
|
||||
"os_name",
|
||||
"os_version",
|
||||
"kernel_version",
|
||||
"architecture",
|
||||
"cpu_model",
|
||||
"cpu_cores",
|
||||
"total_memory_bytes",
|
||||
"total_disk_bytes",
|
||||
"uptime_seconds",
|
||||
"reported_at",
|
||||
"raw_json",
|
||||
"updated_at",
|
||||
}),
|
||||
}).Create(profile).Error
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"openflare/common"
|
||||
"openflare/utils/geoip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Option struct {
|
||||
Key string `json:"key" gorm:"primaryKey"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
func AllOption() ([]*Option, error) {
|
||||
var options []*Option
|
||||
var err error
|
||||
err = DB.Find(&options).Error
|
||||
return options, err
|
||||
}
|
||||
|
||||
func InitOptionMap() {
|
||||
common.OptionMapRWMutex.Lock()
|
||||
common.OptionMap = make(map[string]string)
|
||||
common.OptionMap["FileUploadPermission"] = strconv.Itoa(common.FileUploadPermission)
|
||||
common.OptionMap["FileDownloadPermission"] = strconv.Itoa(common.FileDownloadPermission)
|
||||
common.OptionMap["ImageUploadPermission"] = strconv.Itoa(common.ImageUploadPermission)
|
||||
common.OptionMap["ImageDownloadPermission"] = strconv.Itoa(common.ImageDownloadPermission)
|
||||
common.OptionMap["PasswordLoginEnabled"] = strconv.FormatBool(common.PasswordLoginEnabled)
|
||||
common.OptionMap["PasswordRegisterEnabled"] = strconv.FormatBool(common.PasswordRegisterEnabled)
|
||||
common.OptionMap["EmailVerificationEnabled"] = strconv.FormatBool(common.EmailVerificationEnabled)
|
||||
common.OptionMap["GitHubOAuthEnabled"] = strconv.FormatBool(common.GitHubOAuthEnabled)
|
||||
common.OptionMap["WeChatAuthEnabled"] = strconv.FormatBool(common.WeChatAuthEnabled)
|
||||
common.OptionMap["TurnstileCheckEnabled"] = strconv.FormatBool(common.TurnstileCheckEnabled)
|
||||
common.OptionMap["RegisterEnabled"] = strconv.FormatBool(common.RegisterEnabled)
|
||||
common.OptionMap["SMTPServer"] = ""
|
||||
common.OptionMap["SMTPPort"] = strconv.Itoa(common.SMTPPort)
|
||||
common.OptionMap["SMTPAccount"] = ""
|
||||
common.OptionMap["SMTPToken"] = ""
|
||||
common.OptionMap["Notice"] = ""
|
||||
common.OptionMap["About"] = ""
|
||||
common.OptionMap["Footer"] = common.Footer
|
||||
common.OptionMap["HomePageLink"] = common.HomePageLink
|
||||
common.OptionMap["SystemName"] = common.SystemName
|
||||
common.OptionMap["ServerAddress"] = ""
|
||||
common.OptionMap["GitHubClientId"] = ""
|
||||
common.OptionMap["GitHubClientSecret"] = ""
|
||||
common.OptionMap["WeChatServerAddress"] = ""
|
||||
common.OptionMap["WeChatServerToken"] = ""
|
||||
common.OptionMap["WeChatAccountQRCodeImageURL"] = ""
|
||||
common.OptionMap["TurnstileSiteKey"] = ""
|
||||
common.OptionMap["TurnstileSecretKey"] = ""
|
||||
common.OptionMap["AgentDiscoveryToken"] = ""
|
||||
common.OptionMap["AgentHeartbeatInterval"] = strconv.Itoa(common.AgentHeartbeatInterval)
|
||||
common.OptionMap["NodeOfflineThreshold"] = strconv.Itoa(int(common.NodeOfflineThreshold.Milliseconds()))
|
||||
common.OptionMap["AgentUpdateRepo"] = common.AgentUpdateRepo
|
||||
common.OptionMap["GeoIPProvider"] = common.GeoIPProvider
|
||||
common.OptionMap["OpenRestyWorkerProcesses"] = common.OpenRestyWorkerProcesses
|
||||
common.OptionMap["OpenRestyWorkerConnections"] = strconv.Itoa(common.OpenRestyWorkerConnections)
|
||||
common.OptionMap["OpenRestyWorkerRlimitNofile"] = strconv.Itoa(common.OpenRestyWorkerRlimitNofile)
|
||||
common.OptionMap["OpenRestyEventsUse"] = common.OpenRestyEventsUse
|
||||
common.OptionMap["OpenRestyEventsMultiAcceptEnabled"] = strconv.FormatBool(common.OpenRestyEventsMultiAcceptEnabled)
|
||||
common.OptionMap["OpenRestyKeepaliveTimeout"] = strconv.Itoa(common.OpenRestyKeepaliveTimeout)
|
||||
common.OptionMap["OpenRestyKeepaliveRequests"] = strconv.Itoa(common.OpenRestyKeepaliveRequests)
|
||||
common.OptionMap["OpenRestyClientHeaderTimeout"] = strconv.Itoa(common.OpenRestyClientHeaderTimeout)
|
||||
common.OptionMap["OpenRestyClientBodyTimeout"] = strconv.Itoa(common.OpenRestyClientBodyTimeout)
|
||||
common.OptionMap["OpenRestyClientMaxBodySize"] = common.OpenRestyClientMaxBodySize
|
||||
common.OptionMap["OpenRestyLargeClientHeaderBuffers"] = common.OpenRestyLargeClientHeaderBuffers
|
||||
common.OptionMap["OpenRestySendTimeout"] = strconv.Itoa(common.OpenRestySendTimeout)
|
||||
common.OptionMap["OpenRestyProxyConnectTimeout"] = strconv.Itoa(common.OpenRestyProxyConnectTimeout)
|
||||
common.OptionMap["OpenRestyProxySendTimeout"] = strconv.Itoa(common.OpenRestyProxySendTimeout)
|
||||
common.OptionMap["OpenRestyProxyReadTimeout"] = strconv.Itoa(common.OpenRestyProxyReadTimeout)
|
||||
common.OptionMap["OpenRestyWebsocketEnabled"] = strconv.FormatBool(common.OpenRestyWebsocketEnabled)
|
||||
common.OptionMap["OpenRestyProxyRequestBufferingEnabled"] = strconv.FormatBool(common.OpenRestyProxyRequestBufferingEnabled)
|
||||
common.OptionMap["OpenRestyProxyBufferingEnabled"] = strconv.FormatBool(common.OpenRestyProxyBufferingEnabled)
|
||||
common.OptionMap["OpenRestyProxyBuffers"] = common.OpenRestyProxyBuffers
|
||||
common.OptionMap["OpenRestyProxyBufferSize"] = common.OpenRestyProxyBufferSize
|
||||
common.OptionMap["OpenRestyProxyBusyBuffersSize"] = common.OpenRestyProxyBusyBuffersSize
|
||||
common.OptionMap["OpenRestyGzipEnabled"] = strconv.FormatBool(common.OpenRestyGzipEnabled)
|
||||
common.OptionMap["OpenRestyGzipMinLength"] = strconv.Itoa(common.OpenRestyGzipMinLength)
|
||||
common.OptionMap["OpenRestyGzipCompLevel"] = strconv.Itoa(common.OpenRestyGzipCompLevel)
|
||||
common.OptionMap["OpenRestyCacheEnabled"] = strconv.FormatBool(common.OpenRestyCacheEnabled)
|
||||
common.OptionMap["OpenRestyCachePath"] = common.OpenRestyCachePath
|
||||
common.OptionMap["OpenRestyCacheLevels"] = common.OpenRestyCacheLevels
|
||||
common.OptionMap["OpenRestyCacheInactive"] = common.OpenRestyCacheInactive
|
||||
common.OptionMap["OpenRestyCacheMaxSize"] = common.OpenRestyCacheMaxSize
|
||||
common.OptionMap["OpenRestyCacheKeyTemplate"] = common.OpenRestyCacheKeyTemplate
|
||||
common.OptionMap["OpenRestyCacheLockEnabled"] = strconv.FormatBool(common.OpenRestyCacheLockEnabled)
|
||||
common.OptionMap["OpenRestyCacheLockTimeout"] = common.OpenRestyCacheLockTimeout
|
||||
common.OptionMap["OpenRestyCacheUseStale"] = common.OpenRestyCacheUseStale
|
||||
common.OptionMap["OpenRestyMainConfigTemplate"] = common.OpenRestyMainConfigTemplate
|
||||
common.OptionMap["GlobalApiRateLimitNum"] = strconv.Itoa(common.GlobalApiRateLimitNum)
|
||||
common.OptionMap["GlobalApiRateLimitDuration"] = strconv.FormatInt(common.GlobalApiRateLimitDuration, 10)
|
||||
common.OptionMap["GlobalWebRateLimitNum"] = strconv.Itoa(common.GlobalWebRateLimitNum)
|
||||
common.OptionMap["GlobalWebRateLimitDuration"] = strconv.FormatInt(common.GlobalWebRateLimitDuration, 10)
|
||||
common.OptionMap["UploadRateLimitNum"] = strconv.Itoa(common.UploadRateLimitNum)
|
||||
common.OptionMap["UploadRateLimitDuration"] = strconv.FormatInt(common.UploadRateLimitDuration, 10)
|
||||
common.OptionMap["DownloadRateLimitNum"] = strconv.Itoa(common.DownloadRateLimitNum)
|
||||
common.OptionMap["DownloadRateLimitDuration"] = strconv.FormatInt(common.DownloadRateLimitDuration, 10)
|
||||
common.OptionMap["CriticalRateLimitNum"] = strconv.Itoa(common.CriticalRateLimitNum)
|
||||
common.OptionMap["CriticalRateLimitDuration"] = strconv.FormatInt(common.CriticalRateLimitDuration, 10)
|
||||
common.OptionMapRWMutex.Unlock()
|
||||
options, _ := AllOption()
|
||||
for _, option := range options {
|
||||
updateOptionMap(option.Key, option.Value)
|
||||
}
|
||||
}
|
||||
|
||||
func UpdateOption(key string, value string) error {
|
||||
// Save to database first
|
||||
option := Option{
|
||||
Key: key,
|
||||
}
|
||||
// https://gorm.io/docs/update.html#Save-All-Fields
|
||||
DB.FirstOrCreate(&option, Option{Key: key})
|
||||
option.Value = value
|
||||
// Save is a combination function.
|
||||
// If save value does not contain primary key, it will execute Create,
|
||||
// otherwise it will execute Update (with all fields).
|
||||
DB.Save(&option)
|
||||
// Update OptionMap
|
||||
updateOptionMap(key, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func updateOptionMap(key string, value string) {
|
||||
shouldRefreshGeoIP := false
|
||||
common.OptionMapRWMutex.Lock()
|
||||
if common.OptionMap == nil {
|
||||
common.OptionMap = make(map[string]string)
|
||||
}
|
||||
common.OptionMap[key] = value
|
||||
if strings.HasSuffix(key, "Permission") {
|
||||
intValue, _ := strconv.Atoi(value)
|
||||
switch key {
|
||||
case "FileUploadPermission":
|
||||
common.FileUploadPermission = intValue
|
||||
case "FileDownloadPermission":
|
||||
common.FileDownloadPermission = intValue
|
||||
case "ImageUploadPermission":
|
||||
common.ImageUploadPermission = intValue
|
||||
case "ImageDownloadPermission":
|
||||
common.ImageDownloadPermission = intValue
|
||||
}
|
||||
}
|
||||
if strings.HasSuffix(key, "Enabled") {
|
||||
boolValue := value == "true"
|
||||
switch key {
|
||||
case "PasswordRegisterEnabled":
|
||||
common.PasswordRegisterEnabled = boolValue
|
||||
case "PasswordLoginEnabled":
|
||||
common.PasswordLoginEnabled = boolValue
|
||||
case "EmailVerificationEnabled":
|
||||
common.EmailVerificationEnabled = boolValue
|
||||
case "GitHubOAuthEnabled":
|
||||
common.GitHubOAuthEnabled = boolValue
|
||||
case "WeChatAuthEnabled":
|
||||
common.WeChatAuthEnabled = boolValue
|
||||
case "TurnstileCheckEnabled":
|
||||
common.TurnstileCheckEnabled = boolValue
|
||||
case "RegisterEnabled":
|
||||
common.RegisterEnabled = boolValue
|
||||
}
|
||||
}
|
||||
switch key {
|
||||
case "SMTPServer":
|
||||
common.SMTPServer = value
|
||||
case "SMTPPort":
|
||||
intValue, _ := strconv.Atoi(value)
|
||||
common.SMTPPort = intValue
|
||||
case "SMTPAccount":
|
||||
common.SMTPAccount = value
|
||||
case "SMTPToken":
|
||||
common.SMTPToken = value
|
||||
case "ServerAddress":
|
||||
common.ServerAddress = value
|
||||
case "GitHubClientId":
|
||||
common.GitHubClientId = value
|
||||
case "GitHubClientSecret":
|
||||
common.GitHubClientSecret = value
|
||||
case "Footer":
|
||||
common.Footer = value
|
||||
case "HomePageLink":
|
||||
common.HomePageLink = value
|
||||
case "SystemName":
|
||||
common.SystemName = value
|
||||
case "WeChatServerAddress":
|
||||
common.WeChatServerAddress = value
|
||||
case "WeChatServerToken":
|
||||
common.WeChatServerToken = value
|
||||
case "WeChatAccountQRCodeImageURL":
|
||||
common.WeChatAccountQRCodeImageURL = value
|
||||
case "TurnstileSiteKey":
|
||||
common.TurnstileSiteKey = value
|
||||
case "TurnstileSecretKey":
|
||||
common.TurnstileSecretKey = value
|
||||
case "AgentDiscoveryToken":
|
||||
common.AgentDiscoveryToken = value
|
||||
case "AgentHeartbeatInterval":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.AgentHeartbeatInterval = v
|
||||
}
|
||||
case "NodeOfflineThreshold":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.NodeOfflineThreshold = time.Duration(v) * time.Millisecond
|
||||
}
|
||||
case "AgentUpdateRepo":
|
||||
if value != "" {
|
||||
common.AgentUpdateRepo = value
|
||||
}
|
||||
case "GeoIPProvider":
|
||||
if geoip.IsValidProvider(value) {
|
||||
common.GeoIPProvider = value
|
||||
shouldRefreshGeoIP = true
|
||||
}
|
||||
case "OpenRestyWorkerProcesses":
|
||||
if strings.TrimSpace(value) != "" {
|
||||
common.OpenRestyWorkerProcesses = value
|
||||
}
|
||||
case "OpenRestyWorkerConnections":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.OpenRestyWorkerConnections = v
|
||||
}
|
||||
case "OpenRestyWorkerRlimitNofile":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.OpenRestyWorkerRlimitNofile = v
|
||||
}
|
||||
case "OpenRestyEventsUse":
|
||||
common.OpenRestyEventsUse = value
|
||||
case "OpenRestyEventsMultiAcceptEnabled":
|
||||
common.OpenRestyEventsMultiAcceptEnabled = value == "true"
|
||||
case "OpenRestyKeepaliveTimeout":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.OpenRestyKeepaliveTimeout = v
|
||||
}
|
||||
case "OpenRestyKeepaliveRequests":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.OpenRestyKeepaliveRequests = v
|
||||
}
|
||||
case "OpenRestyClientHeaderTimeout":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.OpenRestyClientHeaderTimeout = v
|
||||
}
|
||||
case "OpenRestyClientBodyTimeout":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.OpenRestyClientBodyTimeout = v
|
||||
}
|
||||
case "OpenRestyClientMaxBodySize":
|
||||
if strings.TrimSpace(value) != "" {
|
||||
common.OpenRestyClientMaxBodySize = value
|
||||
}
|
||||
case "OpenRestyLargeClientHeaderBuffers":
|
||||
if strings.TrimSpace(value) != "" {
|
||||
common.OpenRestyLargeClientHeaderBuffers = value
|
||||
}
|
||||
case "OpenRestySendTimeout":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.OpenRestySendTimeout = v
|
||||
}
|
||||
case "OpenRestyProxyConnectTimeout":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.OpenRestyProxyConnectTimeout = v
|
||||
}
|
||||
case "OpenRestyProxySendTimeout":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.OpenRestyProxySendTimeout = v
|
||||
}
|
||||
case "OpenRestyProxyReadTimeout":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.OpenRestyProxyReadTimeout = v
|
||||
}
|
||||
case "OpenRestyWebsocketEnabled":
|
||||
common.OpenRestyWebsocketEnabled = value == "true"
|
||||
case "OpenRestyProxyRequestBufferingEnabled":
|
||||
common.OpenRestyProxyRequestBufferingEnabled = value == "true"
|
||||
case "OpenRestyProxyBufferingEnabled":
|
||||
common.OpenRestyProxyBufferingEnabled = value == "true"
|
||||
case "OpenRestyProxyBuffers":
|
||||
if strings.TrimSpace(value) != "" {
|
||||
common.OpenRestyProxyBuffers = value
|
||||
}
|
||||
case "OpenRestyProxyBufferSize":
|
||||
if strings.TrimSpace(value) != "" {
|
||||
common.OpenRestyProxyBufferSize = value
|
||||
}
|
||||
case "OpenRestyProxyBusyBuffersSize":
|
||||
if strings.TrimSpace(value) != "" {
|
||||
common.OpenRestyProxyBusyBuffersSize = value
|
||||
}
|
||||
case "OpenRestyGzipEnabled":
|
||||
common.OpenRestyGzipEnabled = value == "true"
|
||||
case "OpenRestyGzipMinLength":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.OpenRestyGzipMinLength = v
|
||||
}
|
||||
case "OpenRestyGzipCompLevel":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.OpenRestyGzipCompLevel = v
|
||||
}
|
||||
case "OpenRestyCacheEnabled":
|
||||
common.OpenRestyCacheEnabled = value == "true"
|
||||
case "OpenRestyCachePath":
|
||||
common.OpenRestyCachePath = value
|
||||
case "OpenRestyCacheLevels":
|
||||
if strings.TrimSpace(value) != "" {
|
||||
common.OpenRestyCacheLevels = value
|
||||
}
|
||||
case "OpenRestyCacheInactive":
|
||||
if strings.TrimSpace(value) != "" {
|
||||
common.OpenRestyCacheInactive = value
|
||||
}
|
||||
case "OpenRestyCacheMaxSize":
|
||||
if strings.TrimSpace(value) != "" {
|
||||
common.OpenRestyCacheMaxSize = value
|
||||
}
|
||||
case "OpenRestyCacheKeyTemplate":
|
||||
if strings.TrimSpace(value) != "" {
|
||||
common.OpenRestyCacheKeyTemplate = value
|
||||
}
|
||||
case "OpenRestyCacheLockEnabled":
|
||||
common.OpenRestyCacheLockEnabled = value == "true"
|
||||
case "OpenRestyCacheLockTimeout":
|
||||
if strings.TrimSpace(value) != "" {
|
||||
common.OpenRestyCacheLockTimeout = value
|
||||
}
|
||||
case "OpenRestyCacheUseStale":
|
||||
if strings.TrimSpace(value) != "" {
|
||||
common.OpenRestyCacheUseStale = value
|
||||
}
|
||||
case "OpenRestyMainConfigTemplate":
|
||||
if strings.TrimSpace(value) != "" {
|
||||
common.OpenRestyMainConfigTemplate = value
|
||||
}
|
||||
case "GlobalApiRateLimitNum":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.GlobalApiRateLimitNum = v
|
||||
}
|
||||
case "GlobalApiRateLimitDuration":
|
||||
if v, err := strconv.ParseInt(value, 10, 64); err == nil && v > 0 {
|
||||
common.GlobalApiRateLimitDuration = v
|
||||
}
|
||||
case "GlobalWebRateLimitNum":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.GlobalWebRateLimitNum = v
|
||||
}
|
||||
case "GlobalWebRateLimitDuration":
|
||||
if v, err := strconv.ParseInt(value, 10, 64); err == nil && v > 0 {
|
||||
common.GlobalWebRateLimitDuration = v
|
||||
}
|
||||
case "UploadRateLimitNum":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.UploadRateLimitNum = v
|
||||
}
|
||||
case "UploadRateLimitDuration":
|
||||
if v, err := strconv.ParseInt(value, 10, 64); err == nil && v > 0 {
|
||||
common.UploadRateLimitDuration = v
|
||||
}
|
||||
case "DownloadRateLimitNum":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.DownloadRateLimitNum = v
|
||||
}
|
||||
case "DownloadRateLimitDuration":
|
||||
if v, err := strconv.ParseInt(value, 10, 64); err == nil && v > 0 {
|
||||
common.DownloadRateLimitDuration = v
|
||||
}
|
||||
case "CriticalRateLimitNum":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.CriticalRateLimitNum = v
|
||||
}
|
||||
case "CriticalRateLimitDuration":
|
||||
if v, err := strconv.ParseInt(value, 10, 64); err == nil && v > 0 {
|
||||
common.CriticalRateLimitDuration = v
|
||||
}
|
||||
}
|
||||
common.OptionMapRWMutex.Unlock()
|
||||
if shouldRefreshGeoIP {
|
||||
geoip.InitGeoIP()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type ProxyRoute struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
Domain string `json:"domain" gorm:"uniqueIndex;size:255;not null"`
|
||||
OriginURL string `json:"origin_url" gorm:"size:2048;not null"`
|
||||
Enabled bool `json:"enabled" gorm:"not null;default:true"`
|
||||
EnableHTTPS bool `json:"enable_https" gorm:"column:enable_https;not null;default:false"`
|
||||
CertID *uint `json:"cert_id"`
|
||||
RedirectHTTP bool `json:"redirect_http" gorm:"not null;default:false"`
|
||||
CustomHeaders string `json:"custom_headers" gorm:"type:text;not null;default:'[]'"`
|
||||
Remark string `json:"remark" gorm:"size:255"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func ListProxyRoutes() (routes []*ProxyRoute, err error) {
|
||||
err = DB.Order("id desc").Find(&routes).Error
|
||||
return routes, err
|
||||
}
|
||||
|
||||
func GetEnabledProxyRoutes() (routes []*ProxyRoute, err error) {
|
||||
err = DB.Where("enabled = ?", true).Order("domain asc").Find(&routes).Error
|
||||
return routes, err
|
||||
}
|
||||
|
||||
func GetProxyRouteByID(id uint) (*ProxyRoute, error) {
|
||||
route := &ProxyRoute{}
|
||||
err := DB.First(route, id).Error
|
||||
return route, err
|
||||
}
|
||||
|
||||
func (route *ProxyRoute) Insert() error {
|
||||
return DB.Create(route).Error
|
||||
}
|
||||
|
||||
func (route *ProxyRoute) Update() error {
|
||||
return DB.Model(&ProxyRoute{}).Where("id = ?", route.ID).Updates(map[string]any{
|
||||
"domain": route.Domain,
|
||||
"origin_url": route.OriginURL,
|
||||
"enabled": route.Enabled,
|
||||
"enable_https": route.EnableHTTPS,
|
||||
"cert_id": route.CertID,
|
||||
"redirect_http": route.RedirectHTTP,
|
||||
"custom_headers": route.CustomHeaders,
|
||||
"remark": route.Remark,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (route *ProxyRoute) Delete() error {
|
||||
return DB.Delete(route).Error
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type TLSCertificate struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
Name string `json:"name" gorm:"uniqueIndex;size:255;not null"`
|
||||
CertPEM string `json:"-" gorm:"type:text;not null"`
|
||||
KeyPEM string `json:"-" gorm:"type:text;not null"`
|
||||
NotBefore time.Time `json:"not_before"`
|
||||
NotAfter time.Time `json:"not_after"`
|
||||
Remark string `json:"remark" gorm:"size:255"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func ListTLSCertificates() (certificates []*TLSCertificate, err error) {
|
||||
err = DB.Order("id desc").Find(&certificates).Error
|
||||
return certificates, err
|
||||
}
|
||||
|
||||
func GetTLSCertificateByID(id uint) (*TLSCertificate, error) {
|
||||
certificate := &TLSCertificate{}
|
||||
err := DB.First(certificate, id).Error
|
||||
return certificate, err
|
||||
}
|
||||
|
||||
func (certificate *TLSCertificate) Insert() error {
|
||||
return DB.Create(certificate).Error
|
||||
}
|
||||
|
||||
func (certificate *TLSCertificate) Update() error {
|
||||
return DB.Save(certificate).Error
|
||||
}
|
||||
|
||||
func (certificate *TLSCertificate) Delete() error {
|
||||
return DB.Delete(certificate).Error
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"openflare/common"
|
||||
"openflare/utils/security"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// User if you add sensitive fields, don't forget to clean them in setupLogin function.
|
||||
// Otherwise, the sensitive information will be saved on local storage in plain text!
|
||||
type User struct {
|
||||
Id int `json:"id"`
|
||||
Username string `json:"username" gorm:"unique;index" validate:"max=12"`
|
||||
Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
|
||||
DisplayName string `json:"display_name" gorm:"index" validate:"max=20"`
|
||||
Role int `json:"role" gorm:"type:int;default:1"` // admin, common
|
||||
Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled
|
||||
Token string `json:"token" gorm:"index"`
|
||||
Email string `json:"email" gorm:"index" validate:"max=50"`
|
||||
GitHubId string `json:"github_id" gorm:"column:github_id;index"`
|
||||
WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"`
|
||||
VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database!
|
||||
}
|
||||
|
||||
func GetMaxUserId() int {
|
||||
var user User
|
||||
DB.Last(&user)
|
||||
return user.Id
|
||||
}
|
||||
|
||||
func GetAllUsers(startIdx int, num int) (users []*User, err error) {
|
||||
err = DB.Order("id desc").Limit(num).Offset(startIdx).Select([]string{"id", "username", "display_name", "role", "status", "email"}).Find(&users).Error
|
||||
return users, err
|
||||
}
|
||||
|
||||
func SearchUsers(keyword string) (users []*User, err error) {
|
||||
err = DB.Select([]string{"id", "username", "display_name", "role", "status", "email"}).Where("id = ? or username LIKE ? or email LIKE ? or display_name LIKE ?", keyword, keyword+"%", keyword+"%", keyword+"%").Find(&users).Error
|
||||
return users, err
|
||||
}
|
||||
|
||||
func GetUserById(id int, selectAll bool) (*User, error) {
|
||||
if id == 0 {
|
||||
return nil, errors.New("id 为空!")
|
||||
}
|
||||
user := User{Id: id}
|
||||
var err error = nil
|
||||
if selectAll {
|
||||
err = DB.First(&user, "id = ?", id).Error
|
||||
} else {
|
||||
err = DB.Select([]string{"id", "username", "display_name", "role", "status", "email", "wechat_id", "github_id"}).First(&user, "id = ?", id).Error
|
||||
}
|
||||
return &user, err
|
||||
}
|
||||
|
||||
func DeleteUserById(id int) (err error) {
|
||||
if id == 0 {
|
||||
return errors.New("id 为空!")
|
||||
}
|
||||
user := User{Id: id}
|
||||
return user.Delete()
|
||||
}
|
||||
|
||||
func (user *User) Insert() error {
|
||||
var err error
|
||||
if user.Password != "" {
|
||||
user.Password, err = security.Password2Hash(user.Password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
err = DB.Create(user).Error
|
||||
return err
|
||||
}
|
||||
|
||||
func (user *User) Update(updatePassword bool) error {
|
||||
var err error
|
||||
if updatePassword {
|
||||
user.Password, err = security.Password2Hash(user.Password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
err = DB.Model(user).Updates(user).Error
|
||||
return err
|
||||
}
|
||||
|
||||
func (user *User) Delete() error {
|
||||
if user.Id == 0 {
|
||||
return errors.New("id 为空!")
|
||||
}
|
||||
err := DB.Delete(user).Error
|
||||
return err
|
||||
}
|
||||
|
||||
// ValidateAndFill check password & user status
|
||||
func (user *User) ValidateAndFill() (err error) {
|
||||
// When querying with struct, GORM will only query with non-zero fields,
|
||||
// that means if your field’s value is 0, '', false or other zero values,
|
||||
// it won’t be used to build query conditions
|
||||
password := user.Password
|
||||
if user.Username == "" || password == "" {
|
||||
return errors.New("用户名或密码为空")
|
||||
}
|
||||
DB.Where(User{Username: user.Username}).First(user)
|
||||
okay := security.ValidatePasswordAndHash(password, user.Password)
|
||||
if !okay || user.Status != common.UserStatusEnabled {
|
||||
return errors.New("用户名或密码错误,或用户已被封禁")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (user *User) FillUserById() error {
|
||||
if user.Id == 0 {
|
||||
return errors.New("id 为空!")
|
||||
}
|
||||
DB.Where(User{Id: user.Id}).First(user)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (user *User) FillUserByEmail() error {
|
||||
if user.Email == "" {
|
||||
return errors.New("email 为空!")
|
||||
}
|
||||
DB.Where(User{Email: user.Email}).First(user)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (user *User) FillUserByGitHubId() error {
|
||||
if user.GitHubId == "" {
|
||||
return errors.New("GitHub id 为空!")
|
||||
}
|
||||
DB.Where(User{GitHubId: user.GitHubId}).First(user)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (user *User) FillUserByWeChatId() error {
|
||||
if user.WeChatId == "" {
|
||||
return errors.New("WeChat id 为空!")
|
||||
}
|
||||
DB.Where(User{WeChatId: user.WeChatId}).First(user)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (user *User) FillUserByUsername() error {
|
||||
if user.Username == "" {
|
||||
return errors.New("username 为空!")
|
||||
}
|
||||
DB.Where(User{Username: user.Username}).First(user)
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateUserToken(token string) (user *User) {
|
||||
if token == "" {
|
||||
return nil
|
||||
}
|
||||
token = strings.Replace(token, "Bearer ", "", 1)
|
||||
user = &User{}
|
||||
if DB.Where("token = ?", token).First(user).RowsAffected == 1 {
|
||||
return user
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func IsEmailAlreadyTaken(email string) bool {
|
||||
return DB.Where("email = ?", email).Find(&User{}).RowsAffected == 1
|
||||
}
|
||||
|
||||
func IsWeChatIdAlreadyTaken(wechatId string) bool {
|
||||
return DB.Where("wechat_id = ?", wechatId).Find(&User{}).RowsAffected == 1
|
||||
}
|
||||
|
||||
func IsGitHubIdAlreadyTaken(githubId string) bool {
|
||||
return DB.Where("github_id = ?", githubId).Find(&User{}).RowsAffected == 1
|
||||
}
|
||||
|
||||
func IsUsernameAlreadyTaken(username string) bool {
|
||||
return DB.Where("username = ?", username).Find(&User{}).RowsAffected == 1
|
||||
}
|
||||
|
||||
func ResetUserPasswordByEmail(email string, password string) error {
|
||||
if email == "" || password == "" {
|
||||
return errors.New("邮箱地址或密码为空!")
|
||||
}
|
||||
hashedPassword, err := security.Password2Hash(password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = DB.Model(&User{}).Where("email = ?", email).Update("password", hashedPassword).Error
|
||||
return err
|
||||
}
|
||||
Reference in New Issue
Block a user