97 lines
2.6 KiB
Go
97 lines
2.6 KiB
Go
// 命令行工具 - 重置管理员密码
|
|
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
|
|
"git.zkcoi.com/zkcoi/meshray/internal/config"
|
|
"git.zkcoi.com/zkcoi/meshray/internal/service"
|
|
store "git.zkcoi.com/zkcoi/meshray/internal/store/sqlite"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
// ANSI 颜色代码
|
|
const (
|
|
ColorReset = "\033[0m"
|
|
ColorRed = "\033[31m"
|
|
ColorGreen = "\033[32m"
|
|
ColorYellow = "\033[33m"
|
|
ColorBlue = "\033[34m"
|
|
)
|
|
|
|
var (
|
|
resetPasswordCmd = &cobra.Command{
|
|
Use: "reset-admin-password",
|
|
Short: "重置管理员密码",
|
|
Long: "重置 MeshRay 管理员账户的密码。将生成随机密码并在控制台显示。",
|
|
RunE: runResetPassword,
|
|
}
|
|
|
|
newPassword string
|
|
)
|
|
|
|
func init() {
|
|
resetPasswordCmd.Flags().StringVarP(&newPassword, "new-password", "p", "", "设置新密码(留空则自动生成随机密码)")
|
|
}
|
|
|
|
func runResetPassword(cmd *cobra.Command, args []string) error {
|
|
fmt.Println("MeshRay - 重置管理员密码")
|
|
fmt.Println("=========================")
|
|
fmt.Println("")
|
|
|
|
// 加载配置
|
|
cfg, err := config.Load("")
|
|
if err != nil {
|
|
return fmt.Errorf("加载配置失败:%w", err)
|
|
}
|
|
|
|
// 确保数据库文件存在
|
|
if _, err := os.Stat(cfg.Database.Path); os.IsNotExist(err) {
|
|
return fmt.Errorf("数据库文件不存在:%s", cfg.Database.Path)
|
|
}
|
|
|
|
// 连接数据库
|
|
dbStore, err := store.New(cfg.Database.Path)
|
|
if err != nil {
|
|
return fmt.Errorf("连接数据库失败:%w", err)
|
|
}
|
|
defer dbStore.Close()
|
|
|
|
// 创建用户服务
|
|
userService := service.NewUserService(dbStore)
|
|
|
|
// 生成或使用指定的新密码
|
|
finalPassword := newPassword
|
|
if finalPassword == "" {
|
|
finalPassword = service.GenerateRandomPassword(16)
|
|
}
|
|
|
|
// 重置密码
|
|
err = userService.ResetAdminPassword(finalPassword)
|
|
if err != nil {
|
|
return fmt.Errorf("重置密码失败:%w", err)
|
|
}
|
|
|
|
// 输出结果
|
|
fmt.Println("")
|
|
fmt.Printf("%s========================================%s\n", ColorGreen, ColorReset)
|
|
fmt.Printf("%s✅ 管理员密码已重置%s\n", ColorGreen, ColorReset)
|
|
fmt.Printf("%s========================================%s\n", ColorGreen, ColorReset)
|
|
fmt.Printf("用户名:admin\n")
|
|
fmt.Printf("新密码:%s%s%s\n", ColorBlue, finalPassword, ColorReset)
|
|
fmt.Printf("%s****************************************%s\n", ColorYellow, ColorReset)
|
|
fmt.Printf("%s⚠️ 请妥善保管密码,建议登录后立即修改%s\n", ColorYellow, ColorReset)
|
|
fmt.Printf("%s****************************************%s\n", ColorYellow, ColorReset)
|
|
fmt.Println("")
|
|
|
|
return nil
|
|
}
|
|
|
|
func main() {
|
|
if err := resetPasswordCmd.Execute(); err != nil {
|
|
fmt.Fprintf(os.Stderr, "错误:%v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|