add login
This commit is contained in:
200
backend/main.go
200
backend/main.go
@ -8,18 +8,27 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Server struct {
|
||||
Port string `yaml:"port"`
|
||||
SecretKey string `yaml:"secret_key"`
|
||||
} `yaml:"server"`
|
||||
Database struct {
|
||||
Path string `yaml:"path"`
|
||||
} `yaml:"database"`
|
||||
Admin struct {
|
||||
Username string `yaml:"username"`
|
||||
Password string `yaml:"password"`
|
||||
} `yaml:"admin"`
|
||||
}
|
||||
|
||||
type Site struct {
|
||||
@ -28,13 +37,28 @@ type Site struct {
|
||||
URL string `json:"url"`
|
||||
Icon string `json:"icon,omitempty"`
|
||||
Category string `json:"category"`
|
||||
Order int `json:"order"` // 新增排序字段
|
||||
}
|
||||
|
||||
var db *sql.DB
|
||||
type Credentials struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type Claims struct {
|
||||
Username string `json:"username"`
|
||||
jwt.StandardClaims
|
||||
}
|
||||
|
||||
var (
|
||||
db *sql.DB
|
||||
config *Config
|
||||
)
|
||||
|
||||
func main() {
|
||||
// 加载配置
|
||||
config, err := loadConfig("config/config.yaml")
|
||||
var err error
|
||||
config, err = loadConfig("config/config.yaml")
|
||||
if err != nil {
|
||||
log.Fatalf("Error loading config: %v", err)
|
||||
}
|
||||
@ -47,9 +71,13 @@ func main() {
|
||||
defer db.Close()
|
||||
|
||||
// 设置路由
|
||||
http.HandleFunc("/api/login", loginHandler)
|
||||
http.HandleFunc("/api/sites", sitesHandler)
|
||||
http.HandleFunc("/api/add", addSiteHandler)
|
||||
http.HandleFunc("/api/delete", deleteSiteHandler)
|
||||
http.HandleFunc("/api/sites/order", authMiddleware(updateSitesOrderHandler))
|
||||
http.HandleFunc("/api/sites/add", authMiddleware(addSiteHandler))
|
||||
http.HandleFunc("/api/sites/delete", authMiddleware(deleteSiteHandler))
|
||||
http.HandleFunc("/api/export", authMiddleware(exportHandler))
|
||||
http.HandleFunc("/api/import", authMiddleware(importHandler))
|
||||
|
||||
// 静态文件服务
|
||||
fs := http.FileServer(http.Dir("../frontend"))
|
||||
@ -61,7 +89,7 @@ func main() {
|
||||
}
|
||||
|
||||
func loadConfig(path string) (*Config, error) {
|
||||
config := &Config{}
|
||||
cfg := &Config{}
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -69,16 +97,15 @@ func loadConfig(path string) (*Config, error) {
|
||||
defer file.Close()
|
||||
|
||||
d := yaml.NewDecoder(file)
|
||||
if err := d.Decode(&config); err != nil {
|
||||
if err := d.Decode(&cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return config, nil
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func initDB(dbPath string) error {
|
||||
var err error
|
||||
// 确保数据库目录存在
|
||||
os.MkdirAll(filepath.Dir(dbPath), 0755)
|
||||
|
||||
db, err = sql.Open("sqlite3", dbPath)
|
||||
@ -92,22 +119,110 @@ func initDB(dbPath string) error {
|
||||
name TEXT NOT NULL,
|
||||
url TEXT NOT NULL,
|
||||
icon TEXT,
|
||||
category TEXT NOT NULL
|
||||
category TEXT NOT NULL,
|
||||
sort_order INTEGER DEFAULT 0
|
||||
)`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
func sitesHandler(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
getSites(w, r)
|
||||
default:
|
||||
// 创建管理员表
|
||||
_, err = db.Exec(`CREATE TABLE IF NOT EXISTS admin_users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password TEXT NOT NULL
|
||||
)`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 初始化管理员账户
|
||||
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(config.Admin.Password), bcrypt.DefaultCost)
|
||||
db.Exec("INSERT OR IGNORE INTO admin_users (username, password) VALUES (?, ?)",
|
||||
config.Admin.Username, string(hashedPassword))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func loginHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "POST" {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var creds Credentials
|
||||
if err := json.NewDecoder(r.Body).Decode(&creds); err != nil {
|
||||
http.Error(w, "Bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// 验证用户
|
||||
var storedPassword string
|
||||
err := db.QueryRow("SELECT password FROM admin_users WHERE username = ?", creds.Username).Scan(&storedPassword)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(storedPassword), []byte(creds.Password)); err != nil {
|
||||
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// 创建JWT令牌
|
||||
expirationTime := time.Now().Add(24 * time.Hour)
|
||||
claims := &Claims{
|
||||
Username: creds.Username,
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
ExpiresAt: expirationTime.Unix(),
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
tokenString, err := token.SignedString([]byte(config.Server.SecretKey))
|
||||
if err != nil {
|
||||
http.Error(w, "Error generating token", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// 返回令牌
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"token": tokenString,
|
||||
})
|
||||
}
|
||||
|
||||
func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
http.Error(w, "Authorization header required", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
claims := &Claims{}
|
||||
|
||||
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(config.Server.SecretKey), nil
|
||||
})
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
http.Error(w, "Invalid token", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func getSites(w http.ResponseWriter, r *http.Request) {
|
||||
rows, err := db.Query("SELECT id, name, url, icon, category FROM sites")
|
||||
func sitesHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "GET" {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
rows, err := db.Query("SELECT id, name, url, icon, category, sort_order FROM sites ORDER BY category, sort_order, name")
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@ -117,7 +232,7 @@ func getSites(w http.ResponseWriter, r *http.Request) {
|
||||
var sites []Site
|
||||
for rows.Next() {
|
||||
var s Site
|
||||
if err := rows.Scan(&s.ID, &s.Name, &s.URL, &s.Icon, &s.Category); err != nil {
|
||||
if err := rows.Scan(&s.ID, &s.Name, &s.URL, &s.Icon, &s.Category, &s.Order); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
@ -128,60 +243,39 @@ func getSites(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(sites)
|
||||
}
|
||||
|
||||
func addSiteHandler(w http.ResponseWriter, r *http.Request) {
|
||||
func updateSitesOrderHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "POST" {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var s Site
|
||||
if err := json.NewDecoder(r.Body).Decode(&s); err != nil {
|
||||
var sites []Site
|
||||
if err := json.NewDecoder(r.Body).Decode(&sites); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// 验证数据
|
||||
if s.Name == "" || s.URL == "" || s.Category == "" {
|
||||
http.Error(w, "Name, URL and Category are required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// 插入数据库
|
||||
res, err := db.Exec("INSERT INTO sites (name, url, icon, category) VALUES (?, ?, ?, ?)",
|
||||
s.Name, s.URL, s.Icon, s.Category)
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
id, _ := res.LastInsertId()
|
||||
s.ID = int(id)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(s)
|
||||
}
|
||||
|
||||
func deleteSiteHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "POST" {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var request struct {
|
||||
ID int `json:"id"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
_, err := db.Exec("DELETE FROM sites WHERE id = ?", request.ID)
|
||||
for _, site := range sites {
|
||||
_, err = tx.Exec("UPDATE sites SET sort_order = ? WHERE id = ?", site.Order, site.ID)
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
fmt.Fprint(w, `{"status": "success"}`)
|
||||
}
|
||||
|
||||
// 其他处理函数(addSiteHandler, deleteSiteHandler等)保持不变...
|
@ -1,5 +1,10 @@
|
||||
server:
|
||||
port: "8080" # 服务端口
|
||||
port: "8080"
|
||||
secret_key: "6Sc1OTEaU3n9t80ijBptYYYSEwPx2Y5t" # 用于JWT签名的密钥
|
||||
|
||||
database:
|
||||
path: "data/navigation.db" # 数据库文件路径
|
||||
path: "data/navigation.db"
|
||||
|
||||
admin:
|
||||
username: "admin"
|
||||
password: "123456" # 首次运行后请修改
|
@ -8,6 +8,24 @@
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
|
||||
</head>
|
||||
<body>
|
||||
<!-- 在原有HTML中添加登录模态框 -->
|
||||
<div class="modal" id="loginModal">
|
||||
<div class="modal-content">
|
||||
<span class="close">×</span>
|
||||
<h2><i class="fas fa-sign-in-alt"></i> 管理员登录</h2>
|
||||
<form id="loginForm">
|
||||
<div class="form-group">
|
||||
<label for="username"><i class="fas fa-user"></i> 用户名</label>
|
||||
<input type="text" id="username" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="password"><i class="fas fa-lock"></i> 密码</label>
|
||||
<input type="password" id="password" required>
|
||||
</div>
|
||||
<button type="submit"><i class="fas fa-sign-in-alt"></i> 登录</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="container">
|
||||
<header>
|
||||
<div class="header-left">
|
||||
@ -19,10 +37,13 @@
|
||||
</div>
|
||||
<div class="header-right">
|
||||
<button id="themeBtn"><i class="fas fa-moon"></i></button>
|
||||
<button id="addSiteBtn"><i class="fas fa-plus"></i> 添加网站</button>
|
||||
<button id="manageCategoriesBtn"><i class="fas fa-tags"></i> 管理分类</button>
|
||||
<button id="exportBtn"><i class="fas fa-file-export"></i> 导出</button>
|
||||
<button id="importBtn"><i class="fas fa-file-import"></i> 导入</button>
|
||||
<button id="loginBtn" style="display: none;"><i class="fas fa-sign-in-alt"></i> 登录</button>
|
||||
<button id="logoutBtn" style="display: none;"><i class="fas fa-sign-out-alt"></i> 注销</button>
|
||||
<!-- 管理员按钮默认隐藏 -->
|
||||
<button id="addSiteBtn" style="display: none;"><i class="fas fa-plus"></i> 添加网站</button>
|
||||
<button id="manageCategoriesBtn" style="display: none;"><i class="fas fa-tags"></i> 管理分类</button>
|
||||
<button id="exportBtn" style="display: none;"><i class="fas fa-file-export"></i> 导出</button>
|
||||
<button id="importBtn" style="display: none;"><i class="fas fa-file-import"></i> 导入</button>
|
||||
<input type="file" id="importFile" style="display: none;" accept=".json">
|
||||
</div>
|
||||
</header>
|
||||
|
@ -59,9 +59,6 @@ header {
|
||||
h1 {
|
||||
font-size: 2rem;
|
||||
color: var(--primary-color);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.search-box {
|
||||
@ -87,7 +84,13 @@ h1 {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
button {
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.actions button {
|
||||
padding: 8px 16px;
|
||||
background-color: var(--primary-color);
|
||||
color: white;
|
||||
@ -99,22 +102,21 @@ button {
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
.actions button:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
button i {
|
||||
.actions button i {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.loading, .error {
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.error {
|
||||
color: var(--danger-color);
|
||||
.theme-switcher button {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-color);
|
||||
font-size: 1.2rem;
|
||||
cursor: pointer;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.categories {
|
||||
@ -198,12 +200,12 @@ button i {
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
display: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.site:hover .delete-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
/* 模态框样式 */
|
||||
@ -267,7 +269,8 @@ button i {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.form-group input {
|
||||
.form-group input,
|
||||
.form-group select {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
border: 1px solid var(--border-color);
|
||||
@ -323,9 +326,6 @@ form button:hover {
|
||||
border-radius: 4px;
|
||||
padding: 5px 10px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.add-category {
|
||||
@ -352,3 +352,69 @@ form button:hover {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
/* 拖拽样式 */
|
||||
.sortable-ghost {
|
||||
opacity: 0.5;
|
||||
background: var(--primary-color);
|
||||
}
|
||||
|
||||
.sortable-chosen {
|
||||
box-shadow: 0 0 10px var(--shadow-color);
|
||||
}
|
||||
|
||||
/* 响应式设计 */
|
||||
@media (max-width: 768px) {
|
||||
header {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
.header-left, .header-right {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
.search-box {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.actions {
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.actions button {
|
||||
flex-grow: 1;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.sites {
|
||||
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
|
||||
}
|
||||
|
||||
.add-category {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
/* 添加拖拽相关样式 */
|
||||
.site[draggable="true"] {
|
||||
cursor: grab;
|
||||
}
|
||||
|
||||
.site[draggable="true"]:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.site.dragging {
|
||||
opacity: 0.5;
|
||||
background-color: var(--primary-color);
|
||||
}
|
||||
|
||||
/* 登录按钮样式 */
|
||||
#loginBtn, #logoutBtn {
|
||||
background-color: var(--secondary-color);
|
||||
}
|
Reference in New Issue
Block a user