1
0
mirror of https://shylinux.com/x/ContextOS synced 2025-06-26 18:07:30 +08:00

mac add web.share

This commit is contained in:
shaoying 2018-06-23 18:57:34 +08:00
parent 74bd31bbd7
commit d2e150dac7
7 changed files with 306 additions and 177 deletions

View File

@ -127,7 +127,7 @@ var Index = &ctx.Context{Name: "aaa", Help: "认证中心",
}, },
Configs: map[string]*ctx.Config{ Configs: map[string]*ctx.Config{
"rootname": &ctx.Config{Name: "根用户名", Value: "root", Help: "根用户名"}, "rootname": &ctx.Config{Name: "根用户名", Value: "root", Help: "根用户名"},
"expire": &ctx.Config{Name: "会话超时(s)", Value: "120", Help: "会话超时"}, "expire": &ctx.Config{Name: "会话超时(s)", Value: "7200", Help: "会话超时"},
}, },
Commands: map[string]*ctx.Command{ Commands: map[string]*ctx.Command{
"login": &ctx.Command{Name: "login [sessid]|[[group] username password]]", Help: "用户登录", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) { "login": &ctx.Command{Name: "login [sessid]|[[group] username password]]", Help: "用户登录", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
@ -151,6 +151,11 @@ var Index = &ctx.Context{Name: "aaa", Help: "认证中心",
m.Log("info", m.Source(), "logon %s %s", m.Cap("username"), m.Cap("group")) m.Log("info", m.Source(), "logon %s %s", m.Cap("username"), m.Cap("group"))
m.Echo(m.Cap("username")) m.Echo(m.Cap("username"))
m.Append("username", m.Cap("username"))
m.Append("userrole", m.Cap("group"))
m.Appendv("aaa", m)
m.Sesss("aaa", m)
case 2, 3: case 2, 3:
group, username, password := arg[0], arg[0], arg[1] group, username, password := arg[0], arg[0], arg[1]
if len(arg) == 3 { if len(arg) == 3 {
@ -176,7 +181,13 @@ var Index = &ctx.Context{Name: "aaa", Help: "认证中心",
m.Login(msg) m.Login(msg)
aaa.sessions[m.Cap("sessid")] = msg.Target() aaa.sessions[m.Cap("sessid")] = msg.Target()
m.Echo(msg.Cap("sessid")) m.Echo(msg.Cap("sessid"))
} // }}}
m.Append("username", msg.Cap("username"))
m.Append("userrole", msg.Cap("group"))
m.Appendv("aaa", msg)
m.Sesss("aaa", msg)
}
// }}}
}}, }},
"share": &ctx.Command{Name: "share user", Help: "用户登录", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) { "share": &ctx.Command{Name: "share user", Help: "用户登录", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
if len(arg) == 0 { // {{{ if len(arg) == 0 { // {{{

View File

@ -21,7 +21,7 @@ import ( // {{{
func Right(str string) bool { func Right(str string) bool {
switch str { switch str {
case "", "0", "false", "off": case "", "0", "false", "off", "no", "error: ":
return false return false
} }
return true return true
@ -437,15 +437,16 @@ func (m *Message) Login(aaa *Message) { // {{{
} }
// }}} // }}}
func (m *Message) Log(action string, ctx *Context, str string, arg ...interface{}) { // {{{ func (m *Message) Log(action string, ctx *Context, str string, arg ...interface{}) *Message { // {{{
if !m.Options("log") { if !m.Options("log") {
return return m
} }
if l := m.Sesss("log"); l != nil { if l := m.Sesss("log"); l != nil {
l.Options("log", false) l.Options("log", false)
l.Cmd("log", action, fmt.Sprintf(str, arg...)) l.Cmd("log", action, fmt.Sprintf(str, arg...))
} }
return m
} }
// }}} // }}}
@ -706,7 +707,20 @@ func (m *Message) AssertOne(msg *Message, safe bool, hand ...func(msg *Message))
// }}} // }}}
func (m *Message) Spawn(c *Context, key ...string) *Message { // {{{ func (m *Message) Spawn(arg ...interface{}) *Message { // {{{
c := m.target
if len(arg) > 0 {
if v, ok := arg[0].(*Context); ok {
c, arg = v, arg[1:]
}
}
key := ""
if len(arg) > 0 {
if v, ok := arg[0].(string); ok {
key, arg = v, arg[1:]
}
}
msg := &Message{ msg := &Message{
code: m.root.Capi("nmessage", 1), code: m.root.Capi("nmessage", 1),
time: time.Now(), time: time.Now(),
@ -724,22 +738,22 @@ func (m *Message) Spawn(c *Context, key ...string) *Message { // {{{
msg.Sessions = make(map[string]*Message) msg.Sessions = make(map[string]*Message)
msg.Wait = make(chan bool) msg.Wait = make(chan bool)
if len(key) == 0 { if key == "" {
return msg return msg
} }
if msg.source.Sessions == nil { if msg.source.Sessions == nil {
msg.source.Sessions = make(map[string]*Message) msg.source.Sessions = make(map[string]*Message)
} }
msg.source.Sessions[key[0]] = msg msg.source.Sessions[key] = msg
msg.Name = key[0] msg.Name = key
return msg return msg
} }
// }}} // }}}
func (m *Message) Reply(key ...string) *Message { // {{{ func (m *Message) Reply(key ...string) *Message { // {{{
if m.Template == nil { if m.Template == nil {
m.Template = m.Spawn(m.source, key...) m.Template = m.Spawn(m.source)
} }
msg := m.Template msg := m.Template
@ -1102,6 +1116,7 @@ func (m *Message) Color(color int, str string, arg ...interface{}) *Message { //
// }}} // }}}
func (m *Message) Copy(msg *Message, meta string, arg ...string) *Message { // {{{ func (m *Message) Copy(msg *Message, meta string, arg ...string) *Message { // {{{
switch meta { switch meta {
case "session":
case "detail", "result": case "detail", "result":
m.Set(meta, msg.Meta[meta]...) m.Set(meta, msg.Meta[meta]...)
case "option", "append": case "option", "append":
@ -1255,6 +1270,29 @@ func (m *Message) Options(key string, arg ...bool) bool { // {{{
return Right(m.Option(key, arg)) return Right(m.Option(key, arg))
} }
// }}}
func (m *Message) Optionv(key string, arg ...interface{}) interface{} { // {{{
if len(arg) > 0 {
m.Put("option", key, arg[0])
return arg[0]
}
for msg := m; msg != nil; msg = msg.message {
if msg.Data == nil || msg.Data[key] == nil {
continue
}
if msg.Meta["option"] == nil || len(msg.Meta["option"]) == 0 {
continue
}
for _, v := range msg.Meta["option"] {
if v == key {
return msg.Data[key]
}
}
}
return nil
}
// }}} // }}}
func (m *Message) Append(key string, arg ...interface{}) string { // {{{ func (m *Message) Append(key string, arg ...interface{}) string { // {{{
m.Insert(key, 0, arg...) m.Insert(key, 0, arg...)
@ -1262,9 +1300,15 @@ func (m *Message) Append(key string, arg ...interface{}) string { // {{{
m.Add("append", key) m.Add("append", key)
} }
for msg := m; msg != nil; msg = msg.message { ms := []*Message{m}
if m.Has(key) { for i := 0; i < len(ms); i++ {
return m.Get(key) ms = append(ms, ms[i].messages...)
if ms[i].Has(key) {
for j := 0; j < len(ms[i].Meta["append"]); j++ {
if ms[i].Meta["append"][j] == key {
return ms[i].Get(key)
}
}
} }
} }
return "" return ""
@ -1282,6 +1326,30 @@ func (m *Message) Appends(key string, arg ...bool) bool { // {{{
return Right(m.Append(key, arg)) return Right(m.Append(key, arg))
} }
// }}}
func (m *Message) Appendv(key string, arg ...interface{}) interface{} { // {{{
if len(arg) > 0 {
m.Put("append", key, arg[0])
}
ms := []*Message{m}
for i := 0; i < len(ms); i++ {
ms = append(ms, ms[i].messages...)
if ms[i].Data == nil || ms[i].Data[key] == nil {
continue
}
if ms[i].Meta["append"] == nil || len(ms[i].Meta["append"]) == 0 {
continue
}
for _, v := range ms[i].Meta["append"] {
if v == key {
return ms[i].Data[key]
}
}
}
return nil
}
// }}} // }}}
func (m *Message) Start(name string, help string, arg ...string) bool { // {{{ func (m *Message) Start(name string, help string, arg ...string) bool { // {{{
@ -1339,7 +1407,8 @@ func (m *Message) Exec(key string, arg ...string) string { // {{{
} }
m.Hand = true m.Hand = true
x.Hand(m.Set("result").Set("append"), s, key, arg...) // x.Hand(m.Set("result").Set("append"), s, key, arg...)
x.Hand(m, s, key, arg...)
if x.Appends != nil { if x.Appends != nil {
for _, v := range m.Meta["append"] { for _, v := range m.Meta["append"] {
@ -2662,7 +2731,7 @@ var Index = &Context{Name: "ctx", Help: "模块中心",
"right": &Command{ "right": &Command{
Name: "right [share|add|del group [cache|config|command item]]", Name: "right [share|add|del group [cache|config|command item]]",
Help: "用户组管理,查看、添加、删除用户组或是接口", Help: "用户组管理,查看、添加、删除用户组或是接口",
Formats: map[string]int{"check": 0, "add": 0, "del": 0, "cache": 0, "config": 0, "command": 0}, Formats: map[string]int{"check": 0, "add": 0, "del": 0, "brow": 0, "cache": 0, "config": 0, "command": 0},
Hand: func(m *Message, c *Context, key string, arg ...string) { Hand: func(m *Message, c *Context, key string, arg ...string) {
index := m.Target().Index // {{{ index := m.Target().Index // {{{
if index == nil { if index == nil {
@ -2697,7 +2766,7 @@ var Index = &Context{Name: "ctx", Help: "模块中心",
} }
group := current group := current
if len(arg) > 1 { if len(arg) > 0 {
group = current.Index[arg[0]] group = current.Index[arg[0]]
} }
@ -2713,20 +2782,24 @@ var Index = &Context{Name: "ctx", Help: "模块中心",
case m.Has("cache"): case m.Has("cache"):
if _, ok := group.Caches[item]; ok { if _, ok := group.Caches[item]; ok {
m.Echo("ok") m.Echo("ok")
return
} }
case m.Has("config"): case m.Has("config"):
if _, ok := group.Configs[item]; ok { if _, ok := group.Configs[item]; ok {
m.Echo("ok") m.Echo("ok")
return
} }
case m.Has("command"): case m.Has("command"):
if len(arg) > 1 { if len(arg) > 1 {
if _, ok := group.Commands[item]; !ok { if _, ok := group.Commands[item]; !ok {
m.Echo("no")
return return
} }
} }
if len(arg) > 2 { if len(arg) > 2 {
if _, ok := group.Commands[item].Shares[arg[2]]; !ok { if _, ok := group.Commands[item].Shares[arg[2]]; !ok {
m.Echo("no")
return return
} }
} }
@ -2739,11 +2812,17 @@ var Index = &Context{Name: "ctx", Help: "模块中心",
return return
} }
} }
m.Echo("no")
return return
} }
m.Echo("ok") m.Echo("ok")
return
default:
m.Echo("ok")
return
} }
} }
m.Echo("no")
return return
case m.Has("add"): case m.Has("add"):
if group == nil { if group == nil {
@ -2839,6 +2918,7 @@ var Index = &Context{Name: "ctx", Help: "模块中心",
shares[arg[2]] = shares[arg[2]][:i] shares[arg[2]] = shares[arg[2]][:i]
} }
} }
gs[i].Commands[item].Shares = shares
default: default:
delete(index, gs[i].Name) delete(index, gs[i].Name)
@ -2847,40 +2927,40 @@ var Index = &Context{Name: "ctx", Help: "模块中心",
} }
default: default:
m.Echo("%s:caches\n", current.Name) m.Echo("%s:caches\n", group.Name)
if void != nil { if void != nil {
for k, c := range void.Caches { for k, c := range void.Caches {
m.Echo(" %s: %s\n", k, c.Value) m.Echo(" %s: %s\n", k, c.Value)
} }
} }
for k, c := range current.Caches { for k, c := range group.Caches {
m.Echo(" %s: %s\n", k, c.Value) m.Echo(" %s: %s\n", k, c.Value)
} }
m.Echo("%s:configs\n", current.Name) m.Echo("%s:configs\n", group.Name)
if void != nil { if void != nil {
for k, c := range void.Configs { for k, c := range void.Configs {
m.Echo(" %s: %s\n", k, c.Value) m.Echo(" %s: %s\n", k, c.Value)
} }
} }
for k, c := range current.Configs { for k, c := range group.Configs {
m.Echo(" %s: %s\n", k, c.Value) m.Echo(" %s: %s\n", k, c.Value)
} }
m.Echo("%s:commands\n", current.Name) m.Echo("%s:commands\n", group.Name)
if void != nil { if void != nil {
for k, c := range void.Commands { for k, c := range void.Commands {
m.Echo(" %s: %s\n", k, c.Name) m.Echo(" %s: %s\n", k, c.Name)
} }
} }
for k, c := range current.Commands { for k, c := range group.Commands {
m.Echo(" %s: %s\n", k, c.Name) m.Echo(" %s: %s %v\n", k, c.Name, c.Shares)
} }
m.Echo("%s:contexts\n", current.Name) m.Echo("%s:contexts\n", group.Name)
if void != nil { if void != nil {
for k, c := range void.Index { for k, c := range void.Index {
m.Echo(" %s: %s\n", k, c.Name) m.Echo(" %s: %s\n", k, c.Name)
} }
} }
for k, c := range current.Index { for k, c := range group.Index {
m.Echo(" %s: %s\n", k, c.Name) m.Echo(" %s: %s\n", k, c.Name)
} }
} // }}} } // }}}

View File

@ -196,26 +196,33 @@ func (web *WEB) AppendJson(msg *ctx.Message) string { // {{{
// }}} // }}}
func (web *WEB) Trans(m *ctx.Message, key string, hand func(*ctx.Message, *ctx.Context, string, ...string)) { // {{{ func (web *WEB) Trans(m *ctx.Message, key string, hand func(*ctx.Message, *ctx.Context, string, ...string)) { // {{{
web.HandleFunc(key, func(w http.ResponseWriter, r *http.Request) { web.HandleFunc(key, func(w http.ResponseWriter, r *http.Request) {
msg := m.Spawn(m.Target()).Set("detail", key) msg := m.Spawn().Set("detail", key)
msg.Option("method", r.Method)
msg.Add("option", "method", r.Method) msg.Option("referer", r.Header.Get("Referer"))
for k, v := range r.Form { for k, v := range r.Form {
msg.Add("option", k, v...) msg.Add("option", k, v...)
} }
for _, v := range r.Cookies() { for _, v := range r.Cookies() {
msg.Add("option", v.Name, v.Value) msg.Option(v.Name, v.Value)
} }
msg.Log("cmd", nil, "%s [] %v", key, msg.Meta["option"])
msg.Log("cmd", nil, "%s [] %v", key, msg.Meta["option"])
msg.Put("option", "request", r).Put("option", "response", w) msg.Put("option", "request", r).Put("option", "response", w)
if hand(msg, msg.Target(), key); len(msg.Meta["append"]) > -1 {
w.Write([]byte(web.AppendJson(msg))) if hand(msg, msg.Target(), key); msg.Has("redirect") {
http.Redirect(w, r, msg.Append("redirect"), http.StatusFound)
return
}
if msg.Has("template") {
msg.Spawn().Cmd("/render", msg.Meta["template"])
return
}
if msg.Has("append") {
msg.Spawn().Copy(msg, "append").Cmd("/json")
return return
} }
for _, v := range msg.Meta["result"] { for _, v := range msg.Meta["result"] {
msg.Log("info", nil, "%s", v)
w.Write([]byte(v)) w.Write([]byte(v))
} }
}) })
@ -707,97 +714,36 @@ var Index = &ctx.Context{Name: "web", Help: "应用中心",
// }}} // }}}
}}, }},
"/upload": &ctx.Command{Name: "/upload", Help: "文件上传", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) { "/upload": &ctx.Command{Name: "/upload", Help: "文件上传", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
r := m.Data["request"].(*http.Request) // {{{ r := m.Optionv("request").(*http.Request)
w := m.Data["response"].(http.ResponseWriter) w := m.Optionv("response").(http.ResponseWriter)
if !m.Options("file") { if !m.Options("dir") {
m.Option("file", m.Cap("directory")) m.Option("dir", m.Cap("directory"))
} }
a := m check := m.Spawn().Cmd("/share")
auth := m.Spawn(m.Target()).Put("option", "request", r).Put("option", "response", w) if !check.Results(0) {
auth.CallBack(true, func(aaa *ctx.Message) *ctx.Message { m.Copy(check, "append")
if aaa != nil {
a = aaa
// m.Sesss("aaa", aaa)
}
return aaa
}, "/check", "command", "/upload", "file", m.Option("file"))
if auth.Append("right") != "ok" {
return return
} }
aaa := check.Appendv("aaa").(*ctx.Message)
if m.Option("method") == "POST" {
if m.Options("notshareto") { // 取消共享
msg := m.Spawn(m.Target())
msg.Sesss("aaa", a)
msg.Cmd("right", "del", m.Option("notshareto"), "command", "/upload", "file", m.Option("sharefile"))
m.Append("link", "hello")
return
} else if m.Options("shareto") { //共享目录
msg := m.Spawn(m.Target()) //TODO
msg.Sesss("aaa", a)
msg.Cmd("right", "add", m.Option("shareto"), "command", "/upload", "file", m.Option("sharefile"))
m.Append("link", "hello")
return
} else if m.Options("filename") { //添加文件或目录
name := path.Join(m.Option("file"), m.Option("filename"))
if _, e := os.Stat(name); e != nil {
if m.Options("content") {
f, e := os.Create(name)
m.Assert(e)
defer f.Close()
_, e = f.WriteString(m.Option("content"))
m.Assert(e)
} else {
e = os.Mkdir(name, 0766)
m.Assert(e)
}
m.Option("message", name, " create success!")
} else {
m.Option("message", name, "already exist!")
}
} else { //上传文件
file, header, e := r.FormFile("file")
m.Assert(e)
name := path.Join(m.Option("file"), header.Filename)
if _, e := os.Stat(name); e != nil {
f, e := os.Create(name)
m.Assert(e)
defer f.Close()
_, e = io.Copy(f, file)
m.Assert(e)
m.Option("message", name, "upload success!")
} else {
m.Option("message", name, "already exist!")
}
}
}
// 输出文件 // 输出文件
s, e := os.Stat(m.Option("file")) s, e := os.Stat(m.Option("dir"))
if m.Assert(e); !s.IsDir() { if m.Assert(e); !s.IsDir() {
http.ServeFile(w, r, m.Option("file")) http.ServeFile(w, r, m.Option("dir"))
return return
} }
// 解析模板
render := m.Spawn(m.Target()).Put("option", "request", r).Put("option", "response", w)
// 共享列表 // 共享列表
share := render.Sesss("share", m.Target()) share := m.Sesss("share", m.Target())
index := share.Target().Index index := share.Target().Index
if index != nil && index[a.Append("group")] != nil { if index != nil && index[aaa.Append("userrole")] != nil {
for k, v := range index[a.Append("group")].Index { for k, v := range index[aaa.Append("userrole")].Index {
for i, j := range v.Commands { for i, j := range v.Commands {
for v, n := range j.Shares { for v, n := range j.Shares {
for _, nn := range n { for _, nn := range n {
if match, e := regexp.MatchString(nn, m.Option("file")); m.Assert(e) && match { if match, e := regexp.MatchString(nn, m.Option("dir")); m.Assert(e) && match {
share.Add("append", "group", k) share.Add("append", "group", k)
share.Add("append", "command", i) share.Add("append", "command", i)
share.Add("append", "argument", v) share.Add("append", "argument", v)
@ -811,11 +757,11 @@ var Index = &ctx.Context{Name: "web", Help: "应用中心",
} }
// 输出目录 // 输出目录
fs, e := ioutil.ReadDir(m.Option("file")) fs, e := ioutil.ReadDir(m.Option("dir"))
m.Assert(e) m.Assert(e)
fs = append(fs, s) fs = append(fs, s)
list := render.Sesss("list", m.Target()) list := m.Sesss("list", m.Target())
list.Option("file", m.Option("file")) list.Option("dir", m.Option("dir"))
// 目录排序 // 目录排序
max := true max := true
@ -854,7 +800,7 @@ var Index = &ctx.Context{Name: "web", Help: "应用中心",
for _, v := range fs { for _, v := range fs {
name := v.Name() name := v.Name()
if v == s { if v == s {
if name == m.Option("file") { if name == m.Option("dir") {
continue continue
} }
name = ".." name = ".."
@ -869,30 +815,135 @@ var Index = &ctx.Context{Name: "web", Help: "应用中心",
list.Add("append", "time", v.ModTime().Format("2006-01-02 15:04:05")) list.Add("append", "time", v.ModTime().Format("2006-01-02 15:04:05"))
list.Add("append", "size", kit.FmtSize(v.Size())) list.Add("append", "size", kit.FmtSize(v.Size()))
list.Add("append", "name", name) list.Add("append", "name", name)
list.Add("append", "path", path.Join(m.Option("file"), name)) list.Add("append", "path", path.Join(m.Option("dir"), name))
} }
// 执行命令 // 执行命令
switch m.Option("cmd") { switch m.Option("cmd") {
case "git": case "git":
git := render.Sesss("git", m.Target()) git := m.Sesss("git", m.Target())
branch := m.Find("nfs").Cmd("git", "-C", m.Option("file"), "branch") branch := m.Find("nfs").Cmd("git", "-C", m.Option("dir"), "branch")
git.Option("branch", branch.Result(0)) git.Option("branch", branch.Result(0))
status := m.Find("nfs").Cmd("git", "-C", m.Option("file"), "status") status := m.Find("nfs").Cmd("git", "-C", m.Option("dir"), "status")
git.Option("status", status.Result(0)) git.Option("status", status.Result(0))
} }
render.Option("title", "upload") m.Append("title", "upload")
render.Option("tmpl", "userinfo", "share", "list", "git", "upload", "create") m.Append("tmpl", "userinfo", "share", "list", "git", "upload", "create")
render.Cmd("/render", m.Conf("upload_main"), m.Conf("upload_tmpl")) m.Append("template", m.Conf("upload_main"), m.Conf("upload_tmpl"))
}},
"/create": &ctx.Command{Name: "/create", Help: "创建目录或文件", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
if check := m.Spawn().Cmd("/share"); !check.Results(0) { // {{{
m.Copy(check, "append")
return
}
r := m.Optionv("request").(*http.Request)
if m.Option("method") == "POST" {
if m.Options("filename") { //添加文件或目录
name := path.Join(m.Option("dir"), m.Option("filename"))
if _, e := os.Stat(name); e != nil {
if m.Options("content") {
f, e := os.Create(name)
m.Assert(e)
defer f.Close()
_, e = f.WriteString(m.Option("content"))
m.Assert(e)
} else {
e = os.Mkdir(name, 0766)
m.Assert(e)
}
m.Append("message", name, " create success!")
} else {
m.Append("message", name, "already exist!")
}
} else { //上传文件
file, header, e := r.FormFile("file")
m.Assert(e)
name := path.Join(m.Option("dir"), header.Filename)
if _, e := os.Stat(name); e != nil {
f, e := os.Create(name)
m.Assert(e)
defer f.Close()
_, e = io.Copy(f, file)
m.Assert(e)
m.Append("message", name, "upload success!")
} else {
m.Append("message", name, "already exist!")
}
}
}
m.Append("redirect", m.Option("referer"))
// }}} // }}}
}}, }},
"/render": &ctx.Command{Name: "/render [main [tmpl]]", Help: "生成模板", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) { "/share": &ctx.Command{Name: "/share", Help: "资源共享", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
w := m.Data["response"].(http.ResponseWriter) check := m.Spawn().Cmd("/check", "command", "/share", "dir", m.Option("dir")) // {{{
if !check.Results(0) {
m.Copy(check, "append")
return
}
m.Log("fuck", nil, "wh")
tpl := template.Must(template.New("fuck").Funcs(ctx.CGI).ParseGlob(path.Join(m.Conf("template_dir"), m.Conf("common_tmpl")))) msg := check.Appendv("aaa").(*ctx.Message).Spawn(m.Target())
if m.Options("shareto") {
msg.Cmd("right", "add", m.Option("shareto"), "command", "/share", "dir", m.Option("dir"))
}
if m.Options("notshareto") {
m.Log("fuck", nil, "wh %v", msg)
msg.Cmd("right", "del", m.Option("notshareto"), "command", "/share", "dir", m.Option("dir"))
m.Log("fuck", nil, "wh %v", msg.Meta["result"])
}
m.Echo("ok")
// }}}
}},
"/check": &ctx.Command{Name: "/check cache|config|command name args", Help: "权限检查, cache|config|command: 接口类型, name: 接口名称, args: 其它参数", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
w := m.Optionv("response").(http.ResponseWriter) //{{{
if login := m.Spawn().Cmd("/login"); login.Has("redirect") {
if msg := m.Spawn().Cmd("right", "check", login.Append("userrole"), arg); msg.Results(0) {
m.Copy(login, "append").Echo(msg.Result(0))
return
}
w.WriteHeader(http.StatusForbidden)
m.Append("message", "please contact manager")
m.Echo("no")
return
} else {
m.Copy(login, "append").Echo("no")
}
// }}}
}},
"/login": &ctx.Command{Name: "/login", Help: "用户登录", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
w := m.Optionv("response").(http.ResponseWriter) // {{{
if m.Options("sessid") {
if aaa := m.Find("aaa").Cmd("login", m.Option("sessid")); aaa.Results(0) {
m.Append("redirect", m.Option("referer"))
return
}
}
if m.Options("username") && m.Options("password") {
if aaa := m.Find("aaa").Cmd("login", m.Option("username"), m.Option("password")); aaa.Results(0) {
http.SetCookie(w, &http.Cookie{Name: "sessid", Value: aaa.Result(0)})
m.Append("redirect", m.Option("referer"))
return
}
}
w.WriteHeader(http.StatusUnauthorized)
m.Append("template", "login.html")
// }}}
}},
"/render": &ctx.Command{Name: "/render [main [tmpl]]", Help: "模板响应, main: 模板入口, tmpl: 附加模板", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
w := m.Optionv("response").(http.ResponseWriter) // {{{
tpl := template.Must(template.New("render").Funcs(ctx.CGI).ParseGlob(path.Join(m.Conf("template_dir"), m.Conf("common_tmpl"))))
if len(arg) > 1 { if len(arg) > 1 {
tpl = template.Must(tpl.ParseGlob(path.Join(m.Conf("template_dir"), arg[1]))) tpl = template.Must(tpl.ParseGlob(path.Join(m.Conf("template_dir"), arg[1])))
} }
@ -903,48 +954,25 @@ var Index = &ctx.Context{Name: "web", Help: "应用中心",
} }
w.Header().Add("Content-Type", "text/html") w.Header().Add("Content-Type", "text/html")
m.Assert(tpl.ExecuteTemplate(w, main, m)) m.Assert(tpl.ExecuteTemplate(w, main, m.Message()))
// }}}
}}, }},
"/check": &ctx.Command{Name: "/check sessid", Help: "权限检查", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) { "/json": &ctx.Command{Name: "/json", Help: "json响应", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
r := m.Data["request"].(*http.Request) w := m.Optionv("response").(http.ResponseWriter) // {{{
w := m.Data["response"].(http.ResponseWriter)
user := m.Spawn(m.Target()).Put("option", "request", r).Put("option", "response", w) meta := map[string][]string{}
user.CallBack(true, func(aaa *ctx.Message) *ctx.Message { if len(m.Meta["append"]) > 0 {
if aaa.Appends("group") { meta["append"] = m.Meta["append"]
msg := aaa.Spawn(m.Target()).Cmd("right", "check", aaa.Append("group"), arg) for _, v := range m.Meta["append"] {
m.Append("right", msg.Result(0)) meta[v] = m.Meta[v]
}
return aaa
}, "/login")
}},
"/login": &ctx.Command{Name: "/login", Help: "用户登录", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
r := m.Data["request"].(*http.Request)
w := m.Data["response"].(http.ResponseWriter)
if m.Options("sessid") {
if aaa := m.Find("aaa").Cmd("login", m.Option("sessid")); aaa.Result(0) != "error: " {
m.Append("username", aaa.Cap("username"))
m.Append("group", aaa.Cap("group"))
m.Back(m)
return
} }
} }
sessid := "" if b, e := json.Marshal(meta); m.Assert(e) {
if m.Options("username") && m.Options("password") { w.Header().Set("Content-Type", "application/javascript")
msg := m.Find("aaa").Cmd("login", m.Option("username"), m.Option("password")) w.Write(b)
sessid = msg.Result(0)
http.SetCookie(w, &http.Cookie{Name: "sessid", Value: sessid})
} }
// }}}
if sessid != "" {
http.Redirect(w, r, "/upload", http.StatusFound)
} else {
render := m.Spawn(m.Target()).Put("option", "request", r).Put("option", "response", w)
render.Cmd("/render", "login.html")
}
m.Back(m)
}}, }},
"temp": &ctx.Command{Name: "temp", Help: "应用示例", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) { "temp": &ctx.Command{Name: "temp", Help: "应用示例", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
msg := m.Spawn(m.Target()) msg := m.Spawn(m.Target())

View File

@ -48,7 +48,12 @@ ctx = {
case 4: case 4:
switch (xhr.status) { switch (xhr.status) {
case 200: case 200:
var msg = JSON.parse(xhr.responseText||'{"result":[]}'); try {
var msg = JSON.parse(xhr.responseText||'{"result":[]}');
} catch (e) {
msg = {"result": [xhr.responseText]}
}
msg && console.log(msg) msg && console.log(msg)
msg.result && console.log(msg.result.join("")); msg.result && console.log(msg.result.join(""));
typeof cb == "function" && cb(msg) typeof cb == "function" && cb(msg)

View File

@ -33,6 +33,10 @@
</style> </style>
{{end}} {{end}}
{{define "main"}}
welcome to context world!
{{end}}
{{define "tail"}} {{define "tail"}}
<script src="library/context.js"></script> <script src="library/context.js"></script>
</body> </body>

View File

@ -10,7 +10,7 @@
{{define "userinfo"}} {{define "userinfo"}}
<fieldset><legend>userinfo</legend> <fieldset><legend>userinfo</legend>
welcome <span class="username">{{meta .username}}</span> to context world welcome <span class="username">{{append . "username"}}</span> to context world
<button onclick="return logout(event)">logout</button> <button onclick="return logout(event)">logout</button>
</fieldset> </fieldset>
<style> <style>
@ -30,8 +30,8 @@
{{define "share"}} {{define "share"}}
<fieldset><legend>share</legend> <fieldset><legend>share</legend>
<form method="POST" onsubmit="return share(event, '{{msg . "option" "file"}}')"> <form method="POST">
<label>share to:</label><input type="text" name="shareto" required> <label>share to:</label><input type="text" name="shareto" value="{{msg . "option" "dir"}}" required>
<input type="submit"> <input type="submit">
</form> </form>
<table> <table>
@ -58,21 +58,21 @@
</table> </table>
</fieldset> </fieldset>
<script> <script>
function share(event, file) { function share(event, dir) {
var fields = event.target.elements; var fields = event.target.elements;
var shareto = fields["shareto"].value var shareto = fields["shareto"].value
ctx.POST("/upload", { ctx.POST("/upload", {
shareto: shareto, shareto: shareto,
sharefile: file, sharedir: dir,
}, function(msg) { }, function(msg) {
ctx.Refresh(); ctx.Refresh();
}) })
return false; return false;
} }
function deleteshare(event, file, group) { function deleteshare(event, dir, group) {
ctx.POST("/upload", { ctx.POST("/share", {
notshareto: group, notshareto: group,
sharefile: file, sharedir: dir,
}, function(msg) { }, function(msg) {
ctx.Refresh(); ctx.Refresh();
}) })

View File

@ -1,5 +1,5 @@
{{define "list"}} {{define "list"}}
<fieldset><legend><input type="text" id="dir" value="{{meta .file}}" onkeydown="return Change(event)"></legend> <fieldset><legend><input type="text" id="dir" value="{{meta .dir}}" onkeydown="return Change(event)"></legend>
<table> <table>
<colgroup>{{range .append}}<col class="{{.}}">{{end}}</colgroup> <colgroup>{{range .append}}<col class="{{.}}">{{end}}</colgroup>
@ -26,7 +26,7 @@
{{range $key := index $meta "append"}} {{range $key := index $meta "append"}}
{{if eq $key "name"}} {{if eq $key "name"}}
<td class="{{$key}}"> <td class="{{$key}}">
<a href="/upload?file={{index $meta "path" $i}}"><code>{{index $meta $key $i}}</code></a> <a href="/upload?dir={{index $meta "path" $i}}"><code>{{index $meta $key $i}}</code></a>
</td> </td>
{{else if eq $key "path"}} {{else if eq $key "path"}}
{{else}} {{else}}
@ -62,7 +62,7 @@
<script> <script>
function Change(event) { function Change(event) {
if (event.keyCode == 13) { if (event.keyCode == 13) {
ctx.Search("file", event.target.value); ctx.Search("dir", event.target.value);
} }
} }
@ -85,7 +85,7 @@
{{define "upload"}} {{define "upload"}}
<fieldset><legend>upload</legend> <fieldset><legend>upload</legend>
<form method="POST" action="/upload" enctype="multipart/form-data"> <form method="POST" action="/create?dir={{option . "dir"}}" enctype="multipart/form-data">
<input type="file" name="file"><input type="submit"> <input type="file" name="file"><input type="submit">
</form> </form>
</fieldset> </fieldset>
@ -93,7 +93,7 @@
{{define "create"}} {{define "create"}}
<fieldset><legend>create</legend> <fieldset><legend>create</legend>
<form method="POST" action="/upload"> <form method="POST" action="/create?dir={{option . "dir"}}">
<table> <table>
<tr><td>filename:</td><td><input type="text" name="filename" required><input type="submit"></td></tr> <tr><td>filename:</td><td><input type="text" name="filename" required><input type="submit"></td></tr>
<tr><td>content:</td><td><textarea rows="5" cols="80" name="content"></textarea></td></tr> <tr><td>content:</td><td><textarea rows="5" cols="80" name="content"></textarea></td></tr>
@ -105,13 +105,14 @@
{{define "main"}} {{define "main"}}
{{$msg := .}} {{$msg := .}}
{{$meta := .Meta}} {{$meta := .Meta}}
{{$sess := .Sessions}}
{{range .Meta.tmpl}} {{range .Meta.tmpl}}
{{if eq . "login"}} {{if eq . "login"}}
{{template "login" $meta}} {{template "login" $meta}}
{{else if eq . "userinfo"}} {{else if eq . "userinfo"}}
{{template "userinfo" $meta}} {{template "userinfo" $msg}}
{{else if eq . "share"}} {{else if eq . "share"}}
{{template "share" $msg.Sessions.share}} {{template "share" $sess.share}}
{{else if eq . "list"}} {{else if eq . "list"}}
{{template "list" $msg.Sessions.list.Meta}} {{template "list" $msg.Sessions.list.Meta}}
{{else if eq . "git"}} {{else if eq . "git"}}
@ -119,9 +120,9 @@
{{template "git" $msg.Sessions.git.Meta}} {{template "git" $msg.Sessions.git.Meta}}
{{end}} {{end}}
{{else if eq . "upload"}} {{else if eq . "upload"}}
{{template "upload" $meta}} {{template "upload" $msg}}
{{else if eq . "create"}} {{else if eq . "create"}}
{{template "create" $meta}} {{template "create" $msg}}
{{end}} {{end}}
{{end}} {{end}}
{{end}} {{end}}