From c1eb4d894a092aed1b87ddf5f80ee824fd56789d Mon Sep 17 00:00:00 2001 From: Unknown Date: Mon, 5 May 2014 13:08:01 -0400 Subject: [PATCH] Clean api code --- cmd/dump.go | 13 +++-- cmd/web.go | 15 ++++- modules/auth/apiv1/miscellaneous.go | 89 +++++++++++++++++++++++++++++ modules/auth/auth.go | 6 +- modules/base/base.go | 5 ++ modules/base/markdown.go | 11 ++-- modules/middleware/auth.go | 12 ++-- modules/middleware/context.go | 13 +++++ public/js/app.js | 12 ++-- routers/api/v1/miscellaneous.go | 36 ++++++++++-- routers/dashboard.go | 14 ++++- routers/install.go | 12 ++-- templates/admin/nav.tmpl | 2 +- templates/base/navbar.tmpl | 21 ++++--- templates/home.tmpl | 4 +- templates/install.tmpl | 33 ++++------- templates/issue/create.tmpl | 4 +- templates/issue/view.tmpl | 4 +- templates/repo/hooks_add.tmpl | 89 ++++++++++++++--------------- templates/repo/hooks_edit.tmpl | 3 + 20 files changed, 277 insertions(+), 121 deletions(-) create mode 100644 modules/auth/apiv1/miscellaneous.go diff --git a/cmd/dump.go b/cmd/dump.go index 035f7828b8..1bac1aeeb2 100644 --- a/cmd/dump.go +++ b/cmd/dump.go @@ -5,9 +5,11 @@ package cmd import ( + "fmt" "log" "os" "path" + "time" "github.com/Unknwon/cae/zip" "github.com/codegangsta/cli" @@ -43,11 +45,12 @@ func runDump(*cli.Context) { log.Fatalf("Fail to dump database: %v", err) } + fileName := fmt.Sprintf("gogs-dump-%d.zip", time.Now().Unix()) log.Printf("Packing dump files...") - z, err := zip.Create("gogs-dump.zip") + z, err := zip.Create(fileName) if err != nil { - os.Remove("gogs-dump.zip") - log.Fatalf("Fail to create gogs-dump.zip: %v", err) + os.Remove(fileName) + log.Fatalf("Fail to create %s: %v", fileName, err) } execDir, _ := base.ExecDir() @@ -56,8 +59,8 @@ func runDump(*cli.Context) { z.AddFile("custom/conf/app.ini", path.Join(execDir, "custom/conf/app.ini")) z.AddDir("log", path.Join(execDir, "log")) if err = z.Close(); err != nil { - os.Remove("gogs-dump.zip") - log.Fatalf("Fail to save gogs-dump.zip: %v", err) + os.Remove(fileName) + log.Fatalf("Fail to save %s: %v", fileName, err) } log.Println("Finish dumping!") diff --git a/cmd/web.go b/cmd/web.go index bad19bfeb1..2d80a89b7d 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -15,6 +15,7 @@ import ( qlog "github.com/qiniu/log" "github.com/gogits/gogs/modules/auth" + "github.com/gogits/gogs/modules/auth/apiv1" "github.com/gogits/gogs/modules/avatar" "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" @@ -54,7 +55,10 @@ func runWeb(*cli.Context) { m := newMartini() // Middlewares. - m.Use(middleware.Renderer(middleware.RenderOptions{Funcs: []template.FuncMap{base.TemplateFuncs}})) + m.Use(middleware.Renderer(middleware.RenderOptions{ + Funcs: []template.FuncMap{base.TemplateFuncs}, + IndentJSON: true, + })) m.Use(middleware.InitContext()) reqSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true}) @@ -76,10 +80,15 @@ func runWeb(*cli.Context) { m.Group("/api/v1", func(r martini.Router) { // Miscellaneous. - r.Post("/markdown", v1.Markdown) + r.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown) + r.Post("/markdown/raw", v1.MarkdownRaw) // Users. r.Get("/users/search", v1.SearchUser) + + r.Any("**", func(ctx *middleware.Context) { + ctx.JSON(404, &base.ApiJsonErr{"Not Found", v1.DOC_URL}) + }) }) avt := avatar.CacheServer("public/img/avatar/", "public/img/avatar_default.jpg") @@ -87,7 +96,7 @@ func runWeb(*cli.Context) { m.Get("/avatar/:hash", avt.ServeHTTP) m.Group("/user", func(r martini.Router) { - r.Get("/login", user.SignIn) + r.Get("/login", user.SignIn) // TODO r.Post("/login", bindIgnErr(auth.LogInForm{}), user.SignInPost) r.Get("/login/:name", user.SocialSignIn) r.Get("/sign_up", user.SignUp) diff --git a/modules/auth/apiv1/miscellaneous.go b/modules/auth/apiv1/miscellaneous.go new file mode 100644 index 0000000000..c34bdfa43b --- /dev/null +++ b/modules/auth/apiv1/miscellaneous.go @@ -0,0 +1,89 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package apiv1 + +import ( + "net/http" + "reflect" + + "github.com/go-martini/martini" + + "github.com/gogits/gogs/modules/auth" + "github.com/gogits/gogs/modules/base" + "github.com/gogits/gogs/modules/log" + "github.com/gogits/gogs/modules/middleware/binding" +) + +type MarkdownForm struct { + Text string `form:"text" binding:"Required"` + Mode string `form:"mode"` + Context string `form:"context"` +} + +func (f *MarkdownForm) Name(field string) string { + names := map[string]string{ + "Text": "text", + } + return names[field] +} + +func (f *MarkdownForm) Validate(errs *binding.BindingErrors, req *http.Request, ctx martini.Context) { + data := ctx.Get(reflect.TypeOf(base.TmplData{})).Interface().(base.TmplData) + validateApiReq(errs, data, f) +} + +func validateApiReq(errs *binding.BindingErrors, data base.TmplData, f auth.Form) { + if errs.Count() == 0 { + return + } else if len(errs.Overall) > 0 { + for _, err := range errs.Overall { + log.Error("%s: %v", reflect.TypeOf(f), err) + } + return + } + + data["HasError"] = true + + typ := reflect.TypeOf(f) + val := reflect.ValueOf(f) + + if typ.Kind() == reflect.Ptr { + typ = typ.Elem() + val = val.Elem() + } + + for i := 0; i < typ.NumField(); i++ { + field := typ.Field(i) + + fieldName := field.Tag.Get("form") + // Allow ignored fields in the struct + if fieldName == "-" { + continue + } + + if err, ok := errs.Fields[field.Name]; ok { + data["Err_"+field.Name] = true + switch err { + case binding.BindingRequireError: + data["ErrorMsg"] = f.Name(field.Name) + " cannot be empty" + case binding.BindingAlphaDashError: + data["ErrorMsg"] = f.Name(field.Name) + " must be valid alpha or numeric or dash(-_) characters" + case binding.BindingAlphaDashDotError: + data["ErrorMsg"] = f.Name(field.Name) + " must be valid alpha or numeric or dash(-_) or dot characters" + case binding.BindingMinSizeError: + data["ErrorMsg"] = f.Name(field.Name) + " must contain at least " + auth.GetMinMaxSize(field) + " characters" + case binding.BindingMaxSizeError: + data["ErrorMsg"] = f.Name(field.Name) + " must contain at most " + auth.GetMinMaxSize(field) + " characters" + case binding.BindingEmailError: + data["ErrorMsg"] = f.Name(field.Name) + " is not a valid e-mail address" + case binding.BindingUrlError: + data["ErrorMsg"] = f.Name(field.Name) + " is not a valid URL" + default: + data["ErrorMsg"] = "Unknown error: " + err + } + return + } + } +} diff --git a/modules/auth/auth.go b/modules/auth/auth.go index 2f77349177..62728acceb 100644 --- a/modules/auth/auth.go +++ b/modules/auth/auth.go @@ -91,7 +91,7 @@ func (f *LogInForm) Validate(errors *binding.BindingErrors, req *http.Request, c validate(errors, data, f) } -func getMinMaxSize(field reflect.StructField) string { +func GetMinMaxSize(field reflect.StructField) string { for _, rule := range strings.Split(field.Tag.Get("binding"), ";") { if strings.HasPrefix(rule, "MinSize(") || strings.HasPrefix(rule, "MaxSize(") { return rule[8 : len(rule)-1] @@ -128,9 +128,9 @@ func validate(errors *binding.BindingErrors, data base.TmplData, form Form) { case binding.BindingAlphaDashDotError: data["ErrorMsg"] = form.Name(field.Name) + " must be valid alpha or numeric or dash(-_) or dot characters" case binding.BindingMinSizeError: - data["ErrorMsg"] = form.Name(field.Name) + " must contain at least " + getMinMaxSize(field) + " characters" + data["ErrorMsg"] = form.Name(field.Name) + " must contain at least " + GetMinMaxSize(field) + " characters" case binding.BindingMaxSizeError: - data["ErrorMsg"] = form.Name(field.Name) + " must contain at most " + getMinMaxSize(field) + " characters" + data["ErrorMsg"] = form.Name(field.Name) + " must contain at most " + GetMinMaxSize(field) + " characters" case binding.BindingEmailError: data["ErrorMsg"] = form.Name(field.Name) + " is not a valid e-mail address" case binding.BindingUrlError: diff --git a/modules/base/base.go b/modules/base/base.go index 5536685a4f..145fae6f13 100644 --- a/modules/base/base.go +++ b/modules/base/base.go @@ -7,6 +7,11 @@ package base type ( // Type TmplData represents data in the templates. TmplData map[string]interface{} + + ApiJsonErr struct { + Message string `json:"message"` + DocUrl string `json:"documentation_url"` + } ) var GoGetMetas = make(map[string]bool) diff --git a/modules/base/markdown.go b/modules/base/markdown.go index 95b4b212fd..057e1b0477 100644 --- a/modules/base/markdown.go +++ b/modules/base/markdown.go @@ -132,9 +132,7 @@ func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte { return rawBytes } -func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte { - body := RenderSpecialLink(rawBytes, urlPrefix) - // fmt.Println(string(body)) +func RenderRawMarkdown(body []byte, urlPrefix string) []byte { htmlFlags := 0 // htmlFlags |= gfm.HTML_USE_XHTML // htmlFlags |= gfm.HTML_USE_SMARTYPANTS @@ -163,7 +161,12 @@ func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte { extensions |= gfm.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK body = gfm.Markdown(body, renderer, extensions) - // fmt.Println(string(body)) + return body +} + +func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte { + body := RenderSpecialLink(rawBytes, urlPrefix) + body = RenderRawMarkdown(body, urlPrefix) return body } diff --git a/modules/middleware/auth.go b/modules/middleware/auth.go index 39b7796d92..cd00d4679e 100644 --- a/modules/middleware/auth.go +++ b/modules/middleware/auth.go @@ -21,23 +21,21 @@ type ToggleOptions struct { func Toggle(options *ToggleOptions) martini.Handler { return func(ctx *Context) { + // Cannot view any page before installation. if !base.InstallLock { ctx.Redirect("/install") return } + // Redirect to dashboard if user tries to visit any non-login page. if options.SignOutRequire && ctx.IsSigned && ctx.Req.RequestURI != "/" { ctx.Redirect("/") return } - if !options.DisableCsrf { - if ctx.Req.Method == "POST" { - if !ctx.CsrfTokenValid() { - ctx.Error(403, "CSRF token does not match") - return - } - } + if !options.DisableCsrf && ctx.Req.Method == "POST" && !ctx.CsrfTokenValid() { + ctx.Error(403, "CSRF token does not match") + return } if options.SignInRequire { diff --git a/modules/middleware/context.go b/modules/middleware/context.go index 31fdca681a..e9084d330c 100644 --- a/modules/middleware/context.go +++ b/modules/middleware/context.go @@ -78,6 +78,19 @@ func (ctx *Context) Query(name string) string { // return ctx.p[name] // } +// HasError returns true if error occurs in form validation. +func (ctx *Context) HasApiError() bool { + hasErr, ok := ctx.Data["HasError"] + if !ok { + return false + } + return hasErr.(bool) +} + +func (ctx *Context) GetErrMsg() string { + return ctx.Data["ErrorMsg"].(string) +} + // HasError returns true if error occurs in form validation. func (ctx *Context) HasError() bool { hasErr, ok := ctx.Data["HasError"] diff --git a/public/js/app.js b/public/js/app.js index 59fffd36d0..59d4461350 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -62,6 +62,12 @@ var Gogits = { var method = $(this).data('ajax-method') || 'get'; var ajaxName = $(this).data('ajax-name'); var data = {}; + + if (ajaxName.endsWith("preview")) { + data["mode"] = "gfm"; + data["context"] = $(this).data('ajax-context'); + } + $('[data-ajax-rel=' + ajaxName + ']').each(function () { var field = $(this).data("ajax-field"); var t = $(this).data("ajax-val"); @@ -547,10 +553,8 @@ function initIssue() { (function () { $('[data-ajax-name=issue-preview]').on("click", function () { var $this = $(this); - $this.toggleAjax(function (json) { - if (json.ok) { - $($this.data("preview")).html(json.content); - } + $this.toggleAjax(function (resp) { + $($this.data("preview")).html(resp); }) }); $('.issue-write a[data-toggle]').on("click", function () { diff --git a/routers/api/v1/miscellaneous.go b/routers/api/v1/miscellaneous.go index babdfce9b2..30751efcca 100644 --- a/routers/api/v1/miscellaneous.go +++ b/routers/api/v1/miscellaneous.go @@ -5,14 +5,38 @@ package v1 import ( + "io/ioutil" + "strings" + + "github.com/gogits/gogs/modules/auth/apiv1" "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/middleware" ) -func Markdown(ctx *middleware.Context) { - content := ctx.Query("content") - ctx.Render.JSON(200, map[string]interface{}{ - "ok": true, - "content": string(base.RenderMarkdown([]byte(content), ctx.Query("repoLink"))), - }) +const DOC_URL = "http://gogs.io/docs" + +// Render an arbitrary Markdown document. +func Markdown(ctx *middleware.Context, form apiv1.MarkdownForm) { + if ctx.HasApiError() { + ctx.JSON(422, base.ApiJsonErr{ctx.GetErrMsg(), DOC_URL}) + return + } + + switch form.Mode { + case "gfm": + ctx.Write(base.RenderMarkdown([]byte(form.Text), + base.AppUrl+strings.TrimPrefix(form.Context, "/"))) + default: + ctx.Write(base.RenderRawMarkdown([]byte(form.Text), "")) + } +} + +// Render a Markdown document in raw mode. +func MarkdownRaw(ctx *middleware.Context) { + body, err := ioutil.ReadAll(ctx.Req.Body) + if err != nil { + ctx.JSON(422, base.ApiJsonErr{err.Error(), DOC_URL}) + return + } + ctx.Write(base.RenderRawMarkdown(body, "")) } diff --git a/routers/dashboard.go b/routers/dashboard.go index 71bdcc9f13..78533127fd 100644 --- a/routers/dashboard.go +++ b/routers/dashboard.go @@ -24,9 +24,19 @@ func Home(ctx *middleware.Context) { return } - repos, _ := models.GetRecentUpdatedRepositories() + // Show recent updated repositoires for new visiters. + repos, err := models.GetRecentUpdatedRepositories() + if err != nil { + ctx.Handle(500, "dashboard.Home(GetRecentUpdatedRepositories)", err) + return + } + for _, repo := range repos { - repo.Owner, _ = models.GetUserById(repo.OwnerId) + repo.Owner, err = models.GetUserById(repo.OwnerId) + if err != nil { + ctx.Handle(500, "dashboard.Home(GetUserById)", err) + return + } } ctx.Data["Repos"] = repos ctx.Data["PageIsHome"] = true diff --git a/routers/install.go b/routers/install.go index 38bf896f4e..53ce90d5b6 100644 --- a/routers/install.go +++ b/routers/install.go @@ -78,7 +78,7 @@ func Install(ctx *middleware.Context, form auth.InstallForm) { ctx.Data["Title"] = "Install" ctx.Data["PageIsInstall"] = true - // Get and assign value to install form. + // Get and assign values to install form. if len(form.Host) == 0 { form.Host = models.DbCfg.Host } @@ -109,11 +109,11 @@ func Install(ctx *middleware.Context, form auth.InstallForm) { } renderDbOption(ctx) - curDbValue := "" + curDbOp := "" if models.EnableSQLite3 { - curDbValue = "SQLite3" // Default when enabled. + curDbOp = "SQLite3" // Default when enabled. } - ctx.Data["CurDbValue"] = curDbValue + ctx.Data["CurDbOption"] = curDbOp auth.AssignForm(form, ctx.Data) ctx.HTML(200, "install") @@ -129,7 +129,7 @@ func InstallPost(ctx *middleware.Context, form auth.InstallForm) { ctx.Data["PageIsInstall"] = true renderDbOption(ctx) - ctx.Data["CurDbValue"] = form.Database + ctx.Data["CurDbOption"] = form.Database if ctx.HasError() { ctx.HTML(200, "install") @@ -157,7 +157,7 @@ func InstallPost(ctx *middleware.Context, form auth.InstallForm) { if err := models.NewTestEngine(x); err != nil { if strings.Contains(err.Error(), `Unknown database type: sqlite3`) { ctx.RenderWithErr("Your release version does not support SQLite3, please download the official binary version "+ - "from https://github.com/gogits/gogs/wiki/Install-from-binary, NOT the gobuild version.", "install", &form) + "from http://gogs.io/docs/installation/install_from_binary.md, NOT the gobuild version.", "install", &form) } else { ctx.RenderWithErr("Database setting is not correct: "+err.Error(), "install", &form) } diff --git a/templates/admin/nav.tmpl b/templates/admin/nav.tmpl index e22ae0b9f5..f27b8bb24b 100644 --- a/templates/admin/nav.tmpl +++ b/templates/admin/nav.tmpl @@ -4,6 +4,6 @@
  • Users
  • Repositories
  • Configuration
  • -
  • Authentication
  • +
  • Authentication
  • \ No newline at end of file diff --git a/templates/base/navbar.tmpl b/templates/base/navbar.tmpl index 80085d974a..29a2b75cc1 100644 --- a/templates/base/navbar.tmpl +++ b/templates/base/navbar.tmpl @@ -3,20 +3,25 @@ diff --git a/templates/home.tmpl b/templates/home.tmpl index b08d1c2451..8288d21e15 100644 --- a/templates/home.tmpl +++ b/templates/home.tmpl @@ -10,7 +10,7 @@
    Here are some recent updated repositories:
    {{end}} diff --git a/templates/install.tmpl b/templates/install.tmpl index eb6327d205..9ba610b62d 100644 --- a/templates/install.tmpl +++ b/templates/install.tmpl @@ -9,15 +9,15 @@
    -
    +
    @@ -27,7 +27,6 @@
    -
    @@ -35,7 +34,6 @@
    -
    @@ -43,14 +41,13 @@
    -

    Recommend use INNODB engine with utf8_general_ci charset.

    -
    +

    The file path of SQLite3 database.

    @@ -78,17 +74,14 @@

    General Settings of Gogs

    -
    -

    The git copy of each repository is saved in this directory.

    -

    The user has access to visit and run Gogs.

    @@ -97,7 +90,6 @@
    -

    This affects SSH clone URL.

    @@ -106,7 +98,6 @@
    -

    This affects HTTP/HTTPS clone URL and somewhere in e-mail.

    @@ -116,7 +107,7 @@

    Admin Account Settings

    -
    +
    @@ -152,31 +143,30 @@ {{template "base/footer" .}} diff --git a/templates/issue/create.tmpl b/templates/issue/create.tmpl index a75ee83617..f6a65cc846 100644 --- a/templates/issue/create.tmpl +++ b/templates/issue/create.tmpl @@ -20,12 +20,12 @@
    - +
    loading...
    diff --git a/templates/issue/view.tmpl b/templates/issue/view.tmpl index 90c9361241..19dce4f2df 100644 --- a/templates/issue/view.tmpl +++ b/templates/issue/view.tmpl @@ -72,13 +72,13 @@
    - +
    Loading...
    diff --git a/templates/repo/hooks_add.tmpl b/templates/repo/hooks_add.tmpl index fb1c37d8a8..3a377fda69 100644 --- a/templates/repo/hooks_add.tmpl +++ b/templates/repo/hooks_add.tmpl @@ -6,56 +6,55 @@ {{template "repo/setting_nav" .}}
    {{template "base/alert" .}} -
    -
    - Add Webhook -
    -
    -

    We’ll send a POST request to the URL below with details of any subscribed events.

    -
    -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    -
    - -
    + +
    +
    + Add Webhook +
    + +
    +
    +

    We’ll send a POST request to the URL below with details of any subscribed events.

    +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    +
    + +
    + +
    +
    +
    +
    +

    We will deliver event details when this hook is triggered.

    -
    -
    - -

    We will deliver event details when this hook is triggered.

    -
    -
    -
    - -
    - -
    - -
    +
    + +
    +
    {{template "base/footer" .}} \ No newline at end of file diff --git a/templates/repo/hooks_edit.tmpl b/templates/repo/hooks_edit.tmpl index b017197c10..718336ec3a 100644 --- a/templates/repo/hooks_edit.tmpl +++ b/templates/repo/hooks_edit.tmpl @@ -11,6 +11,7 @@
    Manage Webhook
    +

    We’ll send a POST request to the URL below with details of any subscribed events.

    @@ -51,6 +52,7 @@
    +