init
This commit is contained in:
@@ -0,0 +1,202 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"anytunnel/at-admin/app/utils"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/astaxie/beego"
|
||||
)
|
||||
|
||||
type BaseController struct {
|
||||
beego.Controller
|
||||
}
|
||||
|
||||
//验证登录
|
||||
func (this *BaseController) isLogin() bool {
|
||||
passport := beego.AppConfig.String("author.passport")
|
||||
//fmt.Println(passport)
|
||||
cookie := this.Ctx.GetCookie(passport)
|
||||
//cookie 失效
|
||||
if cookie == "" {
|
||||
//fmt.Println("cookie 失效")
|
||||
return false
|
||||
}
|
||||
user := this.GetSession("author")
|
||||
//fmt.Println(user)
|
||||
//session 失效
|
||||
if user == nil {
|
||||
//fmt.Println("session 失效")
|
||||
return false
|
||||
}
|
||||
encrypt := new(utils.Encrypt)
|
||||
cookieValue, _ := encrypt.Base64Decode(cookie)
|
||||
//fmt.Println("get cookie " + cookie)
|
||||
identifyList := strings.Split(cookieValue, "@")
|
||||
//fmt.Println(cookieValue, identifyList)
|
||||
if cookieValue == "" || len(identifyList) != 2 {
|
||||
//fmt.Println("cookieValue 无效")
|
||||
return false
|
||||
}
|
||||
name := identifyList[0]
|
||||
identify := identifyList[1]
|
||||
userValue := user.(map[string]string)
|
||||
|
||||
//对比cookie 和 session name
|
||||
if name != userValue["username"] {
|
||||
//fmt.Println("对比cookie 和 session name 无效")
|
||||
//fmt.Println(userValue)
|
||||
return false
|
||||
}
|
||||
//对比客户端UAG and IP
|
||||
if identify != utils.NewEncrypt().Md5Encode(this.Ctx.Request.UserAgent()+this.getClientIp()+userValue["password"]) {
|
||||
//fmt.Println("对比客户端UAG and IP 无效")
|
||||
return false
|
||||
}
|
||||
//success
|
||||
return true
|
||||
}
|
||||
func (this *BaseController) viewLayoutTitle(title, viewName, layout string) {
|
||||
this.ViewLayoutTitle("", title, viewName, layout)
|
||||
}
|
||||
func (this *BaseController) viewLayout(viewName, layout string) {
|
||||
this.ViewLayout("", viewName, layout)
|
||||
}
|
||||
func (this *BaseController) view(viewName string) {
|
||||
this.View("", viewName)
|
||||
}
|
||||
func (this *BaseController) viewTitle(title, viewName string) {
|
||||
this.ViewTitle("", title, viewName)
|
||||
}
|
||||
func (this *BaseController) ViewLayoutTitle(module, title, viewName, layout string) {
|
||||
if module != "" {
|
||||
this.Layout = "layout/modules/" + module + "/" + layout + ".html"
|
||||
this.TplName = "modules/" + module + "/" + viewName + ".html"
|
||||
} else {
|
||||
this.Layout = "layout/" + layout + ".html"
|
||||
this.TplName = viewName + ".html"
|
||||
}
|
||||
this.Data["title"] = title
|
||||
this.Render()
|
||||
}
|
||||
func (this *BaseController) ViewLayout(module, viewName, layout string) {
|
||||
if module != "" {
|
||||
this.Layout = "layout/modules/" + module + "/" + layout + ".html"
|
||||
this.TplName = "modules/" + module + "/" + viewName + ".html"
|
||||
} else {
|
||||
this.Layout = "layout/" + layout + ".html"
|
||||
this.TplName = viewName + ".html"
|
||||
}
|
||||
this.Data["title"] = ""
|
||||
this.Render()
|
||||
}
|
||||
func (this *BaseController) View(module, viewName string) {
|
||||
if module != "" {
|
||||
this.Layout = "layout/modules/" + module + "/default.html"
|
||||
this.TplName = "modules/" + module + "/" + viewName + ".html"
|
||||
} else {
|
||||
this.Layout = "layout/default.html"
|
||||
this.TplName = viewName + ".html"
|
||||
}
|
||||
this.Data["title"] = ""
|
||||
this.Render()
|
||||
}
|
||||
func (this *BaseController) ViewTitle(module, title, viewName string) {
|
||||
if module != "" {
|
||||
this.Layout = "layout/modules/" + module + "/default.html"
|
||||
this.TplName = "modules/" + module + "/" + viewName + ".html"
|
||||
} else {
|
||||
this.Layout = "layout/default.html"
|
||||
this.TplName = viewName + ".html"
|
||||
}
|
||||
this.Data["title"] = title
|
||||
this.Render()
|
||||
}
|
||||
func (this *BaseController) ViewError(errorMessage string, data ...interface{}) {
|
||||
this.viewError(errorMessage, data...)
|
||||
}
|
||||
func (this *BaseController) viewError(errorMessage string, data ...interface{}) {
|
||||
this.Layout = "layout/default.html"
|
||||
errorType := "500"
|
||||
if len(data) > 0 {
|
||||
errorType = data[0].(string)
|
||||
}
|
||||
this.TplName = "error/" + errorType + ".html"
|
||||
this.Data["title"] = "system error"
|
||||
this.Data["errorMessage"] = errorMessage
|
||||
this.Render()
|
||||
}
|
||||
func (this *BaseController) JsonSuccess(message interface{}, data ...interface{}) {
|
||||
this.jsonSuccess(message, data...)
|
||||
}
|
||||
|
||||
func (this *BaseController) jsonSuccess(message interface{}, data ...interface{}) {
|
||||
url := ""
|
||||
sleep := 500
|
||||
var _data interface{}
|
||||
if len(data) > 0 {
|
||||
_data = data[0]
|
||||
}
|
||||
if len(data) > 1 {
|
||||
url = data[1].(string)
|
||||
}
|
||||
if len(data) > 2 {
|
||||
sleep = data[2].(int)
|
||||
}
|
||||
|
||||
this.Data["json"] = JSONResponse{
|
||||
Code: 1,
|
||||
Message: message,
|
||||
Data: _data,
|
||||
Redirect: map[string]interface{}{
|
||||
"url": url,
|
||||
"sleep": sleep,
|
||||
},
|
||||
}
|
||||
//this.ServeJSON()
|
||||
j, err := json.MarshalIndent(this.Data["json"], "", "\t")
|
||||
if err != nil {
|
||||
this.Abort(err.Error())
|
||||
} else {
|
||||
this.Abort(string(j))
|
||||
}
|
||||
|
||||
}
|
||||
func (this *BaseController) JsonError(message interface{}, data ...interface{}) {
|
||||
this.jsonError(message, data...)
|
||||
}
|
||||
func (this *BaseController) jsonError(message interface{}, data ...interface{}) {
|
||||
url := ""
|
||||
sleep := 500
|
||||
var _data interface{}
|
||||
if len(data) > 0 {
|
||||
_data = data[0]
|
||||
}
|
||||
if len(data) > 1 {
|
||||
url = data[1].(string)
|
||||
}
|
||||
if len(data) > 2 {
|
||||
sleep = data[2].(int)
|
||||
}
|
||||
this.Data["json"] = JSONResponse{
|
||||
Code: 0,
|
||||
Message: message,
|
||||
Data: _data,
|
||||
Redirect: map[string]interface{}{
|
||||
"url": url,
|
||||
"sleep": sleep,
|
||||
},
|
||||
}
|
||||
j, err := json.MarshalIndent(this.Data["json"], "", " \t")
|
||||
if err != nil {
|
||||
this.Abort(err.Error())
|
||||
} else {
|
||||
this.Abort(string(j))
|
||||
}
|
||||
}
|
||||
|
||||
//获取用户IP地址
|
||||
func (this *BaseController) getClientIp() string {
|
||||
s := strings.Split(this.Ctx.Request.RemoteAddr, ":")
|
||||
return s[0]
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"anytunnel/at-admin/app/models"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type JSONResponse struct {
|
||||
Code int `json:"code"`
|
||||
Message interface{} `json:"message"`
|
||||
Data interface{} `json:"data"`
|
||||
Redirect map[string]interface{} `json:"redirect"`
|
||||
}
|
||||
type BaseAdminController struct {
|
||||
BaseController
|
||||
loginUser map[string]string
|
||||
}
|
||||
|
||||
func (this *BaseAdminController) Prepare() {
|
||||
if !this.isLogin() {
|
||||
this.Redirect("/login/index.html", 302)
|
||||
this.StopRun()
|
||||
}
|
||||
user := this.GetSession("author").(map[string]string)
|
||||
this.Data["loginUser"] = user
|
||||
this.loginUser = user
|
||||
this.checkAccess()
|
||||
this.Data["TimeNowYear"] = time.Now().Format("2006")
|
||||
this.Layout = "layout/default.html"
|
||||
}
|
||||
func (this *BaseAdminController) checkAccess() {
|
||||
controllerName, actionName := this.GetControllerAndAction()
|
||||
controllerName = strings.ToLower(controllerName[0 : len(controllerName)-10])
|
||||
actionName = strings.ToLower(actionName)
|
||||
if (controllerName == "main" && actionName == "index") || controllerName == "main" && actionName == "default" {
|
||||
return
|
||||
}
|
||||
//检查权限
|
||||
if "1" != this.loginUser["user_id"] {
|
||||
privilege := models.Privilege{}
|
||||
_, _, controllers, err := privilege.GetTypedPrivileges(this.loginUser["user_id"], "-1")
|
||||
if err != nil {
|
||||
this.jsonError(err.Error(), "")
|
||||
}
|
||||
found := false
|
||||
for _, c := range controllers {
|
||||
action := strings.ToLower(c["action"])
|
||||
if strings.Contains(action, ".") {
|
||||
action = action[:strings.LastIndex(action, ".")]
|
||||
}
|
||||
if controllerName == strings.ToLower(c["controller"]) && actionName == action {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
if this.IsAjax() {
|
||||
this.jsonError("您无权限进行此操作")
|
||||
} else {
|
||||
this.viewError("您无权限进行此操作")
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,96 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"anytunnel/at-admin/app/models"
|
||||
"anytunnel/at-admin/app/utils"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"strings"
|
||||
|
||||
"github.com/afocus/captcha"
|
||||
"github.com/astaxie/beego"
|
||||
)
|
||||
|
||||
var (
|
||||
cap = captcha.New()
|
||||
)
|
||||
|
||||
func init() {
|
||||
bs, _ := utils.NewEncrypt().Base64DecodeBytes(fontData)
|
||||
cap.AddFontFromBytes(bs)
|
||||
}
|
||||
|
||||
type LoginController struct {
|
||||
BaseController
|
||||
}
|
||||
|
||||
func (this *LoginController) Index() {
|
||||
this.Layout = "layout/login.html"
|
||||
this.TplName = "login/login.html"
|
||||
this.Data["title"] = beego.AppConfig.String("sys.name") + "登录"
|
||||
this.Render()
|
||||
}
|
||||
|
||||
//login
|
||||
func (this *LoginController) Login() {
|
||||
if this.isLogin() {
|
||||
return
|
||||
}
|
||||
userModel := models.User{}
|
||||
name := strings.TrimSpace(this.GetString("username"))
|
||||
password := strings.TrimSpace(this.GetString("password"))
|
||||
captcha := strings.TrimSpace(this.GetString("captcha"))
|
||||
captchaSession := this.GetSession("captcha")
|
||||
if captchaSession == nil || captcha == "" || captchaSession != strings.ToLower(captcha) {
|
||||
this.SetSession("captcha", "")
|
||||
this.jsonError("验证码错误!")
|
||||
}
|
||||
this.SetSession("captcha", "")
|
||||
user, err := userModel.GetUserByName(name)
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
return
|
||||
}
|
||||
if len(user) == 0 {
|
||||
this.jsonError("账号错误!")
|
||||
}
|
||||
encrypt := new(utils.Encrypt)
|
||||
password = userModel.EncodePassword(password)
|
||||
|
||||
if user["password"] != password {
|
||||
this.jsonError("账号或密码错误!")
|
||||
}
|
||||
//加载权限列表
|
||||
|
||||
//保存 session
|
||||
this.SetSession("author", user)
|
||||
//保存 cookie
|
||||
identify := encrypt.Md5Encode(this.Ctx.Request.UserAgent() + this.getClientIp() + password)
|
||||
passportValue := encrypt.Base64Encode(name + "@" + identify)
|
||||
passport := beego.AppConfig.String("author.passport")
|
||||
//fmt.Println("set cookie " + passportValue)
|
||||
this.Ctx.SetCookie(passport, passportValue, 3600)
|
||||
|
||||
this.jsonSuccess("登录成功", "", "/main/index.html")
|
||||
}
|
||||
|
||||
//logout
|
||||
func (this *LoginController) Logout() {
|
||||
passport := beego.AppConfig.String("author.passport")
|
||||
this.Ctx.SetCookie(passport, "")
|
||||
this.SetSession("author", "")
|
||||
this.Redirect("/login/index.html", 302)
|
||||
this.StopRun()
|
||||
}
|
||||
|
||||
func (this *LoginController) Captcha() {
|
||||
//bs, _ := ioutil.ReadFile("static/index/comic.ttf")
|
||||
//ioutil.WriteFile("a.txt", utils.NewEncrypt().Base64EncodeBytes(bs), os.ModeAppend)
|
||||
cap.SetSize(80, 28)
|
||||
cap.SetDisturbance(captcha.NORMAL)
|
||||
cap.SetFrontColor(color.RGBA{255, 255, 255, 255})
|
||||
cap.SetBkgColor(color.RGBA{255, 100, 100, 100})
|
||||
img, str := cap.Create(4, captcha.ALL)
|
||||
this.SetSession("captcha", strings.ToLower(str))
|
||||
png.Encode(this.Ctx.ResponseWriter, img)
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"anytunnel/at-admin/app/models"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
|
||||
"github.com/astaxie/beego"
|
||||
)
|
||||
|
||||
type MainController struct {
|
||||
BaseAdminController
|
||||
}
|
||||
|
||||
func (this *MainController) Default() {
|
||||
if this.Ctx.Input.IsGet() {
|
||||
this.view("main/default")
|
||||
} else {
|
||||
data := map[string]interface{}{}
|
||||
db := models.G.DB("base")
|
||||
rs, err := db.Query(db.AR().Select("count(*) as total,cs_type").From("online").GroupBy("cs_type"))
|
||||
if err != nil {
|
||||
this.jsonError(err.Error())
|
||||
}
|
||||
d := rs.MapValues("cs_type", "total")
|
||||
clients := "0"
|
||||
servers := "0"
|
||||
if v, ok := d["client"]; ok {
|
||||
clients = v
|
||||
}
|
||||
if v, ok := d["server"]; ok {
|
||||
servers = v
|
||||
}
|
||||
rs, err = db.Query(db.AR().Select("count(*) as total").From("cluster").Where(map[string]interface{}{
|
||||
"update_time >": time.Now().Unix() - 60,
|
||||
"is_disable": 0,
|
||||
"is_delete": 0,
|
||||
}))
|
||||
if err != nil {
|
||||
this.jsonError(err.Error())
|
||||
}
|
||||
clusters := rs.Value("total")
|
||||
|
||||
now := time.Now().Unix()
|
||||
|
||||
rs, err = db.Query(db.AR().Select("sum(bytes_total) as total").From("package").Where(map[string]interface{}{
|
||||
"start_time <=": now,
|
||||
"end_time >=": now,
|
||||
}))
|
||||
if err != nil {
|
||||
this.jsonError(err.Error())
|
||||
}
|
||||
traffic := rs.Value("total")
|
||||
if traffic == "" {
|
||||
traffic = "0"
|
||||
}
|
||||
rs, err = db.Query(db.AR().Select("sum(bytes_left) as total").From("package").Where(map[string]interface{}{
|
||||
"start_time <=": now,
|
||||
"end_time >=": now,
|
||||
}))
|
||||
if err != nil {
|
||||
this.jsonError(err.Error())
|
||||
}
|
||||
trafficLeft := rs.Value("total")
|
||||
if trafficLeft == "" {
|
||||
trafficLeft = "0"
|
||||
}
|
||||
data["online"] = map[string]interface{}{
|
||||
"client": clients,
|
||||
"server": servers,
|
||||
"cluster": clusters,
|
||||
}
|
||||
_traffic, _ := strconv.Atoi(traffic)
|
||||
_trafficLeft, _ := strconv.Atoi(trafficLeft)
|
||||
_trafficUse := _traffic - _trafficLeft
|
||||
data["traffic"] = map[string]interface{}{
|
||||
"total": traffic,
|
||||
"total_human": humanize.Bytes(uint64(_traffic)),
|
||||
"total_left": _trafficLeft,
|
||||
"total_left_human": humanize.Bytes(uint64(_trafficLeft)),
|
||||
"total_use": _trafficUse,
|
||||
"total_use_human": humanize.Bytes(uint64(_trafficUse)),
|
||||
}
|
||||
this.jsonSuccess("", data)
|
||||
}
|
||||
}
|
||||
func (this *MainController) Index() {
|
||||
this.Layout = "layout/main.html"
|
||||
this.TplName = "main/index.html"
|
||||
this.Data["title"] = fmt.Sprintf("%s - %s", beego.AppConfig.String("sys.name"), beego.AppConfig.String("sys.fullname"))
|
||||
privilege := models.Privilege{}
|
||||
navigators, menus, controllers, err := privilege.GetTypedPrivileges(this.loginUser["user_id"], "1")
|
||||
if err != nil {
|
||||
this.jsonError(err, "")
|
||||
}
|
||||
this.Data["navigators"] = navigators
|
||||
this.Data["menus"] = menus
|
||||
this.Data["controllers"] = controllers
|
||||
this.Render()
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"anytunnel/at-admin/app/models"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/go-ozzo/ozzo-validation"
|
||||
)
|
||||
|
||||
type PrivilegeController struct {
|
||||
BaseAdminController
|
||||
}
|
||||
|
||||
func (this *PrivilegeController) Delete() {
|
||||
privilegeModel := models.Privilege{}
|
||||
privilegeId := this.GetString("privilege_id")
|
||||
privilege, err := privilegeModel.GetPrivilegeByPrivilegeId(privilegeId)
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
}
|
||||
hasSub, err := privilegeModel.HasSub(privilegeId)
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
}
|
||||
if privilege["type"] != "controller" && hasSub {
|
||||
this.jsonError("子菜单非空,不能删除")
|
||||
}
|
||||
err = privilegeModel.Delete(privilegeId)
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
}
|
||||
this.jsonSuccess("")
|
||||
|
||||
}
|
||||
func (this *PrivilegeController) Add() {
|
||||
privilegeModel := models.Privilege{}
|
||||
if this.Ctx.Input.IsPost() {
|
||||
_, data := this.getPrivilegeFromPost(false)
|
||||
_, err := privilegeModel.Insert(data)
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
}
|
||||
this.jsonSuccess("")
|
||||
} else {
|
||||
navigators, menus, _, err := privilegeModel.GetTypedPrivileges("1", "-1")
|
||||
if err != nil {
|
||||
this.jsonError(err, "")
|
||||
}
|
||||
this.Data["navigators"] = navigators
|
||||
this.Data["menus"] = menus
|
||||
this.Data["action"] = "add"
|
||||
this.viewLayout("privilege/form", "form")
|
||||
}
|
||||
|
||||
}
|
||||
func (this *PrivilegeController) Edit() {
|
||||
privilegeModel := models.Privilege{}
|
||||
privilegeId := this.GetString("privilege_id")
|
||||
if this.Ctx.Input.IsPost() {
|
||||
_, data := this.getPrivilegeFromPost(true)
|
||||
_, err := privilegeModel.Update(privilegeId, data)
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
}
|
||||
this.jsonSuccess("")
|
||||
} else {
|
||||
navigators, menus, _, err := privilegeModel.GetTypedPrivileges("1", "-1")
|
||||
if err != nil {
|
||||
this.jsonError(err, "")
|
||||
}
|
||||
privilege, err := privilegeModel.GetPrivilegeByPrivilegeId(privilegeId)
|
||||
if err != nil {
|
||||
this.jsonError(err, "")
|
||||
}
|
||||
if len(privilege) == 0 {
|
||||
this.jsonError("权限不存在")
|
||||
}
|
||||
this.Data["privilege"] = privilege
|
||||
this.Data["navigators"] = navigators
|
||||
this.Data["menus"] = menus
|
||||
this.Data["action"] = "edit"
|
||||
this.viewLayout("privilege/form", "form")
|
||||
}
|
||||
|
||||
}
|
||||
func (this *PrivilegeController) getPrivilegeFromPost(isUpdate bool) (privilegeId string, privilege map[string]interface{}) {
|
||||
parentId := 0
|
||||
if this.GetString("type") == "menu" {
|
||||
parentId, _ = this.GetInt("parent_n")
|
||||
} else if this.GetString("type") == "controller" {
|
||||
parentId, _ = this.GetInt("parent_m")
|
||||
}
|
||||
privilege = map[string]interface{}{
|
||||
"name": this.GetString("name"),
|
||||
"parent_id": parentId,
|
||||
"type": this.GetString("type"),
|
||||
"controller": this.GetString("controller"),
|
||||
"action": this.GetString("action"),
|
||||
"icon": this.GetString("icon"),
|
||||
"is_display": this.GetString("is_display"),
|
||||
"sequence": this.GetString("sequence"),
|
||||
"target": this.GetString("target"),
|
||||
}
|
||||
err := validation.Errors{
|
||||
"名称": validation.Validate(privilege["name"],
|
||||
validation.Required.Error("不能为空"),
|
||||
validation.Match(regexp.MustCompile("^.{1,15}$")).Error("长度必须是1-15字符")),
|
||||
"类型": validation.Validate(privilege["type"],
|
||||
validation.Required.Error("不能为空"),
|
||||
validation.In("navigator", "menu", "controller").Error("错误")),
|
||||
"排序": validation.Validate(privilege["sequence"],
|
||||
validation.Required.Error("不能为空"),
|
||||
validation.Match(regexp.MustCompile("^[1-9]{1}[0-9]*$")).Error("必须是大于0的数字")),
|
||||
}.Filter()
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
}
|
||||
if isUpdate {
|
||||
privilege["update_time"] = time.Now().Unix()
|
||||
} else {
|
||||
privilege["create_time"] = time.Now().Unix()
|
||||
}
|
||||
if this.GetString("type") != "controller" {
|
||||
privilege["is_display"] = 1
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 权限列表
|
||||
func (this *PrivilegeController) List() {
|
||||
privilegeModel := new(models.Privilege)
|
||||
|
||||
navigators, menus, controllers, err := privilegeModel.GetTypedPrivileges("1", "-1")
|
||||
if err != nil {
|
||||
this.viewError(err.Error())
|
||||
}
|
||||
|
||||
this.Data["navigators"] = navigators
|
||||
this.Data["menus"] = menus
|
||||
this.Data["controllers"] = controllers
|
||||
|
||||
this.view("privilege/list")
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"anytunnel/at-admin/app/models"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation"
|
||||
)
|
||||
|
||||
type RoleController struct {
|
||||
BaseAdminController
|
||||
}
|
||||
|
||||
func (this *RoleController) Delete() {
|
||||
roleModel := models.Role{}
|
||||
roleId := this.GetString("role_id")
|
||||
hasUser, err := roleModel.HasUser(roleId)
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
}
|
||||
if hasUser {
|
||||
this.jsonError("角色用户非空,不能删除")
|
||||
}
|
||||
err = roleModel.Delete(roleId)
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
}
|
||||
this.jsonSuccess("")
|
||||
|
||||
}
|
||||
func (this *RoleController) Add() {
|
||||
roleModel := models.Role{}
|
||||
if this.Ctx.Input.IsPost() {
|
||||
_, data := this.getRoleFromPost(false)
|
||||
_, err := roleModel.Insert(data)
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
}
|
||||
this.jsonSuccess("")
|
||||
} else {
|
||||
|
||||
this.Data["action"] = "add"
|
||||
this.viewLayout("role/form", "form")
|
||||
}
|
||||
|
||||
}
|
||||
func (this *RoleController) Edit() {
|
||||
roleModel := models.Role{}
|
||||
roleId := this.GetString("role_id")
|
||||
if this.Ctx.Input.IsPost() {
|
||||
_, data := this.getRoleFromPost(true)
|
||||
_, err := roleModel.Update(roleId, data)
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
}
|
||||
this.jsonSuccess("")
|
||||
} else {
|
||||
role, err := roleModel.GetRoleByRoleId(roleId)
|
||||
if err != nil {
|
||||
this.jsonError(err, "")
|
||||
}
|
||||
if len(role) == 0 {
|
||||
this.jsonError("角色不存在")
|
||||
}
|
||||
this.Data["role"] = role
|
||||
this.Data["action"] = "edit"
|
||||
this.viewLayout("role/form", "form")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (this *RoleController) List() {
|
||||
roleModel := models.Role{}
|
||||
|
||||
roles, err := roleModel.GetAllRoles()
|
||||
if err != nil {
|
||||
this.viewError(err.Error())
|
||||
}
|
||||
|
||||
this.Data["roles"] = roles
|
||||
this.view("role/list")
|
||||
}
|
||||
|
||||
func (this *RoleController) getRoleFromPost(isUpdate bool) (roleId string, role map[string]interface{}) {
|
||||
role = map[string]interface{}{
|
||||
"name": this.GetString("name"),
|
||||
"is_delete": 0,
|
||||
}
|
||||
err := validation.Validate(role["name"],
|
||||
validation.Required.Error("名称不能为空"),
|
||||
validation.Match(regexp.MustCompile("^.{1,15}$")).Error("名称长度必须是1-15字符"))
|
||||
if err != nil {
|
||||
this.jsonError(err.Error())
|
||||
}
|
||||
if isUpdate {
|
||||
role["update_time"] = time.Now().Unix()
|
||||
} else {
|
||||
role["create_time"] = time.Now().Unix()
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package controllers
|
||||
|
||||
import "anytunnel/at-admin/app/models"
|
||||
|
||||
type Role_PrivilegeController struct {
|
||||
BaseAdminController
|
||||
}
|
||||
|
||||
//角色授权
|
||||
func (this *Role_PrivilegeController) Add() {
|
||||
|
||||
roleId, err := this.GetInt("role_id", 0)
|
||||
if roleId == 0 {
|
||||
this.viewError("role_id is error! ")
|
||||
}
|
||||
|
||||
rolePrivilegeModel := models.RolePrivilege{}
|
||||
rolePrivileges, err := rolePrivilegeModel.GetRolePrivilegesByRoleId(roleId)
|
||||
if err != nil {
|
||||
this.viewError(err.Error())
|
||||
}
|
||||
|
||||
privilegeModel := models.Privilege{}
|
||||
navigators, menus, controllers, err := privilegeModel.GetTypedPrivileges("1", "-1")
|
||||
if err != nil {
|
||||
this.viewError(err.Error())
|
||||
}
|
||||
|
||||
this.Data["navigators"] = navigators
|
||||
this.Data["menus"] = menus
|
||||
this.Data["controllers"] = controllers
|
||||
this.Data["rolePrivileges"] = rolePrivileges
|
||||
this.Data["privileges"] = rolePrivileges
|
||||
this.Data["role_id"] = roleId
|
||||
|
||||
this.viewLayout("role/privilege", "form")
|
||||
}
|
||||
|
||||
func (this *Role_PrivilegeController) Save() {
|
||||
|
||||
privilegeIds := this.GetStrings("privilege_id", []string{})
|
||||
roleId, err := this.GetInt("role_id", 0)
|
||||
|
||||
if err != nil {
|
||||
this.jsonError("角色授权失败:role_id error " + err.Error())
|
||||
}
|
||||
if roleId == 0 {
|
||||
this.jsonError("角色授权失败:role_id is error!")
|
||||
}
|
||||
if len(privilegeIds) == 0 {
|
||||
this.jsonError("角色授权失败:no select privilege!")
|
||||
}
|
||||
|
||||
rolePrivilegeModel := models.RolePrivilege{}
|
||||
|
||||
res, err := rolePrivilegeModel.GrantRolePrivileges(roleId, privilegeIds)
|
||||
if !res {
|
||||
this.jsonError("角色授权失败:" + err.Error())
|
||||
}
|
||||
|
||||
this.jsonSuccess("角色授权成功")
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package controllers
|
||||
|
||||
type SystemController struct {
|
||||
BaseAdminController
|
||||
}
|
||||
|
||||
func (this *SystemController) Base() {
|
||||
this.Layout = "layout/page.html"
|
||||
this.TplName = "system/base.html"
|
||||
this.Render()
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"anytunnel/at-admin/app/models"
|
||||
"anytunnel/at-admin/app/utils"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"fmt"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation"
|
||||
"github.com/go-ozzo/ozzo-validation/is"
|
||||
)
|
||||
|
||||
type UserController struct {
|
||||
BaseAdminController
|
||||
}
|
||||
|
||||
func (this *UserController) Forbidden() {
|
||||
userModel := models.User{}
|
||||
userId := this.GetString("user_id")
|
||||
if userId == "1" {
|
||||
this.jsonError("系统用户不能禁用")
|
||||
}
|
||||
err := userModel.Forbidden(userId)
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
}
|
||||
this.jsonSuccess("")
|
||||
|
||||
}
|
||||
|
||||
func (this *UserController) Review() {
|
||||
userModel := models.User{}
|
||||
userId := this.GetString("user_id")
|
||||
if userId == "1" {
|
||||
this.jsonError("系统用户不能操作")
|
||||
}
|
||||
err := userModel.Review(userId)
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
}
|
||||
this.jsonSuccess("")
|
||||
|
||||
}
|
||||
func (this *UserController) ChangePassword() {
|
||||
userModel := models.User{}
|
||||
if this.Ctx.Input.IsPost() {
|
||||
newpassword := this.GetString("password")
|
||||
oldpassword := this.GetString("password_old")
|
||||
errs := validation.Errors{
|
||||
"旧密码": validation.Validate(oldpassword,
|
||||
validation.Required.Error("不能为空")),
|
||||
"新密码": validation.Validate(newpassword,
|
||||
validation.Required.Error("不能为空"),
|
||||
validation.Match(regexp.MustCompile("^([0-9]+[a-zA-Z]+[_]*){1,16}$")).Error("必须同时包含数字和字母,且1-15字符")),
|
||||
}
|
||||
err := errs.Filter()
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
}
|
||||
err = userModel.ChangePassword(this.loginUser["user_id"], newpassword, oldpassword)
|
||||
if err != nil {
|
||||
this.jsonError("修改密码失败:" + err.Error())
|
||||
}
|
||||
this.jsonSuccess("")
|
||||
} else {
|
||||
this.viewLayout("user/changepassword", "form")
|
||||
}
|
||||
}
|
||||
func (this *UserController) Add() {
|
||||
userModel := models.User{}
|
||||
roleModel := models.Role{}
|
||||
userRoleModel := models.UserRole{}
|
||||
|
||||
if this.Ctx.Input.IsPost() {
|
||||
_, data := this.getUserFromPost(false)
|
||||
username := this.GetString("username")
|
||||
roleIds := this.GetStrings("role_ids", []string{})
|
||||
if len(roleIds) == 0 {
|
||||
this.jsonError("没有选择角色")
|
||||
}
|
||||
HasUsername, err := userModel.HasUsername(username)
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
}
|
||||
if HasUsername {
|
||||
this.jsonError("用户名已经存在")
|
||||
}
|
||||
userId, err := userModel.Insert(data)
|
||||
if err != nil {
|
||||
this.jsonError("添加用户失败:" + err.Error())
|
||||
}
|
||||
|
||||
//添加用户与角色对应关系
|
||||
_, err = userRoleModel.Insert(utils.NewConvert().IntToString(userId, 10), roleIds)
|
||||
if err != nil {
|
||||
this.jsonError("添加用户角色失败:" + err.Error())
|
||||
}
|
||||
|
||||
this.jsonSuccess("")
|
||||
} else {
|
||||
|
||||
roles := []map[string]string{}
|
||||
allRoles, _ := roleModel.GetAllRoles()
|
||||
for _, allRole := range allRoles {
|
||||
role := allRole
|
||||
role["is_default"] = "0"
|
||||
roles = append(roles, role)
|
||||
}
|
||||
this.Data["action"] = "add"
|
||||
this.Data["roles"] = roles
|
||||
this.viewLayout("user/form", "form")
|
||||
}
|
||||
|
||||
}
|
||||
func (this *UserController) Edit() {
|
||||
userModel := models.User{}
|
||||
roleModel := models.Role{}
|
||||
userRoleModel := models.UserRole{}
|
||||
|
||||
userId := this.GetString("user_id")
|
||||
if this.Ctx.Input.IsPost() {
|
||||
_, data := this.getUserFromPost(true)
|
||||
username := this.GetString("username")
|
||||
roleIds := this.GetStrings("role_ids", []string{})
|
||||
if len(roleIds) == 0 {
|
||||
this.jsonError("没有选择角色")
|
||||
}
|
||||
HasSameUsername, err := userModel.HasSameUsername(userId, username)
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
}
|
||||
if HasSameUsername {
|
||||
this.jsonError("用户名已经存在")
|
||||
}
|
||||
_, err = userModel.Update(userId, data)
|
||||
if err != nil {
|
||||
this.jsonError("修改用户失败:" + err.Error())
|
||||
}
|
||||
|
||||
//添加用户与角色对应关系
|
||||
_, err = userRoleModel.Insert(userId, roleIds)
|
||||
if err != nil {
|
||||
this.jsonError("修改用户角色失败:" + err.Error())
|
||||
}
|
||||
|
||||
this.jsonSuccess("")
|
||||
} else {
|
||||
roles := []map[string]string{}
|
||||
user, err := userModel.GetUserByUserId(userId)
|
||||
allRoles, _ := roleModel.GetAllRoles()
|
||||
userRoles, _ := userRoleModel.GetUserRolesByUserId(userId)
|
||||
for _, allRole := range allRoles {
|
||||
role := allRole
|
||||
if len(userRoles) == 0 {
|
||||
role["is_default"] = "0"
|
||||
} else {
|
||||
for _, userRoles := range userRoles {
|
||||
if allRole["role_id"] == userRoles["role_id"] {
|
||||
role["is_default"] = "1"
|
||||
break
|
||||
}
|
||||
role["is_default"] = "0"
|
||||
}
|
||||
}
|
||||
roles = append(roles, role)
|
||||
}
|
||||
if err != nil {
|
||||
this.jsonError(err, "")
|
||||
}
|
||||
if len(user) == 0 {
|
||||
this.jsonError("用户不存在")
|
||||
}
|
||||
this.Data["user"] = user
|
||||
this.Data["roles"] = roles
|
||||
this.Data["action"] = "edit"
|
||||
this.viewLayout("user/form", "form")
|
||||
}
|
||||
|
||||
}
|
||||
func (this *UserController) getUserFromPost(isUpdate bool) (userId string, user map[string]interface{}) {
|
||||
userModel := models.User{}
|
||||
user = map[string]interface{}{
|
||||
"username": this.GetString("username"),
|
||||
"given_name": this.GetString("given_name"),
|
||||
"email": this.GetString("email"),
|
||||
"mobile": this.GetString("mobile"),
|
||||
}
|
||||
errs := validation.Errors{
|
||||
"手机号": validation.Validate(user["mobile"],
|
||||
validation.Match(regexp.MustCompile("^1[3|4|5|7|8][0-9]{9}$")).Error("格式错误")),
|
||||
"邮箱": validation.Validate(user["email"],
|
||||
validation.Required.Error("不能为空"),
|
||||
is.Email.Error("格式错误")),
|
||||
"姓名": validation.Validate(user["given_name"],
|
||||
validation.Required.Error("不能为空"),
|
||||
validation.Match(regexp.MustCompile("^.{1,15}$")).Error("长度必须是1-15字符")),
|
||||
|
||||
//"角色": validation.Validate(user["role_ids"]),
|
||||
// validation.Required.Error("没有选择角色"),
|
||||
}
|
||||
if !isUpdate {
|
||||
errs["用户名"] = validation.Validate(user["username"],
|
||||
validation.Required.Error("不能为空"),
|
||||
validation.Match(regexp.MustCompile("^[0-9_a-zA-Z]{1,15}$")).Error("只能包含数字字母和下划线,且1-15字符"))
|
||||
// errs["密码"] = validation.Validate(this.GetString("password"),
|
||||
// validation.Required.Error("不能为空"),
|
||||
// validation.Match(regexp.MustCompile("^([0-9]+[a-zA-Z]+[_]*){1,16}$")).Error("必须同时包含数字和字母,且1-15字符"))
|
||||
}
|
||||
err := errs.Filter()
|
||||
if err != nil {
|
||||
this.jsonError(err)
|
||||
}
|
||||
if isUpdate {
|
||||
// if this.GetString("password") != "" {
|
||||
// user["password"] = userModel.EncodePassword(this.GetString("password"))
|
||||
// }
|
||||
user["update_time"] = time.Now().Unix()
|
||||
delete(user, "username")
|
||||
} else {
|
||||
user["is_forbidden"] = 0
|
||||
user["password"] = userModel.EncodePassword(this.GetString("password"))
|
||||
user["create_time"] = time.Now().Unix()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (this *UserController) List() {
|
||||
|
||||
keyword := strings.Trim(this.GetString("keyword", ""), " ")
|
||||
page, err := this.GetInt("page", 1)
|
||||
if err != nil {
|
||||
page = 1
|
||||
}
|
||||
//每页的条数
|
||||
pageSize := 10
|
||||
limit := (page - 1) * pageSize
|
||||
|
||||
userModel := models.User{}
|
||||
var users = []map[string]string{}
|
||||
var userCount = 0
|
||||
|
||||
if keyword == "" {
|
||||
userCount, err = userModel.CountUsers()
|
||||
users, err = userModel.GetUsersByLimit(limit, pageSize)
|
||||
} else {
|
||||
userCount, err = userModel.CountUsersByKeyword(keyword)
|
||||
users, err = userModel.GetUsersByKeywordAndLimit(keyword, limit, pageSize)
|
||||
}
|
||||
if err != nil {
|
||||
this.viewError(err.Error())
|
||||
}
|
||||
|
||||
roleModel := models.Role{}
|
||||
userRoles := map[string]string{}
|
||||
|
||||
//用户角色
|
||||
for _, user := range users {
|
||||
userId := user["user_id"]
|
||||
var names = ""
|
||||
roles, err := roleModel.GetRolesByUserId(userId)
|
||||
if err != nil {
|
||||
this.viewError(err.Error())
|
||||
}
|
||||
for _, role := range roles {
|
||||
names += "," + role["name"]
|
||||
}
|
||||
userRoles[user["user_id"]] = strings.Replace(names, ",", "", 1)
|
||||
}
|
||||
|
||||
this.Data["users"] = users
|
||||
this.Data["userRoles"] = userRoles
|
||||
this.Data["keyword"] = keyword
|
||||
this.Data["page"] = utils.NewMisc().Page(userCount, page, pageSize, "/user/list?page={page}")
|
||||
this.viewLayoutTitle("用户列表", "user/list", "form")
|
||||
}
|
||||
|
||||
//个人资料
|
||||
func (this *UserController) Profile() {
|
||||
|
||||
userModel := models.User{}
|
||||
if this.Ctx.Input.IsPost() {
|
||||
_, data := this.getUserFromPost(true)
|
||||
fmt.Println(data)
|
||||
userId := this.GetString("user_id")
|
||||
_, err := userModel.Update(userId, data)
|
||||
if err != nil {
|
||||
this.jsonError("修改个人资料失败:" + err.Error())
|
||||
}
|
||||
this.jsonSuccess("")
|
||||
|
||||
} else {
|
||||
user := this.GetSession("author").(map[string]string)
|
||||
this.Data["user"] = user
|
||||
this.viewLayout("user/profile", "form")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user