Merge pull request #195 from DigitalUnion/master

pull/219/head
Minho 2018-01-10 15:03:06 +08:00 committed by GitHub
commit 9440aff51f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 486 additions and 265 deletions

View File

@ -1,40 +1,52 @@
package controllers package controllers
import ( import (
"time"
"strings"
"regexp" "regexp"
"strconv"
"strings"
"time"
"net/smtp" "net/smtp"
"github.com/lifei6671/mindoc/conf"
"github.com/lifei6671/mindoc/models"
"github.com/lifei6671/mindoc/utils"
"github.com/astaxie/beego" "github.com/astaxie/beego"
"github.com/astaxie/beego/logs" "github.com/astaxie/beego/logs"
"github.com/lifei6671/gocaptcha" "github.com/lifei6671/gocaptcha"
"strconv" "github.com/lifei6671/mindoc/conf"
"github.com/lifei6671/mindoc/models"
"github.com/lifei6671/mindoc/utils"
) )
// AccountController 用户登录与注册. // AccountController 用户登录与注册
type AccountController struct { type AccountController struct {
BaseController BaseController
} }
// Login 用户登录. // Login 用户登录
func (c *AccountController) Login() { func (c *AccountController) Login() {
c.Prepare() c.Prepare()
c.TplName = "account/login.tpl" c.TplName = "account/login.tpl"
var remember struct { MemberId int ; Account string; Time time.Time} var remember struct {
MemberId int
Account string
Time time.Time
}
//如果Cookie中存在登录信息 // 显式指定的 URL 参数优先;为了统一处理,将之更新到 Session 中
if cookie,ok := c.GetSecureCookie(conf.GetAppKey(),"login");ok{ turl := c.GetString("turl", "")
if turl != "" {
c.SetSession("turl", turl)
}
if err := utils.Decode(cookie,&remember); err == nil { beego.Info("AccountController.Login(): turl is: " + turl)
if member,err := models.NewMember().Find(remember.MemberId); err == nil {
// 如果 Cookie 中存在登录信息
if cookie, ok := c.GetSecureCookie(conf.GetAppKey(), "login"); ok {
if err := utils.Decode(cookie, &remember); err == nil {
if member, err := models.NewMember().Find(remember.MemberId); err == nil {
c.SetMember(*member) c.SetMember(*member)
c.Redirect(beego.URLFor("HomeController.Index"), 302) c.LoggedIn(false)
c.StopRun() c.StopRun()
} }
} }
@ -46,48 +58,72 @@ func (c *AccountController) Login() {
captcha := c.GetString("code") captcha := c.GetString("code")
is_remember := c.GetString("is_remember") is_remember := c.GetString("is_remember")
//如果开启了验证码 // 如果开启了验证码
if v,ok := c.Option["ENABLED_CAPTCHA"]; ok && strings.EqualFold(v,"true") { if v, ok := c.Option["ENABLED_CAPTCHA"]; ok && strings.EqualFold(v, "true") {
v,ok := c.GetSession(conf.CaptchaSessionName).(string); v, ok := c.GetSession(conf.CaptchaSessionName).(string)
if !ok || !strings.EqualFold(v,captcha){ if !ok || !strings.EqualFold(v, captcha) {
c.JsonResult(6001,"验证码不正确") c.JsonResult(6001, "验证码不正确")
} }
} }
member,err := models.NewMember().Login(account,password)
//如果没有数据 member, err := models.NewMember().Login(account, password)
if err == nil { if err == nil {
member.LastLoginTime = time.Now() member.LastLoginTime = time.Now()
member.Update() member.Update()
c.SetMember(*member) c.SetMember(*member)
if strings.EqualFold(is_remember,"yes") { if strings.EqualFold(is_remember, "yes") {
remember.MemberId = member.MemberId remember.MemberId = member.MemberId
remember.Account = member.Account remember.Account = member.Account
remember.Time = time.Now() remember.Time = time.Now()
v ,err := utils.Encode(remember) v, err := utils.Encode(remember)
if err == nil { if err == nil {
c.SetSecureCookie(conf.GetAppKey(),"login",v) c.SetSecureCookie(conf.GetAppKey(), "login", v)
} }
} }
c.JsonResult(0,"ok") data := c.LoggedIn(true)
}else{ c.JsonResult(0, "ok", data)
logs.Error("用户登录 =>",err) } else {
c.JsonResult(500,"账号或密码错误",nil) logs.Error("用户登录 =>", err)
c.JsonResult(500, "账号或密码错误", nil)
} }
return
} }
} }
//用户注册. // 登录成功后的操作,如重定向到原始请求页面
func (c *AccountController) Register() { func (c *AccountController) LoggedIn(isPost bool) interface{} {
turl := ""
value := c.GetSession("turl")
if value != nil {
turl = value.(string)
}
c.DelSession("turl")
beego.Info("AccountController.LoggedIn(): turl is: " + turl)
if !isPost {
// 检查是否存在 turl 参数,如果有则重定向至 turl 处,否则进入 Home 页面
if turl == "" {
turl = beego.URLFor("HomeController.Index")
}
c.Redirect(turl, 302)
return nil
} else {
var data struct {
TURL string `json:"turl"`
}
data.TURL = turl
return data
}
}
// 用户注册
func (c *AccountController) Register() {
c.TplName = "account/register.tpl" c.TplName = "account/register.tpl"
//如果没有开启用户注册 // 如果没有开启用户注册
if v,ok := c.Option["ENABLED_REGISTER"]; ok && !strings.EqualFold(v,"true") { if v, ok := c.Option["ENABLED_REGISTER"]; ok && !strings.EqualFold(v, "true") {
c.Abort("404") c.Abort("404")
} }
@ -98,30 +134,30 @@ func (c *AccountController) Register() {
email := c.GetString("email") email := c.GetString("email")
captcha := c.GetString("code") captcha := c.GetString("code")
if ok,err := regexp.MatchString(conf.RegexpAccount,account); account == "" || !ok || err != nil { if ok, err := regexp.MatchString(conf.RegexpAccount, account); account == "" || !ok || err != nil {
c.JsonResult(6001,"账号只能由英文字母数字组成且在3-50个字符") c.JsonResult(6001, "账号只能由英文字母数字组成且在3-50个字符")
} }
if l := strings.Count(password1,"") ; password1 == "" || l > 50 || l < 6{ if l := strings.Count(password1, ""); password1 == "" || l > 50 || l < 6 {
c.JsonResult(6002,"密码必须在6-50个字符之间") c.JsonResult(6002, "密码必须在6-50个字符之间")
} }
if password1 != password2 { if password1 != password2 {
c.JsonResult(6003,"确认密码不正确") c.JsonResult(6003, "确认密码不正确")
} }
if ok,err := regexp.MatchString(conf.RegexpEmail,email); !ok || err != nil || email == "" { if ok, err := regexp.MatchString(conf.RegexpEmail, email); !ok || err != nil || email == "" {
c.JsonResult(6004,"邮箱格式不正确") c.JsonResult(6004, "邮箱格式不正确")
} }
//如果开启了验证码 // 如果开启了验证码
if v,ok := c.Option["ENABLED_CAPTCHA"]; ok && strings.EqualFold(v,"true") { if v, ok := c.Option["ENABLED_CAPTCHA"]; ok && strings.EqualFold(v, "true") {
v,ok := c.GetSession(conf.CaptchaSessionName).(string); v, ok := c.GetSession(conf.CaptchaSessionName).(string)
if !ok || !strings.EqualFold(v,captcha){ if !ok || !strings.EqualFold(v, captcha) {
c.JsonResult(6001,"验证码不正确") c.JsonResult(6001, "验证码不正确")
} }
} }
member := models.NewMember() member := models.NewMember()
if _,err := member.FindByAccount(account); err == nil && member.MemberId > 0 { if _, err := member.FindByAccount(account); err == nil && member.MemberId > 0 {
c.JsonResult(6005,"账号已存在") c.JsonResult(6005, "账号已存在")
} }
member.Account = account member.Account = account
@ -133,15 +169,15 @@ func (c *AccountController) Register() {
member.Status = 0 member.Status = 0
if err := member.Add(); err != nil { if err := member.Add(); err != nil {
beego.Error(err) beego.Error(err)
c.JsonResult(6006,"注册失败,请联系系统管理员处理") c.JsonResult(6006, "注册失败,请联系系统管理员处理")
} }
c.JsonResult(0,"ok",member) c.JsonResult(0, "ok", member)
} }
} }
//找回密码. // 找回密码
func (c *AccountController) FindPassword() { func (c *AccountController) FindPassword() {
c.TplName = "account/find_password_setp1.tpl" c.TplName = "account/find_password_setp1.tpl"
mail_conf := conf.GetMailConfig() mail_conf := conf.GetMailConfig()
@ -151,63 +187,63 @@ func (c *AccountController) FindPassword() {
captcha := c.GetString("code") captcha := c.GetString("code")
if email == "" { if email == "" {
c.JsonResult(6005,"邮箱地址不能为空") c.JsonResult(6005, "邮箱地址不能为空")
} }
if !mail_conf.EnableMail { if !mail_conf.EnableMail {
c.JsonResult(6004,"未启用邮件服务") c.JsonResult(6004, "未启用邮件服务")
} }
//如果开启了验证码 // 如果开启了验证码
if v,ok := c.Option["ENABLED_CAPTCHA"]; ok && strings.EqualFold(v,"true") { if v, ok := c.Option["ENABLED_CAPTCHA"]; ok && strings.EqualFold(v, "true") {
v,ok := c.GetSession(conf.CaptchaSessionName).(string); v, ok := c.GetSession(conf.CaptchaSessionName).(string)
if !ok || !strings.EqualFold(v,captcha){ if !ok || !strings.EqualFold(v, captcha) {
c.JsonResult(6001,"验证码不正确") c.JsonResult(6001, "验证码不正确")
} }
} }
member ,err := models.NewMember().FindByFieldFirst("email",email) member, err := models.NewMember().FindByFieldFirst("email", email)
if err != nil { if err != nil {
c.JsonResult(6006,"邮箱不存在") c.JsonResult(6006, "邮箱不存在")
} }
if member.Status != 0 { if member.Status != 0 {
c.JsonResult(6007,"账号已被禁用") c.JsonResult(6007, "账号已被禁用")
} }
if member.AuthMethod == conf.AuthMethodLDAP { if member.AuthMethod == conf.AuthMethodLDAP {
c.JsonResult(6011,"当前用户不支持找回密码") c.JsonResult(6011, "当前用户不支持找回密码")
} }
count,err := models.NewMemberToken().FindSendCount(email,time.Now().Add(-1*time.Hour),time.Now()) count, err := models.NewMemberToken().FindSendCount(email, time.Now().Add(-1*time.Hour), time.Now())
if err != nil { if err != nil {
beego.Error(err) beego.Error(err)
c.JsonResult(6008,"发送邮件失败") c.JsonResult(6008, "发送邮件失败")
} }
if count > mail_conf.MailNumber { if count > mail_conf.MailNumber {
c.JsonResult(6008,"发送次数太多,请稍候再试") c.JsonResult(6008, "发送次数太多,请稍候再试")
} }
member_token := models.NewMemberToken() member_token := models.NewMemberToken()
member_token.Token = string(utils.Krand(32,utils.KC_RAND_KIND_ALL)) member_token.Token = string(utils.Krand(32, utils.KC_RAND_KIND_ALL))
member_token.Email = email member_token.Email = email
member_token.MemberId = member.MemberId member_token.MemberId = member.MemberId
member_token.IsValid = false member_token.IsValid = false
if _,err := member_token.InsertOrUpdate(); err != nil { if _, err := member_token.InsertOrUpdate(); err != nil {
c.JsonResult(6009,"邮件发送失败") c.JsonResult(6009, "邮件发送失败")
} }
data := map[string]interface{}{ data := map[string]interface{}{
"SITE_NAME" : c.Option["SITE_NAME"], "SITE_NAME": c.Option["SITE_NAME"],
"url" : c.BaseUrl() + beego.URLFor("AccountController.FindPassword", "token",member_token.Token,"mail",email), "url": c.BaseUrl() + beego.URLFor("AccountController.FindPassword", "token", member_token.Token, "mail", email),
} }
body,err := c.ExecuteViewPathTemplate("account/mail_template.tpl",data) body, err := c.ExecuteViewPathTemplate("account/mail_template.tpl", data)
if err != nil { if err != nil {
beego.Error(err) beego.Error(err)
c.JsonResult(6003,"邮件发送失败") c.JsonResult(6003, "邮件发送失败")
} }
go func(mail_conf *conf.SmtpConf,email string,body string) { go func(mail_conf *conf.SmtpConf, email string, body string) {
auth := smtp.PlainAuth( auth := smtp.PlainAuth(
"", "",
mail_conf.SmtpUserName, mail_conf.SmtpUserName,
@ -215,30 +251,29 @@ func (c *AccountController) FindPassword() {
mail_conf.SmtpHost, mail_conf.SmtpHost,
) )
mime := "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n"; mime := "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n"
subject := "Subject: 找回密码!\n" subject := "Subject: 找回密码!\n"
err = smtp.SendMail( err = smtp.SendMail(
mail_conf.SmtpHost + ":" + strconv.Itoa(mail_conf.SmtpPort), mail_conf.SmtpHost+":"+strconv.Itoa(mail_conf.SmtpPort),
auth, auth,
mail_conf.FormUserName, mail_conf.FormUserName,
[]string{ email }, []string{email},
[]byte(subject + mime +"\n" +body), []byte(subject+mime+"\n"+body),
) )
if err != nil { if err != nil {
beego.Error("邮件发送失败 => ",email,err) beego.Error("邮件发送失败 => ", email, err)
} }
}(mail_conf,email,body) }(mail_conf, email, body)
c.JsonResult(0, "ok", c.BaseUrl()+beego.URLFor("AccountController.Login"))
c.JsonResult(0,"ok", c.BaseUrl() + beego.URLFor("AccountController.Login"))
} }
token := c.GetString("token") token := c.GetString("token")
mail := c.GetString("mail") mail := c.GetString("mail")
if token != "" && mail != "" { if token != "" && mail != "" {
member_token,err := models.NewMemberToken().FindByFieldFirst("token",token) member_token, err := models.NewMemberToken().FindByFieldFirst("token", token)
if err != nil { if err != nil {
beego.Error(err) beego.Error(err)
@ -248,7 +283,7 @@ func (c *AccountController) FindPassword() {
} }
sub_time := member_token.SendTime.Sub(time.Now()) sub_time := member_token.SendTime.Sub(time.Now())
if !strings.EqualFold(member_token.Email,mail) || sub_time.Minutes() > float64(mail_conf.MailExpired) || !member_token.ValidTime.IsZero() { if !strings.EqualFold(member_token.Email, mail) || sub_time.Minutes() > float64(mail_conf.MailExpired) || !member_token.ValidTime.IsZero() {
c.Data["ErrorMessage"] = "验证码已过期,请重新操作。" c.Data["ErrorMessage"] = "验证码已过期,请重新操作。"
c.TplName = "errors/error.tpl" c.TplName = "errors/error.tpl"
return return
@ -260,7 +295,7 @@ func (c *AccountController) FindPassword() {
} }
} }
//校验邮件并修改密码. // 校验邮件并修改密码
func (c *AccountController) ValidEmail() { func (c *AccountController) ValidEmail() {
c.Prepare() c.Prepare()
password1 := c.GetString("password1") password1 := c.GetString("password1")
@ -270,48 +305,48 @@ func (c *AccountController) ValidEmail() {
mail := c.GetString("mail") mail := c.GetString("mail")
if password1 == "" { if password1 == "" {
c.JsonResult(6001,"密码不能为空") c.JsonResult(6001, "密码不能为空")
} }
if l := strings.Count(password1,""); l <6 || l > 50{ if l := strings.Count(password1, ""); l < 6 || l > 50 {
c.JsonResult(6001,"密码不能为空且必须在6-50个字符之间") c.JsonResult(6001, "密码不能为空且必须在6-50个字符之间")
} }
if password2 == ""{ if password2 == "" {
c.JsonResult(6002,"确认密码不能为空") c.JsonResult(6002, "确认密码不能为空")
} }
if password1 != password2 { if password1 != password2 {
c.JsonResult(6003,"确认密码输入不正确") c.JsonResult(6003, "确认密码输入不正确")
} }
if captcha == "" { if captcha == "" {
c.JsonResult(6004,"验证码不能为空") c.JsonResult(6004, "验证码不能为空")
} }
v,ok := c.GetSession(conf.CaptchaSessionName).(string); v, ok := c.GetSession(conf.CaptchaSessionName).(string)
if !ok || !strings.EqualFold(v,captcha){ if !ok || !strings.EqualFold(v, captcha) {
c.JsonResult(6001,"验证码不正确") c.JsonResult(6001, "验证码不正确")
} }
mail_conf := conf.GetMailConfig() mail_conf := conf.GetMailConfig()
member_token,err := models.NewMemberToken().FindByFieldFirst("token",token) member_token, err := models.NewMemberToken().FindByFieldFirst("token", token)
if err != nil { if err != nil {
beego.Error(err) beego.Error(err)
c.JsonResult(6007,"邮件已失效") c.JsonResult(6007, "邮件已失效")
} }
sub_time := member_token.SendTime.Sub(time.Now()) sub_time := member_token.SendTime.Sub(time.Now())
if !strings.EqualFold(member_token.Email,mail) || sub_time.Minutes() > float64(mail_conf.MailExpired) || !member_token.ValidTime.IsZero() { if !strings.EqualFold(member_token.Email, mail) || sub_time.Minutes() > float64(mail_conf.MailExpired) || !member_token.ValidTime.IsZero() {
c.JsonResult(6008,"验证码已过期,请重新操作。") c.JsonResult(6008, "验证码已过期,请重新操作。")
} }
member ,err := models.NewMember().Find(member_token.MemberId) member, err := models.NewMember().Find(member_token.MemberId)
if err != nil{ if err != nil {
beego.Error(err) beego.Error(err)
c.JsonResult(6005,"用户不存在") c.JsonResult(6005, "用户不存在")
} }
hash ,err := utils.PasswordHash(password1); hash, err := utils.PasswordHash(password1)
if err != nil { if err != nil {
beego.Error(err) beego.Error(err)
c.JsonResult(6006,"保存密码失败") c.JsonResult(6006, "保存密码失败")
} }
member.Password = hash member.Password = hash
@ -321,25 +356,24 @@ func (c *AccountController) ValidEmail() {
member_token.IsValid = true member_token.IsValid = true
member_token.InsertOrUpdate() member_token.InsertOrUpdate()
if err != nil { if err != nil {
beego.Error(err) beego.Error(err)
c.JsonResult(6006,"保存密码失败") c.JsonResult(6006, "保存密码失败")
} }
c.JsonResult(0,"ok",c.BaseUrl() + beego.URLFor("AccountController.Login")) c.JsonResult(0, "ok", c.BaseUrl()+beego.URLFor("AccountController.Login"))
} }
// Logout 退出登录
func (c *AccountController) Logout() {
c.SetMember(models.Member{})
// Logout 退出登录. c.SetSecureCookie(conf.GetAppKey(), "login", "", -3600)
func (c *AccountController) Logout(){
c.SetMember(models.Member{});
c.SetSecureCookie(conf.GetAppKey(),"login","",-3600) c.Redirect(beego.URLFor("AccountController.Login"), 302)
c.Redirect(beego.URLFor("AccountController.Login"),302)
} }
//验证码. // 验证码
func (c *AccountController) Captcha() { func (c *AccountController) Captcha() {
c.Prepare() c.Prepare()
captchaImage, err := gocaptcha.NewCaptchaImage(140, 40, gocaptcha.RandLightColor()) captchaImage, err := gocaptcha.NewCaptchaImage(140, 40, gocaptcha.RandLightColor())
@ -351,17 +385,16 @@ func (c *AccountController) Captcha() {
captchaImage.DrawNoise(gocaptcha.CaptchaComplexLower) captchaImage.DrawNoise(gocaptcha.CaptchaComplexLower)
//captchaImage.DrawTextNoise(gocaptcha.CaptchaComplexHigh) // captchaImage.DrawTextNoise(gocaptcha.CaptchaComplexHigh)
txt := gocaptcha.RandText(4) txt := gocaptcha.RandText(4)
c.SetSession(conf.CaptchaSessionName,txt) c.SetSession(conf.CaptchaSessionName, txt)
captchaImage.DrawText(txt) captchaImage.DrawText(txt)
//captchaImage.Drawline(3); // captchaImage.Drawline(3);
captchaImage.DrawBorder(gocaptcha.ColorToRGB(0x17A7A7A)) captchaImage.DrawBorder(gocaptcha.ColorToRGB(0x17A7A7A))
//captchaImage.DrawHollowLine() // captchaImage.DrawHollowLine()
captchaImage.SaveImage(c.Ctx.ResponseWriter, gocaptcha.ImageFormatJpeg) captchaImage.SaveImage(c.Ctx.ResponseWriter, gocaptcha.ImageFormatJpeg)
c.StopRun() c.StopRun()
} }

View File

@ -99,6 +99,11 @@ func isUserLoggedIn(c *DocumentController) bool {
} }
func promptUserToLogIn(c *DocumentController) { func promptUserToLogIn(c *DocumentController) {
beego.Info("Access " + c.Ctx.Request.URL.RequestURI() + " not permitted.")
beego.Info(" Access will be redirected to login page(SessionId: " + c.CruSession.SessionID() + ").")
c.SetSession("turl", c.Ctx.Request.URL.RequestURI())
if c.IsAjax() { if c.IsAjax() {
c.JsonResult(6000, "需要[重]登录。") c.JsonResult(6000, "需要[重]登录。")
} else { } else {

View File

@ -1,31 +1,32 @@
$(function () { $(function () {
window.addDocumentModalFormHtml = $(this).find("form").html(); window.addDocumentModalFormHtml = $(this).find("form").html();
window.editor = editormd("docEditor", { window.editor = editormd("docEditor", {
width : "100%", width: "100%",
height : "100%", height: "100%",
path : "/static/editor.md/lib/", path: "/static/editor.md/lib/",
toolbar : true, toolbar: true,
placeholder: "本编辑器支持Markdown编辑左边编写右边预览", placeholder: "本编辑器支持 Markdown 编辑,左边编写,右边预览",
imageUpload: true, imageUpload: true,
imageFormats: ["jpg", "jpeg", "gif", "png", "JPG", "JPEG", "GIF", "PNG"], imageFormats: ["jpg", "jpeg", "gif", "png", "JPG", "JPEG", "GIF", "PNG"],
imageUploadURL: window.imageUploadURL , imageUploadURL: window.imageUploadURL,
toolbarModes : "full", toolbarModes: "full",
fileUpload: true, fileUpload: true,
fileUploadURL : window.fileUploadURL, fileUploadURL: window.fileUploadURL,
taskList : true, taskList: true,
flowChart : true, flowChart: true,
htmlDecode : "style,script,iframe,title,onmouseover,onmouseout,style", htmlDecode: "style,script,iframe,title,onmouseover,onmouseout,style",
lineNumbers : false, lineNumbers: false,
tocStartLevel : 1, tocStartLevel: 1,
tocm : true, tocm: true,
saveHTMLToTextarea : true, saveHTMLToTextarea: true,
onload : function() {
onload: function() {
this.hideToolbar(); this.hideToolbar();
var keyMap = { var keyMap = {
"Ctrl-S": function(cm) { "Ctrl-S": function(cm) {
saveDocument(false); saveDocument(false);
}, },
"Cmd-S" : function(cm){ "Cmd-S": function(cm){
saveDocument(false); saveDocument(false);
}, },
"Ctrl-A": function(cm) { "Ctrl-A": function(cm) {
@ -35,7 +36,7 @@ $(function () {
this.addKeyMap(keyMap); this.addKeyMap(keyMap);
var $select_node_id = window.treeCatalog.get_selected(); var $select_node_id = window.treeCatalog.get_selected();
if($select_node_id) { if ($select_node_id) {
var $select_node = window.treeCatalog.get_node($select_node_id[0]) var $select_node = window.treeCatalog.get_node($select_node_id[0])
if ($select_node) { if ($select_node) {
$select_node.node = { $select_node.node = {
@ -45,20 +46,21 @@ $(function () {
loadDocument($select_node); loadDocument($select_node);
} }
} }
uploadImage("docEditor",function ($state, $res) {
if($state === "before"){ uploadImage("docEditor", function ($state, $res) {
if ($state === "before") {
return layer.load(1, { return layer.load(1, {
shade: [0.1,'#fff'] //0.1透明度的白色背景 shade: [0.1, '#fff'] // 0.1 透明度的白色背景
}); });
}else if($state === "success"){ } else if ($state === "success") {
if($res.errcode === 0) { if ($res.errcode === 0) {
var value = '![](' + $res.url + ')'; var value = '![](' + $res.url + ')';
window.editor.insertValue(value); window.editor.insertValue(value);
} }
} }
}); });
}, },
onchange : function () { onchange: function () {
resetEditorChanged(true); resetEditorChanged(true);
} }
}); });
@ -66,62 +68,50 @@ $(function () {
/** /**
* *
*/ */
$("#editormd-tools").on("click","a[class!='disabled']",function () { $("#editormd-tools").on("click", "a[class!='disabled']", function () {
var name = $(this).find("i").attr("name"); var name = $(this).find("i").attr("name");
if(name === "attachment"){ if (name === "attachment") {
$("#uploadAttachModal").modal("show"); $("#uploadAttachModal").modal("show");
}else if(name === "history"){ } else if (name === "history") {
window.documentHistory(); window.documentHistory();
}else if(name === "save"){ } else if (name === "save") {
saveDocument(false); saveDocument(false);
}else if(name === "template"){ } else if (name === "template") {
$("#documentTemplateModal").modal("show"); $("#documentTemplateModal").modal("show");
}else if(name === "sidebar"){ } else if (name === "sidebar") {
$("#manualCategory").toggle(0,"swing",function () { $("#manualCategory").toggle(0, "swing", function () {
var $then = $("#manualEditorContainer"); var $then = $("#manualEditorContainer");
var left = parseInt($then.css("left")); var left = parseInt($then.css("left"));
if(left > 0){ if (left > 0) {
window.editorContainerLeft = left; window.editorContainerLeft = left;
$then.css("left","0"); $then.css("left", "0");
}else{ } else {
$then.css("left",window.editorContainerLeft + "px"); $then.css("left", window.editorContainerLeft + "px");
} }
window.editor.resize(); window.editor.resize();
}); });
}else if(name === "release"){ } else if (name === "release") {
if(Object.prototype.toString.call(window.documentCategory) === '[object Array]' && window.documentCategory.length > 0){ if (Object.prototype.toString.call(window.documentCategory) === '[object Array]' && window.documentCategory.length > 0) {
if($("#markdown-save").hasClass('change')) { if ($("#markdown-save").hasClass('change')) {
var comfirm_result = confirm("编辑内容未保存,需要保存吗?") var comfirm_result = confirm("编辑内容未保存,需要保存吗?")
if(comfirm_result) { if (comfirm_result) {
saveDocument(); saveDocument(false, releaseBook);
return;
} }
} }
$.ajax({
url : window.releaseURL, releaseBook();
data :{"identify" : window.book.identify }, } else {
type : "post",
dataType : "json",
success : function (res) {
if(res.errcode === 0){
layer.msg("发布任务已推送到任务队列,稍后将在后台执行。");
}else{
layer.msg(res.message);
}
}
});
}else{
layer.msg("没有需要发布的文档") layer.msg("没有需要发布的文档")
} }
}else if(name === "tasks") { } else if (name === "tasks") {
//插入GFM任务列表 // 插入 GFM 任务列表
var cm = window.editor.cm; var cm = window.editor.cm;
var selection = cm.getSelection(); var selection = cm.getSelection();
if (selection === "") { if (selection === "") {
cm.replaceSelection("- [x] " + selection); cm.replaceSelection("- [x] " + selection);
} } else {
else {
var selectionText = selection.split("\n"); var selectionText = selection.split("\n");
for (var i = 0, len = selectionText.length; i < len; i++) { for (var i = 0, len = selectionText.length; i < len; i++) {
@ -129,7 +119,7 @@ $(function () {
} }
cm.replaceSelection(selectionText.join("\n")); cm.replaceSelection(selectionText.join("\n"));
} }
}else { } else {
var action = window.editor.toolbarHandlers[name]; var action = window.editor.toolbarHandlers[name];
if (action !== "undefined") { if (action !== "undefined") {
@ -145,23 +135,23 @@ $(function () {
*/ */
window.loadDocument = function($node) { window.loadDocument = function($node) {
var index = layer.load(1, { var index = layer.load(1, {
shade: [0.1,'#fff'] //0.1透明度的白色背景 shade: [0.1, '#fff'] // 0.1 透明度的白色背景
}); });
$.get(window.editURL + $node.node.id ).done(function (res) { $.get(window.editURL + $node.node.id ).done(function (res) {
layer.close(index); layer.close(index);
resetEditor(); resetEditor();
if(res.errcode === 0){ if (res.errcode === 0) {
window.isLoad = true; window.isLoad = true;
window.editor.clear(); window.editor.clear();
window.editor.insertValue(res.data.markdown); window.editor.insertValue(res.data.markdown);
window.editor.setCursor({line:0, ch:0}); window.editor.setCursor({ line : 0, ch : 0 });
var node = { "id" : res.data.doc_id,'parent' : res.data.parent_id === 0 ? '#' : res.data.parent_id ,"text" : res.data.doc_name,"identify" : res.data.identify,"version" : res.data.version}; var node = { "id": res.data.doc_id, 'parent': res.data.parent_id === 0 ? '#' : res.data.parent_id, "text": res.data.doc_name, "identify": res.data.identify, "version": res.data.version };
pushDocumentCategory(node); pushDocumentCategory(node);
window.selectNode = node; window.selectNode = node;
pushVueLists(res.data.attach); pushVueLists(res.data.attach);
}else{ } else {
layer.msg("文档加载失败"); layer.msg("文档加载失败");
} }
}).fail(function () { }).fail(function () {
@ -174,58 +164,75 @@ $(function () {
* *
* @param $is_cover * @param $is_cover
*/ */
function saveDocument($is_cover,callback) { function saveDocument($is_cover, callback) {
var index = null; var index = null;
var node = window.selectNode; var node = window.selectNode;
var content = window.editor.getMarkdown(); var content = window.editor.getMarkdown();
var html = window.editor.getPreviewedHTML(); var html = window.editor.getPreviewedHTML();
var version = ""; var version = "";
if(!node){ if (!node) {
layer.msg("获取当前文档信息失败"); layer.msg("获取当前文档信息失败");
return; return;
} }
var doc_id = parseInt(node.id); var doc_id = parseInt(node.id);
for(var i in window.documentCategory){ for (var i in window.documentCategory) {
var item = window.documentCategory[i]; var item = window.documentCategory[i];
if(item.id === doc_id){ if (item.id === doc_id) {
version = item.version; version = item.version;
break; break;
} }
} }
$.ajax({ $.ajax({
beforeSend : function () { beforeSend: function () {
index = layer.load(1, {shade: [0.1,'#fff'] }); index = layer.load(1, { shade: [0.1, '#fff'] });
}, },
url : window.editURL, url: window.editURL,
data : {"identify" : window.book.identify,"doc_id" : doc_id,"markdown" : content,"html" : html,"cover" : $is_cover ? "yes":"no","version": version}, data: { "identify": window.book.identify, "doc_id": doc_id, "markdown": content, "html": html, "cover": $is_cover ? "yes" : "no", "version": version },
type :"post", type: "post",
dataType :"json", dataType: "json",
success : function (res) { success: function (res) {
layer.close(index); layer.close(index);
if(res.errcode === 0){ if (res.errcode === 0) {
resetEditorChanged(false); resetEditorChanged(false);
for(var i in window.documentCategory){ for (var i in window.documentCategory) {
var item = window.documentCategory[i]; var item = window.documentCategory[i];
if(item.id === doc_id){ if (item.id === doc_id) {
window.documentCategory[i].version = res.data.version; window.documentCategory[i].version = res.data.version;
break; break;
} }
} }
if(typeof callback === "function"){ if (typeof callback === "function") {
callback(); callback();
} }
}else if(res.errcode === 6005){ } else if(res.errcode === 6005) {
var confirmIndex = layer.confirm('', { var confirmIndex = layer.confirm('', {
btn: ['',''] //按钮 btn: ['', ''] // 按钮
}, function(){ }, function() {
layer.close(confirmIndex); layer.close(confirmIndex);
saveDocument(true,callback); saveDocument(true, callback);
}); });
}else{ } else {
layer.msg(res.message);
}
}
});
}
function releaseBook() {
$.ajax({
url: window.releaseURL,
data: { "identify": window.book.identify },
type: "post",
dataType: "json",
success: function (res) {
if (res.errcode === 0) {
layer.msg("发布任务已推送到任务队列,稍后将在后台执行。");
} else {
layer.msg(res.message); layer.msg(res.message);
} }
} }
@ -233,7 +240,6 @@ $(function () {
} }
function resetEditor($node) { function resetEditor($node) {
} }
/** /**
@ -241,35 +247,34 @@ $(function () {
* @param $is_change * @param $is_change
*/ */
function resetEditorChanged($is_change) { function resetEditorChanged($is_change) {
if($is_change && !window.isLoad ){ if ($is_change && !window.isLoad) {
$("#markdown-save").removeClass('disabled').addClass('change'); $("#markdown-save").removeClass('disabled').addClass('change');
}else{ } else {
$("#markdown-save").removeClass('change').addClass('disabled'); $("#markdown-save").removeClass('change').addClass('disabled');
} }
window.isLoad = false; window.isLoad = false;
} }
/** /**
* *
*/ */
$("#addDocumentForm").ajaxForm({ $("#addDocumentForm").ajaxForm({
beforeSubmit : function () { beforeSubmit: function () {
var doc_name = $.trim($("#documentName").val()); var doc_name = $.trim($("#documentName").val());
if (doc_name === ""){ if (doc_name === "") {
return showError("目录名称不能为空","#add-error-message") return showError("目录名称不能为空", "#add-error-message")
} }
$("#btnSaveDocument").button("loading"); $("#btnSaveDocument").button("loading");
return true; return true;
}, },
success : function (res) { success: function (res) {
if(res.errcode === 0){ if (res.errcode === 0) {
var data = { "id": res.data.doc_id, 'parent': res.data.parent_id === 0 ? '#' : res.data.parent_id , "text": res.data.doc_name, "identify": res.data.identify, "version": res.data.version };
var data = { "id" : res.data.doc_id,'parent' : res.data.parent_id === 0 ? '#' : res.data.parent_id ,"text" : res.data.doc_name,"identify" : res.data.identify,"version" : res.data.version};
var node = window.treeCatalog.get_node(data.id); var node = window.treeCatalog.get_node(data.id);
if(node){ if (node) {
window.treeCatalog.rename_node({"id":data.id},data.text); window.treeCatalog.rename_node({ "id": data.id }, data.text);
} else {
}else {
window.treeCatalog.create_node(data.parent, data); window.treeCatalog.create_node(data.parent, data);
window.treeCatalog.deselect_all(); window.treeCatalog.deselect_all();
window.treeCatalog.select_node(data); window.treeCatalog.select_node(data);
@ -277,8 +282,8 @@ $(function () {
pushDocumentCategory(data); pushDocumentCategory(data);
$("#markdown-save").removeClass('change').addClass('disabled'); $("#markdown-save").removeClass('change').addClass('disabled');
$("#addDocumentModal").modal('hide'); $("#addDocumentModal").modal('hide');
}else{ } else {
showError(res.message,"#add-error-message") showError(res.message, "#add-error-message");
} }
$("#btnSaveDocument").button("reset"); $("#btnSaveDocument").button("reset");
} }
@ -311,7 +316,6 @@ $(function () {
"label": "添加文档", "label": "添加文档",
"icon": "fa fa-plus", "icon": "fa fa-plus",
"action": function (data) { "action": function (data) {
var inst = $.jstree.reference(data.reference), var inst = $.jstree.reference(data.reference),
node = inst.get_node(data.reference); node = inst.get_node(data.reference);
@ -347,26 +351,26 @@ $(function () {
}).on('loaded.jstree', function () { }).on('loaded.jstree', function () {
window.treeCatalog = $(this).jstree(); window.treeCatalog = $(this).jstree();
}).on('select_node.jstree', function (node, selected, event) { }).on('select_node.jstree', function (node, selected, event) {
if($("#markdown-save").hasClass('change')) { if ($("#markdown-save").hasClass('change')) {
if(confirm("编辑内容未保存,需要保存吗?")){ if (confirm("编辑内容未保存,需要保存吗?")) {
saveDocument(false,function () { saveDocument(false, function () {
loadDocument(selected); loadDocument(selected);
}); });
return true; return true;
} }
} }
loadDocument(selected); loadDocument(selected);
}).on("move_node.jstree", jstree_save);
}).on("move_node.jstree",jstree_save); $("#documentTemplateModal").on("click", ".section>a[data-type]", function () {
$("#documentTemplateModal").on("click",".section>a[data-type]",function () {
var $this = $(this).attr("data-type"); var $this = $(this).attr("data-type");
var body = $("#template-" + $this).html(); var body = $("#template-" + $this).html();
if (body) { if (body) {
window.isLoad = true; window.isLoad = true;
window.editor.clear(); window.editor.clear();
window.editor.insertValue(body); window.editor.insertValue(body);
window.editor.setCursor({line: 0, ch: 0}); window.editor.setCursor({ line: 0, ch: 0 });
resetEditorChanged(true); resetEditorChanged(true);
} }
$("#documentTemplateModal").modal('hide'); $("#documentTemplateModal").modal('hide');

View File

@ -0,0 +1,176 @@
$(function () {
var splitBar = {
// 设置当前屏幕为 840px 时将分割条隐藏
maxWidth: 840,
// 父元素选择器
parentSelector: '.manual-body',
/**
*
*/
init: function () {
var self = this;
$(self.parentSelector)
.append(
$('\
<div id="manual-vsplitbar" unselectable="on"\
style="\
z-index:301;\
position: absolute;\
user-select: none;\
cursor: col-resize;\
left: 275px;\
height: 100%;\
display: block;\
width: 3px;\
border-right: 1px solid #8f949a;">\
<a href="javascript:void(0)" accesskey="" tabindex="0" title="vsplitbar"></a>\
</div>\
')
.hover(
function (event) {
event.target.style.background = '#8f949ad8';
},
function (event) {
event.target.style.background = '';
}
)
);
self.loadingHtml();
// 设置媒体查询
mediaMatcher.set();
},
/**
*
*/
loadingHtml: function () {
var self = this;
var htmlWidth = document.body.clientWidth;
if (htmlWidth <= self.maxWidth) $('#manual-vsplitbar').css('display', 'none');
},
/**
*
*/
reset: function () {
if (isFullScreen) {
// 关闭菜单时,初始化左右窗口
$('#manual-vsplitbar').css('display', 'none');
splitBar.inMaxWidthReset();
$('.manual-left').css('width', '0px');
} else {
// 打开菜单时,初始化左右窗口
$('#manual-vsplitbar').css('display', 'block');
splitBar.outMaxWidthReset();
}
},
/**
* 840px
*/
inMaxWidthReset: function () {
$('#manual-vsplitbar').css('display', 'none');
$('.m-manual.manual-reader .manual-right').css('left', '0');
$('.manual-left').css('width', '280px');
},
/**
* 840px
*/
outMaxWidthReset: function () {
$('.manual-right').css('left', '279px');
$('.manual-left').css('width', '279px');
$('#manual-vsplitbar').css('left', '275px').css('display', 'block');
}
}
/**
*
*
*/
var mediaMatcher = {
mql: window.matchMedia('(max-width:' + splitBar.maxWidth + 'px)'),
/**
*
*/
set: function () {
var self = this;
self.mql.addListener(self.mqCallback);
},
/**
*
*/
remove: function () {
var self = this;
self.mql.removeListener(self.mqCallback);
},
/**
*
*/
mqCallback: function (event) {
if (event.target.matches) { // 宽度小于等于 840 像素
$(".m-manual").removeClass('manual-fullscreen-active');
splitBar.inMaxWidthReset();
} else { // 宽度大于 840 像素
splitBar.outMaxWidthReset();
}
}
}
// 初始化分割条
splitBar.init();
/**
*
* 140px
*/
$('#manual-vsplitbar').on('mousedown', function (e) {
var bodyEle = $('.manual-body')[0];
var leftPane = $('.manual-left')[0];
var splitBar = $('#manual-vsplitbar')[0];
var rightPane = $('.manual-right')[0];
var disX = (e || event).clientX;
splitBar.left = splitBar.offsetLeft;
var docMouseMove = document.onmousemove;
var docMouseUp = document.onmouseup;
document.onmousemove = function (e) {
var curPos = splitBar.left + ((e || event).clientX - disX);
var maxPos = bodyEle.clientWidth - splitBar.offsetWidth;
curPos > maxPos && (curPos = maxPos);
curPos < 140 && (curPos = 140);
leftPane.style.width = curPos + "px";
splitBar.style.left = curPos - 3 + "px";
rightPane.style.left = curPos + 3 + "px";
return false;
}
document.onmouseup = function () {
document.onmousemove = docMouseMove;
document.onmouseup = docMouseUp;
splitBar.releaseCapture && splitBar.releaseCapture();
};
splitBar.setCapture && splitBar.setCapture();
return false;
});
/**
*
*/
$(".manual-fullscreen-switch").on("click", splitBar.reset);
});

View File

@ -92,60 +92,63 @@
<script src="{{cdnjs "/static/layer/layer.js"}}" type="text/javascript"></script> <script src="{{cdnjs "/static/layer/layer.js"}}" type="text/javascript"></script>
<script type="text/javascript"> <script type="text/javascript">
$(function () { $(function () {
$("#account,#passwd,#code").on('focus',function () { $("#account,#passwd,#code").on('focus', function () {
$(this).tooltip('destroy').parents('.form-group').removeClass('has-error');; $(this).tooltip('destroy').parents('.form-group').removeClass('has-error');
}); });
$(document).keydown(function (e) { $(document).keydown(function (e) {
var event = document.all ? window.event : e; var event = document.all ? window.event : e;
if(event.keyCode === 13){ if (event.keyCode === 13) {
$("#btn-login").click(); $("#btn-login").click();
} }
}); });
$("#btn-login").on('click',function () {
$("#btn-login").on('click', function () {
var $btn = $(this).button('loading'); var $btn = $(this).button('loading');
var account = $.trim($("#account").val()); var account = $.trim($("#account").val());
var password = $.trim($("#password").val()); var password = $.trim($("#password").val());
var code = $("#code").val(); var code = $("#code").val();
if(account === ""){
$("#account").tooltip({placement:"auto",title : "账号不能为空",trigger : 'manual'})
.tooltip('show')
.parents('.form-group').addClass('has-error');
$btn.button('reset');
return false;
}else if(password === ""){ if (account === "") {
$("#password").tooltip({title : '密码不能为空',trigger : 'manual'}) $("#account").tooltip({ placement: "auto", title: "账号不能为空", trigger: 'manual' })
.tooltip('show') .tooltip('show')
.parents('.form-group').addClass('has-error'); .parents('.form-group').addClass('has-error');
$btn.button('reset'); $btn.button('reset');
return false; return false;
}else if(code !== undefined && code === ""){ } else if (password === "") {
$("#code").tooltip({title : '验证码不能为空',trigger : 'manual'}) $("#password").tooltip({ title: '密码不能为空', trigger: 'manual' })
.tooltip('show') .tooltip('show')
.parents('.form-group').addClass('has-error'); .parents('.form-group').addClass('has-error');
$btn.button('reset'); $btn.button('reset');
return false; return false;
}else{ } else if (code !== undefined && code === "") {
$("#code").tooltip({ title: '验证码不能为空', trigger: 'manual' })
.tooltip('show')
.parents('.form-group').addClass('has-error');
$btn.button('reset');
return false;
} else {
$.ajax({ $.ajax({
url : "{{urlfor "AccountController.Login"}}", url: "{{urlfor "AccountController.Login"}}",
data : $("form").serializeArray(), data: $("form").serializeArray(),
dataType : "json", dataType: "json",
type : "POST", type: "POST",
success : function (res) { success: function (res) {
if (res.errcode !== 0) {
if(res.errcode !== 0){
$("#captcha-img").click(); $("#captcha-img").click();
$("#code").val(''); $("#code").val('');
layer.msg(res.message); layer.msg(res.message);
$btn.button('reset'); $btn.button('reset');
}else{ } else {
window.location = "/"; turl = res.data.turl;
if (turl === "") {
turl = "/";
}
window.location = turl;
} }
}, },
error :function () { error: function () {
$("#captcha-img").click(); $("#captcha-img").click();
$("#code").val(''); $("#code").val('');
layer.msg('系统错误'); layer.msg('系统错误');
@ -154,7 +157,6 @@
}); });
} }
return false; return false;
}); });
}); });

View File

@ -230,11 +230,12 @@
<script src="{{cdnjs "/static/bootstrap/js/bootstrap.min.js"}}"></script> <script src="{{cdnjs "/static/bootstrap/js/bootstrap.min.js"}}"></script>
<script src="{{cdnjs "/static/js/jquery.form.js"}}" type="text/javascript"></script> <script src="{{cdnjs "/static/js/jquery.form.js"}}" type="text/javascript"></script>
<script src="{{cdnjs "/static/jstree/3.3.4/jstree.min.js"}}" type="text/javascript"></script> <script src="{{cdnjs "/static/jstree/3.3.4/jstree.min.js"}}" type="text/javascript"></script>
<script type="text/javascript" src="{{cdnjs "/static/nprogress/nprogress.js"}}"></script> <script src="{{cdnjs "/static/nprogress/nprogress.js"}}" type="text/javascript"></script>
<script type="text/javascript" src="{{cdnjs "/static/highlight/highlight.js"}}"></script> <script src="{{cdnjs "/static/highlight/highlight.js"}}" type="text/javascript"></script>
<script type="text/javascript" src="{{cdnjs "/static/highlight/highlightjs-line-numbers.min.js"}}"></script> <script src="{{cdnjs "/static/highlight/highlightjs-line-numbers.min.js"}}" type="text/javascript"></script>
<script type="text/javascript" src="/static/js/jquery.highlight.js"></script> <script src="/static/js/jquery.highlight.js" type="text/javascript"></script>
<script type="text/javascript" src="/static/js/kancloud.js"></script> <script src="/static/js/kancloud.js" type="text/javascript"></script>
<script src="/static/js/splitbar.js" type="text/javascript"></script>
<script type="text/javascript"> <script type="text/javascript">
active_book_id = {{.Model.Identify}}; active_book_id = {{.Model.Identify}};
active_doc_id = {{.DocumentId}}; active_doc_id = {{.DocumentId}};