Finish the install procedure.

This commit is contained in:
zicla
2018-12-06 19:26:11 +08:00
parent b7e8a3c1a1
commit 5e84721435
17 changed files with 242 additions and 448 deletions

View File

@ -1,7 +1,6 @@
package rest
import (
"encoding/json"
"github.com/json-iterator/go"
"io/ioutil"
"time"
@ -31,8 +30,8 @@ var CONFIG = &Config{}
type Config struct {
//默认监听端口号
ServerPort int
//数据库是否配置完备
DBConfigured bool
//网站是否已经完成安装
Installed bool
//上传的文件路径,要求不以/结尾。如果没有指定默认在根目录下的matter文件夹中。eg: /var/www/matter
MatterPath string
//数据库连接信息。
@ -118,37 +117,61 @@ func (this *Config) Init() {
}, nil)
//默认从6010端口启动
CONFIG.ServerPort = 6010
this.ServerPort = 6010
this.ReadFromConfigFile()
}
//系统如果安装好了就调用这个方法。
func (this *Config) ReadFromConfigFile() {
//读取配置文件
filePath := GetConfPath() + "/tank.json"
content, err := ioutil.ReadFile(filePath)
if err != nil {
LOGGER.Warn("即将进入安装过程,无法找到配置文件:%s", filePath)
this.DBConfigured = false
LOGGER.Warn("无法找到配置文件:%s 即将进入安装过程!", filePath)
this.Installed = false
} else {
// 用 json.Unmarshal
err := json.Unmarshal(content, this.Item)
this.Item = &ConfigItem{}
err := jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(content, this.Item)
if err != nil {
LOGGER.Error("配置文件格式错误!")
this.DBConfigured = false
this.Installed = false
return
}
//验证项是否齐全
itemValidate := this.Item.validate()
if !itemValidate {
this.DBConfigured = false
LOGGER.Error("配置文件信息不齐全!")
this.Installed = false
return
}
//使用配置项中的文件路径
if this.Item.MatterPath == "" {
CONFIG.MatterPath = GetHomePath() + "/matter"
this.MatterPath = GetHomePath() + "/matter"
} else {
this.MatterPath = this.Item.MatterPath
}
MakeDirAll(CONFIG.MatterPath)
this.MysqlUrl = GetMysqlUrl(this.Item.MysqlPort, this.Item.MysqlHost, this.Item.MysqlSchema, this.Item.MysqlUsername, this.Item.MysqlPassword)
this.DBConfigured = true
}
//使用配置项中的端口
if this.Item.ServerPort != 0 {
this.ServerPort = this.Item.ServerPort
}
this.MysqlUrl = GetMysqlUrl(this.Item.MysqlPort, this.Item.MysqlHost, this.Item.MysqlSchema, this.Item.MysqlUsername, this.Item.MysqlPassword)
this.Installed = true
LOGGER.Info("使用配置文件:%s", filePath)
LOGGER.Info("上传文件存放路径:%s", this.MatterPath)
}
}
//系统如果安装好了就调用这个方法。
func (this *Config) InstallOk() {
this.ReadFromConfigFile()
}

View File

@ -43,10 +43,7 @@ func (this *Context) Init() {
this.Router = NewRouter()
//如果数据库信息配置好了,就直接打开数据库连接 同时执行Bean的ConfigPost方法
if CONFIG.DBConfigured {
this.OpenDb()
this.configPostBeans()
}
this.InstallOk()
}
@ -173,12 +170,18 @@ func (this *Context) initBeans() {
}
}
//所有配置项完备后执行的方法
func (this *Context) configPostBeans() {
for _, bean := range this.BeanMap {
bean.ConfigPost()
//系统如果安装好了就调用这个方法。
func (this *Context) InstallOk() {
if CONFIG.Installed {
this.OpenDb()
for _, bean := range this.BeanMap {
bean.ConfigPost()
}
}
}
//销毁的方法

View File

@ -73,7 +73,7 @@ func (this *FootprintService) Trace(writer http.ResponseWriter, request *http.Re
}
//有可能DB尚且没有配置 直接打印出内容,并且退出
if CONFIG.DBConfigured {
if CONFIG.Installed {
user := this.findUser(writer, request)
userUuid := ""
if user != nil {

View File

@ -1,87 +0,0 @@
package rest
import (
"fmt"
"github.com/jinzhu/gorm"
)
//首次运行的时候,将自动安装数据库等内容。
func InstallDatabase() {
db, err := gorm.Open("mysql", CONFIG.MysqlUrl)
if err != nil {
LOGGER.Panic(fmt.Sprintf("无法打开%s", CONFIG.MysqlUrl))
}
if db != nil {
defer db.Close()
}
//这个方法只会简单查看表是否存在,不会去比照每个字段的。因此如果用户自己修改表结构将会出现不可预测的错误。
var hasTable = true
downloadToken := &DownloadToken{}
hasTable = db.HasTable(downloadToken)
if !hasTable {
createDownloadToken := "CREATE TABLE `tank20_download_token` (`uuid` char(36) NOT NULL,`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',`matter_uuid` char(36) DEFAULT NULL COMMENT '文件标识',`expire_time` timestamp NULL DEFAULT NULL COMMENT '授权访问的次数',`ip` varchar(45) DEFAULT NULL COMMENT '消费者的ip',`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='下载的token表';"
db = db.Exec(createDownloadToken)
if db.Error != nil {
LOGGER.Panic(db.Error.Error())
}
LOGGER.Info("创建DownloadToken表")
}
matter := &Matter{}
hasTable = db.HasTable(matter)
if !hasTable {
createMatter := "CREATE TABLE `tank20_matter` (`uuid` char(36) NOT NULL,`puuid` varchar(45) DEFAULT NULL COMMENT '上一级的uuid',`user_uuid` char(36) DEFAULT NULL COMMENT '上传的用户id',`dir` tinyint(1) DEFAULT '0' COMMENT '是否是文件夹',`alien` tinyint(1) DEFAULT '0',`name` varchar(255) DEFAULT NULL COMMENT '文件名称',`md5` varchar(45) DEFAULT NULL COMMENT '文件的md5值',`size` bigint(20) DEFAULT '0' COMMENT '文件大小',`privacy` tinyint(1) DEFAULT '0' COMMENT '文件是否是公有的',`path` varchar(255) DEFAULT NULL,`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='file表';"
db = db.Exec(createMatter)
if db.Error != nil {
LOGGER.Panic(db.Error.Error())
}
LOGGER.Info("创建Matter表")
}
preference := &Preference{}
hasTable = db.HasTable(preference)
if !hasTable {
createPreference := "CREATE TABLE `tank20_preference` (`uuid` char(36) NOT NULL,`name` varchar(45) DEFAULT NULL COMMENT '网站名称',`logo_url` varchar(255) DEFAULT NULL,`favicon_url` varchar(255) DEFAULT NULL,`footer_line1` varchar(1024) DEFAULT NULL,`footer_line2` varchar(1024) DEFAULT NULL,`version` varchar(45) DEFAULT NULL,`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='网站偏好设置表';"
db = db.Exec(createPreference)
if db.Error != nil {
LOGGER.Panic(db.Error.Error())
}
LOGGER.Info("创建Preference表")
}
session := &Session{}
hasTable = db.HasTable(session)
if !hasTable {
createSession := "CREATE TABLE `tank20_session` (`uuid` char(36) NOT NULL,`authentication` char(36) DEFAULT NULL COMMENT '认证身份存放在cookie中',`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',`ip` varchar(45) DEFAULT NULL COMMENT '用户的ip地址',`expire_time` timestamp NULL DEFAULT NULL,`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='session表';"
db = db.Exec(createSession)
if db.Error != nil {
LOGGER.Panic(db.Error.Error())
}
LOGGER.Info("创建Session表")
}
uploadToken := &UploadToken{}
hasTable = db.HasTable(uploadToken)
if !hasTable {
createUploadToken := "CREATE TABLE `tank20_upload_token` (`uuid` char(36) NOT NULL,`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',`folder_uuid` char(36) DEFAULT NULL,`matter_uuid` char(36) DEFAULT NULL,`filename` varchar(255) DEFAULT NULL COMMENT '文件后缀名的过滤,可以只允许用户上传特定格式的文件。',`privacy` tinyint(1) DEFAULT '1',`size` bigint(20) DEFAULT '0',`expire_time` timestamp NULL DEFAULT NULL,`ip` varchar(45) DEFAULT NULL COMMENT '消费者的ip',`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='上传的token表';"
db = db.Exec(createUploadToken)
if db.Error != nil {
LOGGER.Panic(db.Error.Error())
}
LOGGER.Info("创建UploadToken表")
}
user := &User{}
hasTable = db.HasTable(user)
if !hasTable {
}
}

View File

@ -3,10 +3,12 @@ package rest
import (
"fmt"
"github.com/jinzhu/gorm"
"github.com/json-iterator/go"
"github.com/nu7hatch/gouuid"
"go/build"
"io/ioutil"
"net/http"
"os"
"regexp"
"strconv"
"time"
@ -69,7 +71,10 @@ func (this *InstallController) RegisterRoutes() map[string]func(writer http.Resp
routeMap["/api/install/verify"] = this.Wrap(this.Verify, USER_ROLE_GUEST)
routeMap["/api/install/table/info/list"] = this.Wrap(this.TableInfoList, USER_ROLE_GUEST)
routeMap["/api/install/create/table"] = this.Wrap(this.CreateTable, USER_ROLE_GUEST)
routeMap["/api/install/admin/list"] = this.Wrap(this.AdminList, USER_ROLE_GUEST)
routeMap["/api/install/create/admin"] = this.Wrap(this.CreateAdmin, USER_ROLE_GUEST)
routeMap["/api/install/validate/admin"] = this.Wrap(this.ValidateAdmin, USER_ROLE_GUEST)
routeMap["/api/install/finish"] = this.Wrap(this.Finish, USER_ROLE_GUEST)
return routeMap
}
@ -97,6 +102,8 @@ func (this *InstallController) openDbConnection(writer http.ResponseWriter, requ
db, err := gorm.Open("mysql", mysqlUrl)
this.PanicError(err)
db.LogMode(true)
return db
}
@ -178,6 +185,46 @@ func (this *InstallController) getTableMeta(gormDb *gorm.DB, entity IBase) (bool
}
//根据表名获取建表SQL语句
func (this *InstallController) getTableMetaList(db *gorm.DB) []*InstallTableInfo {
var tableNames = []IBase{&Dashboard{}, &DownloadToken{}, &Footprint{}, &ImageCache{}, &Matter{}, &Preference{}, &Session{}, UploadToken{}, &User{}}
var installTableInfos []*InstallTableInfo
for _, iBase := range tableNames {
exist, allFields, missingFields := this.getTableMeta(db, iBase)
installTableInfos = append(installTableInfos, &InstallTableInfo{
Name: iBase.TableName(),
TableExist: exist,
AllFields: allFields,
MissingFields: missingFields,
})
}
return installTableInfos
}
//验证表结构是否完整。会直接抛出异常
func (this *InstallController) validateTableMetaList(tableInfoList []*InstallTableInfo) {
for _, tableInfo := range tableInfoList {
if tableInfo.TableExist {
if len(tableInfo.MissingFields) != 0 {
var strs []string
for _, v := range tableInfo.MissingFields {
strs = append(strs, v.DBName)
}
this.PanicBadRequest(fmt.Sprintf("%s 表的以下字段缺失:%v", tableInfo.Name, strs))
}
} else {
this.PanicBadRequest(tableInfo.Name + "表不存在")
}
}
}
//验证数据库连接
func (this *InstallController) Verify(writer http.ResponseWriter, request *http.Request) *WebResult {
@ -194,26 +241,10 @@ func (this *InstallController) Verify(writer http.ResponseWriter, request *http.
//获取需要安装的数据库表
func (this *InstallController) TableInfoList(writer http.ResponseWriter, request *http.Request) *WebResult {
var tableNames = []IBase{&Dashboard{}, &DownloadToken{}, &Footprint{}, &ImageCache{}, &Matter{}, &Preference{}, &Session{}, UploadToken{}, &User{}}
var installTableInfos []*InstallTableInfo
db := this.openDbConnection(writer, request)
defer this.closeDbConnection(db)
for _, iBase := range tableNames {
exist, allFields, missingFields := this.getTableMeta(db, iBase)
installTableInfos = append(installTableInfos, &InstallTableInfo{
Name: iBase.TableName(),
TableExist: exist,
AllFields: allFields,
MissingFields: missingFields,
})
}
return this.Success(installTableInfos)
return this.Success(this.getTableMetaList(db))
}
//创建缺失数据库和表
@ -245,6 +276,27 @@ func (this *InstallController) CreateTable(writer http.ResponseWriter, request *
}
//获取管理员列表(10条记录)
func (this *InstallController) AdminList(writer http.ResponseWriter, request *http.Request) *WebResult {
db := this.openDbConnection(writer, request)
defer this.closeDbConnection(db)
var wp = &WherePair{}
wp = wp.And(&WherePair{Query: "role = ?", Args: []interface{}{USER_ROLE_ADMINISTRATOR}})
count := 0
db = db.Model(&User{}).Where(wp.Query, wp.Args...).Count(&count)
this.PanicError(db.Error)
var users []*User
db = db.Where(wp.Query, wp.Args...).Offset(0).Limit(10).Find(&users)
this.PanicError(db.Error)
return this.Success(users)
}
//创建管理员
func (this *InstallController) CreateAdmin(writer http.ResponseWriter, request *http.Request) *WebResult {
@ -269,6 +321,21 @@ func (this *InstallController) CreateAdmin(writer http.ResponseWriter, request *
this.PanicBadRequest(`超级管理员邮箱必填`)
}
//检查是否有重复。
var count1 int64
db1 := db.Model(&User{}).Where("email = ?", adminEmail).Count(&count1)
this.PanicError(db1.Error)
if count1 > 0 {
this.PanicBadRequest(`该邮箱已存在`)
}
var count2 int64
db2 := db.Model(&User{}).Where("username = ?", adminUsername).Count(&count2)
this.PanicError(db2.Error)
if count2 > 0 {
this.PanicBadRequest(`该用户名已存在`)
}
user := &User{}
timeUUID, _ := uuid.NewV4()
user.Uuid = string(timeUUID.String())
@ -285,8 +352,115 @@ func (this *InstallController) CreateAdmin(writer http.ResponseWriter, request *
user.SizeLimit = -1
user.Status = USER_STATUS_OK
db.Create(user)
db3 := db.Create(user)
this.PanicError(db3.Error)
return this.Success("OK")
}
//(如果数据库中本身存在管理员了)验证管理员
func (this *InstallController) ValidateAdmin(writer http.ResponseWriter, request *http.Request) *WebResult {
db := this.openDbConnection(writer, request)
defer this.closeDbConnection(db)
adminEmail := request.FormValue("adminEmail")
adminPassword := request.FormValue("adminPassword")
//验证超级管理员的信息
if adminEmail == "" {
this.PanicBadRequest(`超级管理员邮箱必填`)
}
if len(adminPassword) < 6 {
this.PanicBadRequest(`超级管理员密码长度至少为6位`)
}
var existEmailUser = &User{}
db = db.Where(&User{Email: adminEmail}).First(existEmailUser)
if db.Error != nil {
this.PanicBadRequest(fmt.Sprintf("%s对应的用户不存在", adminEmail))
}
if !MatchBcrypt(adminPassword, existEmailUser.Password) {
this.PanicBadRequest("邮箱或密码错误")
}
if existEmailUser.Role != USER_ROLE_ADMINISTRATOR {
this.PanicBadRequest("该账号不是管理员")
}
return this.Success("OK")
}
//完成系统安装
func (this *InstallController) Finish(writer http.ResponseWriter, request *http.Request) *WebResult {
mysqlPortStr := request.FormValue("mysqlPort")
mysqlHost := request.FormValue("mysqlHost")
mysqlSchema := request.FormValue("mysqlSchema")
mysqlUsername := request.FormValue("mysqlUsername")
mysqlPassword := request.FormValue("mysqlPassword")
var mysqlPort int
if mysqlPortStr != "" {
tmp, err := strconv.Atoi(mysqlPortStr)
this.PanicError(err)
mysqlPort = tmp
}
//要求数据库连接通畅
db := this.openDbConnection(writer, request)
defer this.closeDbConnection(db)
//要求数据库完整。
tableMetaList := this.getTableMetaList(db)
this.validateTableMetaList(tableMetaList)
//要求至少有一名管理员。
var count1 int64
db1 := db.Model(&User{}).Where("role = ?", USER_ROLE_ADMINISTRATOR).Count(&count1)
this.PanicError(db1.Error)
if count1 == 0 {
this.PanicBadRequest(`请至少配置一名管理员`)
}
var configItem = &ConfigItem{
//默认监听端口号
ServerPort: CONFIG.ServerPort,
//上传的文件路径,要求不以/结尾。如果没有指定默认在根目录下的matter文件夹中。eg: /var/www/matter
MatterPath: CONFIG.MatterPath,
//mysql相关配置。
//数据库端口
MysqlPort: mysqlPort,
//数据库Host
MysqlHost: mysqlHost,
//数据库名字
MysqlSchema: mysqlSchema,
//用户名
MysqlUsername: mysqlUsername,
//密码
MysqlPassword: mysqlPassword,
}
//用json的方式输出返回值。
jsonStr, _ := jsoniter.ConfigCompatibleWithStandardLibrary.Marshal(configItem)
//写入到配置文件中
filePath := GetConfPath() + "/tank.json"
f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777)
this.PanicError(err)
_, err = f.Write(jsonStr)
this.PanicError(err)
err = f.Close()
this.PanicError(err)
//通知配置文件安装完毕。
CONFIG.InstallOk()
//通知全局上下文,说系统安装好了
CONTEXT.InstallOk()
return this.Success("OK")
}

View File

@ -122,7 +122,7 @@ func (this *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)
path := request.URL.Path
if strings.HasPrefix(path, "/api") {
if CONFIG.DBConfigured {
if CONFIG.Installed {
//已安装的模式
//统一处理用户的身份信息。