From 076fc98d981aea3533eea363ca1c7e43f77b9802 Mon Sep 17 00:00:00 2001 From: slene Date: Sun, 23 Mar 2014 01:44:02 +0800 Subject: add csrf check --- modules/middleware/auth.go | 58 +++++++++++++++++++++++++--------------------- 1 file changed, 32 insertions(+), 26 deletions(-) (limited to 'modules/middleware/auth.go') diff --git a/modules/middleware/auth.go b/modules/middleware/auth.go index f211de32..b557188e 100644 --- a/modules/middleware/auth.go +++ b/modules/middleware/auth.go @@ -10,39 +10,45 @@ import ( "github.com/gogits/gogs/modules/base" ) -// SignInRequire requires user to sign in. -func SignInRequire(redirect bool) martini.Handler { - return func(ctx *Context) { - if !ctx.IsSigned { - if redirect { - ctx.Redirect("/user/login") - } - return - } else if !ctx.User.IsActive && base.Service.RegisterEmailConfirm { - ctx.Data["Title"] = "Activate Your Account" - ctx.HTML(200, "user/active") - return - } - } +type ToggleOptions struct { + SignInRequire bool + SignOutRequire bool + AdminRequire bool + DisableCsrf bool } -// SignOutRequire requires user to sign out. -func SignOutRequire() martini.Handler { +func Toggle(options *ToggleOptions) martini.Handler { return func(ctx *Context) { - if ctx.IsSigned { + if options.SignOutRequire && ctx.IsSigned { ctx.Redirect("/") return } - } -} -// AdminRequire requires user signed in as administor. -func AdminRequire() martini.Handler { - return func(ctx *Context) { - if !ctx.User.IsAdmin { - ctx.Error(403) - return + if !options.DisableCsrf { + if ctx.Req.Method == "POST" { + if !ctx.CsrfTokenValid() { + ctx.Error(403, "CSRF token does not match") + return + } + } + } + + if options.SignInRequire { + if !ctx.IsSigned { + ctx.Redirect("/user/login") + return + } else if !ctx.User.IsActive && base.Service.RegisterEmailConfirm { + ctx.Data["Title"] = "Activate Your Account" + ctx.HTML(200, "user/active") + return + } + } + + if options.AdminRequire { + if !ctx.User.IsAdmin { + ctx.Error(403) + return + } } - ctx.Data["PageIsAdmin"] = true } } -- cgit v1.2.3 From b3cfd9fe0c293ba9d84d38ec140db2c01b1e3109 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sat, 22 Mar 2014 14:27:03 -0400 Subject: Fix SSH key bug in windows --- models/publickey.go | 45 ++++++++++++++++++++++++++----------------- models/repo.go | 2 +- models/user.go | 2 +- modules/middleware/auth.go | 1 + modules/middleware/context.go | 4 ---- routers/repo/issue.go | 10 ++++++++++ 6 files changed, 40 insertions(+), 24 deletions(-) (limited to 'modules/middleware/auth.go') diff --git a/models/publickey.go b/models/publickey.go index c69bca68..9e7cc6f7 100644 --- a/models/publickey.go +++ b/models/publickey.go @@ -19,6 +19,8 @@ import ( "time" "github.com/Unknwon/com" + + "github.com/gogits/gogs/modules/log" ) const ( @@ -99,8 +101,8 @@ func AddPublicKey(key *PublicKey) (err error) { } // Calculate fingerprint. - tmpPath := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()), - "id_rsa.pub") + tmpPath := strings.Replace(filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()), + "id_rsa.pub"), "\\", "/", -1) os.MkdirAll(path.Dir(tmpPath), os.ModePerm) if err = ioutil.WriteFile(tmpPath, []byte(key.Content), os.ModePerm); err != nil { return err @@ -127,25 +129,11 @@ func AddPublicKey(key *PublicKey) (err error) { return nil } -// DeletePublicKey deletes SSH key information both in database and authorized_keys file. -func DeletePublicKey(key *PublicKey) (err error) { - // Delete SSH key in database. - has, err := orm.Id(key.Id).Get(key) - if err != nil { - return err - } else if !has { - return errors.New("Public key does not exist") - } - if _, err = orm.Delete(key); err != nil { - return err - } - +func rewriteAuthorizedKeys(key *PublicKey, p, tmpP string) error { // Delete SSH key in SSH key file. sshOpLocker.Lock() defer sshOpLocker.Unlock() - p := filepath.Join(sshPath, "authorized_keys") - tmpP := filepath.Join(sshPath, "authorized_keys.tmp") fr, err := os.Open(p) if err != nil { return err @@ -188,8 +176,29 @@ func DeletePublicKey(key *PublicKey) (err error) { break } } + return nil +} - if err = os.Remove(p); err != nil { +// DeletePublicKey deletes SSH key information both in database and authorized_keys file. +func DeletePublicKey(key *PublicKey) (err error) { + // Delete SSH key in database. + has, err := orm.Id(key.Id).Get(key) + if err != nil { + return err + } else if !has { + return errors.New("Public key does not exist") + } + if _, err = orm.Delete(key); err != nil { + return err + } + + p := filepath.Join(sshPath, "authorized_keys") + tmpP := filepath.Join(sshPath, "authorized_keys.tmp") + log.Trace("ssh.DeletePublicKey(authorized_keys): %s", p) + + if err = rewriteAuthorizedKeys(key, p, tmpP); err != nil { + return err + } else if err = os.Remove(p); err != nil { return err } return os.Rename(tmpP, p) diff --git a/models/repo.go b/models/repo.go index fb115de5..317f936e 100644 --- a/models/repo.go +++ b/models/repo.go @@ -372,7 +372,7 @@ func RepoPath(userName, repoName string) string { } func UpdateRepository(repo *Repository) error { - _, err := orm.Id(repo.Id).UseBool().Update(repo) + _, err := orm.Id(repo.Id).UseBool().Cols("description", "website").Update(repo) return err } diff --git a/models/user.go b/models/user.go index d6dc0414..88c29ae4 100644 --- a/models/user.go +++ b/models/user.go @@ -201,7 +201,7 @@ func VerifyUserActiveCode(code string) (user *User) { // UpdateUser updates user's information. func UpdateUser(user *User) (err error) { - _, err = orm.Id(user.Id).UseBool().Update(user) + _, err = orm.Id(user.Id).UseBool().Cols("website", "location").Update(user) return err } diff --git a/modules/middleware/auth.go b/modules/middleware/auth.go index b557188e..3224b3df 100644 --- a/modules/middleware/auth.go +++ b/modules/middleware/auth.go @@ -49,6 +49,7 @@ func Toggle(options *ToggleOptions) martini.Handler { ctx.Error(403) return } + ctx.Data["PageIsAdmin"] = true } } } diff --git a/modules/middleware/context.go b/modules/middleware/context.go index b28953fc..5727b4f0 100644 --- a/modules/middleware/context.go +++ b/modules/middleware/context.go @@ -216,10 +216,6 @@ func InitContext() martini.Handler { ctx.Data["SignedUserId"] = user.Id ctx.Data["SignedUserName"] = user.LowerName ctx.Data["IsAdmin"] = ctx.User.IsAdmin - - if ctx.User.IsAdmin { - ctx.Data["PageIsAdmin"] = true - } } // get or create csrf token diff --git a/routers/repo/issue.go b/routers/repo/issue.go index c6af8ca0..eee55c6f 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -28,3 +28,13 @@ func Issues(ctx *middleware.Context, params martini.Params) { ctx.HTML(200, "repo/issues") } + +func CreateIssue(ctx *middleware.Context, params martini.Params) { + if !ctx.Repo.IsOwner { + ctx.Error(404) + return + } + // else if err = models.CreateIssue(userId, repoId, milestoneId, assigneeId, name, labels, mentions, content, isPull); err != nil { + + // } +} -- cgit v1.2.3 From 7356153ba3c19ff49f3ecfa28bac0b8bb38eccb9 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sat, 22 Mar 2014 17:59:22 -0400 Subject: Batch updates --- README.md | 4 ++-- conf/app.ini | 10 ++++++++-- modules/base/conf.go | 4 ++++ modules/middleware/auth.go | 3 +++ routers/admin/user.go | 2 +- routers/repo/issue.go | 2 +- routers/repo/repo.go | 8 ++++---- routers/user/user.go | 21 ++++++++++++++++++--- 8 files changed, 41 insertions(+), 13 deletions(-) (limited to 'modules/middleware/auth.go') diff --git a/README.md b/README.md index 89a346d6..325c3a97 100644 --- a/README.md +++ b/README.md @@ -43,8 +43,8 @@ There are two ways to install Gogs: ## Acknowledgments - Logo is inspired by [martini](https://github.com/martini-contrib). -- Mail Service is based on [WeTalk](https://github.com/beego/wetalk). -- System Monitor Status is based on [GoBlog](https://github.com/fuxiaohei/goblog). +- Mail Service, modules design is inspired by [WeTalk](https://github.com/beego/wetalk). +- System Monitor Status is inspired by [GoBlog](https://github.com/fuxiaohei/goblog). ## Contributors diff --git a/conf/app.ini b/conf/app.ini index 7f283012..b051557f 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -107,7 +107,7 @@ SERVICE = server PATH = data/pictures [log] -; Either "console", "file", "conn" or "smtp", default is "console" +; Either "console", "file", "conn", "smtp" or "database", default is "console" MODE = console ; Buffer length of channel, keep it as it is if you don't know what it is. BUFFER_LEN = 10000 @@ -156,4 +156,10 @@ HOST = USER = PASSWD = ; Receivers, can be one or more, e.g. ["1@example.com","2@example.com"] -RECEIVERS = \ No newline at end of file +RECEIVERS = + +; For "database" mode only +[log.database] +LEVEL = +Driver = +CONN = \ No newline at end of file diff --git a/modules/base/conf.go b/modules/base/conf.go index cdbe2b36..19f58707 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -143,6 +143,10 @@ func newLogService() { Cfg.MustValue(modeSec, "HOST", "127.0.0.1:25"), Cfg.MustValue(modeSec, "RECEIVERS", "[]"), Cfg.MustValue(modeSec, "SUBJECT", "Diagnostic message from serve")) + case "database": + LogConfig = fmt.Sprintf(`{"level":%s,"driver":%s,"conn":%s}`, level, + Cfg.MustValue(modeSec, "Driver"), + Cfg.MustValue(modeSec, "CONN")) } log.NewLogger(Cfg.MustInt64("log", "BUFFER_LEN", 10000), LogMode, LogConfig) diff --git a/modules/middleware/auth.go b/modules/middleware/auth.go index 3224b3df..82c3367c 100644 --- a/modules/middleware/auth.go +++ b/modules/middleware/auth.go @@ -5,6 +5,8 @@ package middleware import ( + "net/url" + "github.com/codegangsta/martini" "github.com/gogits/gogs/modules/base" @@ -35,6 +37,7 @@ func Toggle(options *ToggleOptions) martini.Handler { if options.SignInRequire { if !ctx.IsSigned { + ctx.SetCookie("redirect_to", "/"+url.QueryEscape(ctx.Req.RequestURI)) ctx.Redirect("/user/login") return } else if !ctx.User.IsActive && base.Service.RegisterEmailConfirm { diff --git a/routers/admin/user.go b/routers/admin/user.go index fa27d116..7f66c552 100644 --- a/routers/admin/user.go +++ b/routers/admin/user.go @@ -140,5 +140,5 @@ func DeleteUser(ctx *middleware.Context, params martini.Params) { log.Trace("%s User deleted by admin(%s): %s", ctx.Req.RequestURI, ctx.User.LowerName, ctx.User.LowerName) - ctx.Redirect("/admin/users", 302) + ctx.Redirect("/admin/users") } diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 154e8308..4cc007e9 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -56,7 +56,7 @@ func CreateIssue(ctx *middleware.Context, params martini.Params, form auth.Creat form.IssueName, form.Labels, form.Content, false) if err == nil { log.Trace("%s Issue created: %d", form.RepoId, issue.Id) - ctx.Redirect(fmt.Sprintf("/%s/%s/issues/%d", params["username"], params["reponame"], issue.Index), 302) + ctx.Redirect(fmt.Sprintf("/%s/%s/issues/%d", params["username"], params["reponame"], issue.Index)) return } ctx.Handle(200, "issue.CreateIssue", err) diff --git a/routers/repo/repo.go b/routers/repo/repo.go index c436d387..4782d64f 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -40,7 +40,7 @@ func Create(ctx *middleware.Context, form auth.CreateRepoForm) { form.Language, form.License, form.Visibility == "private", form.InitReadme == "on") if err == nil { log.Trace("%s Repository created: %s/%s", ctx.Req.RequestURI, ctx.User.LowerName, form.RepoName) - ctx.Redirect("/"+ctx.User.Name+"/"+form.RepoName, 302) + ctx.Redirect("/" + ctx.User.Name + "/" + form.RepoName) return } else if err == models.ErrRepoAlreadyExist { ctx.RenderWithErr("Repository name has already been used", "repo/create", &form) @@ -73,7 +73,7 @@ func SettingPost(ctx *middleware.Context) { } log.Trace("%s Repository deleted: %s/%s", ctx.Req.RequestURI, ctx.User.LowerName, ctx.Repo.Repository.LowerName) - ctx.Redirect("/", 302) + ctx.Redirect("/") } func Branches(ctx *middleware.Context, params martini.Params) { @@ -113,8 +113,8 @@ func Single(ctx *middleware.Context, params martini.Params) { treename := params["_1"] if len(treename) > 0 && treename[len(treename)-1] == '/' { - ctx.Redirect("/"+ctx.Repo.Owner.LowerName+"/"+ - ctx.Repo.Repository.Name+"/src/"+params["branchname"]+"/"+treename[:len(treename)-1], 302) + ctx.Redirect("/" + ctx.Repo.Owner.LowerName + "/" + + ctx.Repo.Repository.Name + "/src/" + params["branchname"] + "/" + treename[:len(treename)-1]) return } diff --git a/routers/user/user.go b/routers/user/user.go index 56bc5f8e..c34b529e 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -6,6 +6,7 @@ package user import ( "fmt" + "net/url" "strings" "github.com/codegangsta/martini" @@ -109,7 +110,13 @@ func SignIn(ctx *middleware.Context, form auth.LogInForm) { isSucceed = true ctx.Session.Set("userId", user.Id) ctx.Session.Set("userName", user.Name) - ctx.Redirect("/") + redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")) + if len(redirectTo) > 0 { + ctx.SetCookie("redirect_to", "", -1) + ctx.Redirect(redirectTo) + } else { + ctx.Redirect("/") + } return } @@ -139,12 +146,20 @@ func SignIn(ctx *middleware.Context, form auth.LogInForm) { ctx.Session.Set("userId", user.Id) ctx.Session.Set("userName", user.Name) - ctx.Redirect("/") + redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")) + if len(redirectTo) > 0 { + ctx.SetCookie("redirect_to", "", -1) + ctx.Redirect(redirectTo) + } else { + ctx.Redirect("/") + } } func SignOut(ctx *middleware.Context) { ctx.Session.Delete("userId") ctx.Session.Delete("userName") + ctx.SetCookie(base.CookieUserName, "", -1) + ctx.SetCookie(base.CookieRememberName, "", -1) ctx.Redirect("/") } @@ -314,7 +329,7 @@ func Activate(ctx *middleware.Context) { ctx.Session.Set("userId", user.Id) ctx.Session.Set("userName", user.Name) - ctx.Redirect("/", 302) + ctx.Redirect("/") return } -- cgit v1.2.3