From 932f717adb1cb1738415fcddaf5eb3c0e4a60fc2 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sat, 22 Mar 2014 04:44:57 -0400 Subject: [PATCH 01/19] Fixing bug --- models/action.go | 10 ++++++++++ models/repo.go | 9 +++++++-- models/user.go | 4 +--- modules/middleware/repo.go | 2 +- serve.go | 2 +- 5 files changed, 20 insertions(+), 7 deletions(-) diff --git a/models/action.go b/models/action.go index 107d4b105..89751b977 100644 --- a/models/action.go +++ b/models/action.go @@ -79,6 +79,16 @@ func CommitRepoAction(userId int64, userName string, }) return err } + + // Update repository last update time. + repo, err := GetRepositoryByName(userId, repoName) + if err != nil { + return err + } + repo.Updated = time.Now() + if err = UpdateRepository(repo); err != nil { + return err + } return nil } diff --git a/models/repo.go b/models/repo.go index 918e5dc84..6a764e6c3 100644 --- a/models/repo.go +++ b/models/repo.go @@ -358,6 +358,11 @@ func RepoPath(userName, repoName string) string { return filepath.Join(UserPath(userName), repoName+".git") } +func UpdateRepository(repo *Repository) error { + _, err := orm.Id(repo.Id).UseBool().Update(repo) + return err +} + // DeleteRepository deletes a repository for a user or orgnaztion. func DeleteRepository(userId, repoId int64, userName string) (err error) { repo := &Repository{Id: repoId, OwnerId: userId} @@ -402,9 +407,9 @@ func DeleteRepository(userId, repoId int64, userName string) (err error) { } // GetRepositoryByName returns the repository by given name under user if exists. -func GetRepositoryByName(user *User, repoName string) (*Repository, error) { +func GetRepositoryByName(userId int64, repoName string) (*Repository, error) { repo := &Repository{ - OwnerId: user.Id, + OwnerId: userId, LowerName: strings.ToLower(repoName), } has, err := orm.Get(repo) diff --git a/models/user.go b/models/user.go index 3c1109128..d6dc04149 100644 --- a/models/user.go +++ b/models/user.go @@ -279,9 +279,7 @@ func GetUserByName(name string) (*User, error) { if len(name) == 0 { return nil, ErrUserNotExist } - user := &User{ - LowerName: strings.ToLower(name), - } + user := &User{LowerName: strings.ToLower(name)} has, err := orm.Get(user) if err != nil { return nil, err diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index a9a90e3ff..3864caaf8 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -54,7 +54,7 @@ func RepoAssignment(redirect bool) martini.Handler { ctx.Repo.Owner = user // get repository - repo, err := models.GetRepositoryByName(user, params["reponame"]) + repo, err := models.GetRepositoryByName(user.Id, params["reponame"]) if err != nil { if redirect { ctx.Redirect("/") diff --git a/serve.go b/serve.go index 3ce8f9046..be8dedc98 100644 --- a/serve.go +++ b/serve.go @@ -86,7 +86,7 @@ func runServ(*cli.Context) { os.Setenv("userName", user.Name) os.Setenv("userId", strconv.Itoa(int(user.Id))) - repo, err := models.GetRepositoryByName(user, repoName) + repo, err := models.GetRepositoryByName(user.Id, repoName) if err != nil { println("Unavilable repository", err) return From 76cd448e7925997b60a54e8d9431ffd0826cc24e Mon Sep 17 00:00:00 2001 From: Unknown Date: Sat, 22 Mar 2014 06:20:00 -0400 Subject: [PATCH 02/19] Add admin delete user --- gogs.go | 2 +- models/action.go | 6 ++++++ routers/admin/user.go | 35 +++++++++++++++++++++++++++++++++ templates/admin/users/edit.tmpl | 2 +- web.go | 1 + 5 files changed, 44 insertions(+), 2 deletions(-) diff --git a/gogs.go b/gogs.go index 41df79280..8ec4fd42f 100644 --- a/gogs.go +++ b/gogs.go @@ -20,7 +20,7 @@ import ( // Test that go1.2 tag above is included in builds. main.go refers to this definition. const go12tag = true -const APP_VER = "0.1.5.0321" +const APP_VER = "0.1.5.0322" func init() { base.AppVer = APP_VER diff --git a/models/action.go b/models/action.go index 89751b977..12122ae24 100644 --- a/models/action.go +++ b/models/action.go @@ -7,6 +7,8 @@ package models import ( "encoding/json" "time" + + "github.com/gogits/gogs/modules/log" ) // Operation types of user action. @@ -89,6 +91,8 @@ func CommitRepoAction(userId int64, userName string, if err = UpdateRepository(repo); err != nil { return err } + + log.Trace("action.CommitRepoAction: %d/%s", userId, repo.LowerName) return nil } @@ -102,6 +106,8 @@ func NewRepoAction(user *User, repo *Repository) error { RepoId: repo.Id, RepoName: repo.Name, }) + + log.Trace("action.NewRepoAction: %s/%s", user.LowerName, repo.LowerName) return err } diff --git a/routers/admin/user.go b/routers/admin/user.go index d6f852321..fa27d1166 100644 --- a/routers/admin/user.go +++ b/routers/admin/user.go @@ -107,3 +107,38 @@ func EditUser(ctx *middleware.Context, params martini.Params, form auth.AdminEdi log.Trace("%s User profile updated by admin(%s): %s", ctx.Req.RequestURI, ctx.User.LowerName, ctx.User.LowerName) } + +func DeleteUser(ctx *middleware.Context, params martini.Params) { + ctx.Data["Title"] = "Edit Account" + ctx.Data["PageIsUsers"] = true + + uid, err := base.StrTo(params["userid"]).Int() + if err != nil { + ctx.Handle(200, "admin.user.EditUser", err) + return + } + + u, err := models.GetUserById(int64(uid)) + if err != nil { + ctx.Handle(200, "admin.user.EditUser", err) + return + } + + if err = models.DeleteUser(u); err != nil { + ctx.Data["HasError"] = true + switch err { + case models.ErrUserOwnRepos: + ctx.Data["ErrorMsg"] = "This account still has ownership of repository, owner has to delete or transfer them first." + ctx.Data["User"] = u + ctx.HTML(200, "admin/users/edit") + default: + ctx.Handle(200, "admin.user.DeleteUser", err) + } + return + } + + log.Trace("%s User deleted by admin(%s): %s", ctx.Req.RequestURI, + ctx.User.LowerName, ctx.User.LowerName) + + ctx.Redirect("/admin/users", 302) +} diff --git a/templates/admin/users/edit.tmpl b/templates/admin/users/edit.tmpl index 415bcedc9..2a9882423 100644 --- a/templates/admin/users/edit.tmpl +++ b/templates/admin/users/edit.tmpl @@ -71,7 +71,7 @@
- + Delete this account
diff --git a/web.go b/web.go index bb316a672..595b8f74e 100644 --- a/web.go +++ b/web.go @@ -119,6 +119,7 @@ func runWeb(*cli.Context) { m.Get("/admin/users", reqSignIn, adminReq, admin.Users) m.Any("/admin/users/new", reqSignIn, adminReq, binding.BindIgnErr(auth.RegisterForm{}), admin.NewUser) m.Any("/admin/users/:userid", reqSignIn, adminReq, binding.BindIgnErr(auth.AdminEditUserForm{}), admin.EditUser) + m.Any("/admin/users/:userid/delete", reqSignIn, adminReq, admin.DeleteUser) m.Get("/admin/repos", reqSignIn, adminReq, admin.Repositories) m.Get("/admin/config", reqSignIn, adminReq, admin.Config) From 7a1ff8636c01844a501dd9cdca2c436d1b7826b7 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sat, 22 Mar 2014 06:42:19 -0400 Subject: [PATCH 03/19] Add config option: Picture cache path --- conf/app.ini | 8 ++++++++ modules/base/conf.go | 8 ++++++++ routers/admin/admin.go | 3 +++ templates/admin/config.tmpl | 12 ++++++++++++ 4 files changed, 31 insertions(+) diff --git a/conf/app.ini b/conf/app.ini index ecb0d2511..cf99c9da0 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -44,6 +44,8 @@ REGISTER_EMAIL_CONFIRM = false DISENABLE_REGISTERATION = false ; User must sign in to view anything. REQUIRE_SIGNIN_VIEW = false +; Cache avatar as picture +ENABLE_CACHE_AVATAR = false [mailer] ENABLED = false @@ -70,6 +72,12 @@ INTERVAL = 60 ; memcache: "127.0.0.1:11211" HOST = +[picture] +; The place to picture data, either "server" or "qiniu", default is "server" +SERVICE = server +; For "server" only, root path of picture data, default is "data/pictures" +PATH = data/pictures + [log] ; Either "console", "file", "conn" or "smtp", default is "console" MODE = console diff --git a/modules/base/conf.go b/modules/base/conf.go index 863daca64..8c6ee6281 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -44,6 +44,9 @@ var ( CacheAdapter string CacheConfig string + PictureService string + PictureRootPath string + LogMode string LogConfig string ) @@ -52,6 +55,7 @@ var Service struct { RegisterEmailConfirm bool DisenableRegisteration bool RequireSignInView bool + EnableCacheAvatar bool ActiveCodeLives int ResetPwdCodeLives int } @@ -82,6 +86,7 @@ func newService() { Service.ResetPwdCodeLives = Cfg.MustInt("service", "RESET_PASSWD_CODE_LIVE_MINUTES", 180) Service.DisenableRegisteration = Cfg.MustBool("service", "DISENABLE_REGISTERATION", false) Service.RequireSignInView = Cfg.MustBool("service", "REQUIRE_SIGNIN_VIEW", false) + Service.EnableCacheAvatar = Cfg.MustBool("service", "ENABLE_CACHE_AVATAR", false) } func newLogService() { @@ -214,6 +219,9 @@ func NewConfigContext() { SecretKey = Cfg.MustValue("security", "SECRET_KEY") RunUser = Cfg.MustValue("", "RUN_USER") + PictureService = Cfg.MustValue("picture", "SERVICE") + PictureRootPath = Cfg.MustValue("picture", "PATH") + // Determine and create root git reposiroty path. RepoRootPath = Cfg.MustValue("repository", "ROOT") if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil { diff --git a/routers/admin/admin.go b/routers/admin/admin.go index 2e19b99c1..25ed8981e 100644 --- a/routers/admin/admin.go +++ b/routers/admin/admin.go @@ -70,6 +70,9 @@ func Config(ctx *middleware.Context) { ctx.Data["CacheAdapter"] = base.CacheAdapter ctx.Data["CacheConfig"] = base.CacheConfig + ctx.Data["PictureService"] = base.PictureService + ctx.Data["PictureRootPath"] = base.PictureRootPath + ctx.Data["LogMode"] = base.LogMode ctx.Data["LogConfig"] = base.LogConfig diff --git a/templates/admin/config.tmpl b/templates/admin/config.tmpl index 6906f2409..e3f69ee6e 100644 --- a/templates/admin/config.tmpl +++ b/templates/admin/config.tmpl @@ -45,6 +45,7 @@
Register Email Confirmation:
Disenable Registeration:
Require Sign In View:
+
Enable Cache Avatar:

Active Code Lives: {{.Service.ActiveCodeLives}} minutes
Reset Password Code Lives: {{.Service.ResetPwdCodeLives}} minutes
@@ -76,6 +77,17 @@ +
+
+ Picture Configuration +
+ +
+
Picture Service: {{.PictureService}}
+
Picture Root Path: {{.PictureRootPath}}
+
+
+
Log Configuration From 0d1872ebe3f11c14f31f454ed8d719a22c0884d0 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sat, 22 Mar 2014 07:42:24 -0400 Subject: [PATCH 04/19] Add admin memStatus panel --- README.md | 3 +- routers/admin/admin.go | 81 ++++++++++++++++++++++++++++++++++ templates/admin/dashboard.tmpl | 33 +++++++++++++- 3 files changed, 115 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index cbd1f588d..a9ab7fe49 100644 --- a/README.md +++ b/README.md @@ -42,8 +42,9 @@ There are two ways to install Gogs: ## Acknowledgments -- Mail service is based on [WeTalk](https://github.com/beego/wetalk). - 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). ## Contributors diff --git a/routers/admin/admin.go b/routers/admin/admin.go index 25ed8981e..57a46d1df 100644 --- a/routers/admin/admin.go +++ b/routers/admin/admin.go @@ -5,7 +5,10 @@ package admin import ( + "fmt" + "runtime" "strings" + "time" "github.com/codegangsta/martini" @@ -14,10 +17,88 @@ import ( "github.com/gogits/gogs/modules/middleware" ) +var sysStatus struct { + NumGoroutine int + + // General statistics. + MemAllocated string // bytes allocated and still in use + MemTotal string // bytes allocated (even if freed) + MemSys string // bytes obtained from system (sum of XxxSys below) + Lookups uint64 // number of pointer lookups + MemMallocs uint64 // number of mallocs + MemFrees uint64 // number of frees + + // Main allocation heap statistics. + HeapAlloc string // bytes allocated and still in use + HeapSys string // bytes obtained from system + HeapIdle string // bytes in idle spans + HeapInuse string // bytes in non-idle span + HeapReleased string // bytes released to the OS + HeapObjects uint64 // total number of allocated objects + + // Low-level fixed-size structure allocator statistics. + // Inuse is bytes used now. + // Sys is bytes obtained from system. + StackInuse string // bootstrap stacks + StackSys string + MSpanInuse string // mspan structures + MSpanSys string + MCacheInuse string // mcache structures + MCacheSys string + BuckHashSys string // profiling bucket hash table + GCSys string // GC metadata + OtherSys string // other system allocations + + // Garbage collector statistics. + NextGC string // next run in HeapAlloc time (bytes) + LastGC string // last run in absolute time (ns) + PauseTotalNs string + PauseNs string // circular buffer of recent GC pause times, most recent at [(NumGC+255)%256] + NumGC uint32 +} + +func updateSystemStatus() { + m := new(runtime.MemStats) + runtime.ReadMemStats(m) + sysStatus.NumGoroutine = runtime.NumGoroutine() + + sysStatus.MemAllocated = base.FileSize(int64(m.Alloc)) + sysStatus.MemTotal = base.FileSize(int64(m.TotalAlloc)) + sysStatus.MemSys = base.FileSize(int64(m.Sys)) + sysStatus.Lookups = m.Lookups + sysStatus.MemMallocs = m.Mallocs + sysStatus.MemFrees = m.Frees + + sysStatus.HeapAlloc = base.FileSize(int64(m.HeapAlloc)) + sysStatus.HeapSys = base.FileSize(int64(m.HeapSys)) + sysStatus.HeapIdle = base.FileSize(int64(m.HeapIdle)) + sysStatus.HeapInuse = base.FileSize(int64(m.HeapInuse)) + sysStatus.HeapReleased = base.FileSize(int64(m.HeapReleased)) + sysStatus.HeapObjects = m.HeapObjects + + sysStatus.StackInuse = base.FileSize(int64(m.StackInuse)) + sysStatus.StackSys = base.FileSize(int64(m.StackSys)) + sysStatus.MSpanInuse = base.FileSize(int64(m.MSpanInuse)) + sysStatus.MSpanSys = base.FileSize(int64(m.MSpanSys)) + sysStatus.MCacheInuse = base.FileSize(int64(m.MCacheInuse)) + sysStatus.MCacheSys = base.FileSize(int64(m.MCacheSys)) + sysStatus.BuckHashSys = base.FileSize(int64(m.BuckHashSys)) + sysStatus.GCSys = base.FileSize(int64(m.GCSys)) + sysStatus.OtherSys = base.FileSize(int64(m.OtherSys)) + + sysStatus.NextGC = base.FileSize(int64(m.NextGC)) + sysStatus.LastGC = fmt.Sprintf("%.1fs", float64(time.Now().UnixNano()-int64(m.LastGC))/1000/1000/1000) + sysStatus.PauseTotalNs = fmt.Sprintf("%.1fs", float64(m.PauseTotalNs/1000/1000/1000)) + sysStatus.PauseNs = fmt.Sprintf("%.3fs", float64(m.PauseNs[(m.NumGC+255)%256]/1000/1000/1000)) + sysStatus.NumGC = m.NumGC +} + func Dashboard(ctx *middleware.Context) { ctx.Data["Title"] = "Admin Dashboard" ctx.Data["PageIsDashboard"] = true ctx.Data["Stats"] = models.GetStatistic() + updateSystemStatus() + ctx.Data["SysStatus"] = sysStatus ctx.HTML(200, "admin/dashboard") } diff --git a/templates/admin/dashboard.tmpl b/templates/admin/dashboard.tmpl index 6088487d6..0bebf8318 100644 --- a/templates/admin/dashboard.tmpl +++ b/templates/admin/dashboard.tmpl @@ -15,10 +15,41 @@
- System Status + System Monitor Status
+
Current Goroutines: {{.SysStatus.NumGoroutine}}
+
+
Current Memory Usage: {{.SysStatus.MemAllocated}}
+
Total Memory Allocated: {{.SysStatus.MemTotal}}
+
Memory Obtained: {{.SysStatus.MemSys}}
+
Pointer Lookup Times: {{.SysStatus.Lookups}}
+
Memory Allocate Times: {{.SysStatus.MemMallocs}}
+
Memory Free Times: {{.SysStatus.MemFrees}}
+
+
Current Heap Usage: {{.SysStatus.HeapAlloc}}
+
Heap Memory Obtained: {{.SysStatus.HeapSys}}
+
Heap Memory Idle: {{.SysStatus.HeapIdle}}
+
Heap Memory In Use: {{.SysStatus.HeapInuse}}
+
Heap Memory Released: {{.SysStatus.HeapReleased}}
+
Heap Objects: {{.SysStatus.HeapObjects}}
+
+
Bootstrap Stack Usage: {{.SysStatus.StackInuse}}
+
Stack Memory Obtained: {{.SysStatus.StackSys}}
+
MSpan Structures Usage: {{.SysStatus.MSpanInuse}}
+
MSpan Structures Obtained: {{.SysStatus.HeapSys}}
+
MCache Structures Usage: {{.SysStatus.MCacheInuse}}
+
MCache Structures Obtained: {{.SysStatus.MCacheSys}}
+
Profiling Bucket Hash Table Obtained: {{.SysStatus.BuckHashSys}}
+
GC Metadada Obtained: {{.SysStatus.GCSys}}
+
Other System Allocation Obtained: {{.SysStatus.OtherSys}}
+
+
Next GC Recycle: {{.SysStatus.NextGC}}
+
Last GC Time: {{.SysStatus.LastGC}} ago
+
Total GC Pause: {{.SysStatus.PauseTotalNs}}
+
Last GC Pause: {{.SysStatus.PauseNs}}
+
GC Times: {{.SysStatus.NumGC}}
From f9c07c4186b61a1548d9a908fe6228bd130f4f92 Mon Sep 17 00:00:00 2001 From: slene Date: Sat, 22 Mar 2014 20:49:53 +0800 Subject: [PATCH 05/19] update session --- .gitignore | 1 + conf/app.ini | 27 +++++++++++++++++++++++++++ modules/auth/user.go | 11 ++++++----- modules/base/conf.go | 30 ++++++++++++++++++++++++++++++ modules/middleware/context.go | 24 ++++++++++++++---------- routers/user/user.go | 2 +- web.go | 5 ----- 7 files changed, 79 insertions(+), 21 deletions(-) diff --git a/.gitignore b/.gitignore index ad27cc8be..d201223ef 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ gogs *.db *.log custom/ +data/ .vendor/ .idea/ *.iml \ No newline at end of file diff --git a/conf/app.ini b/conf/app.ini index cf99c9da0..cf2ae31d8 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -72,6 +72,33 @@ INTERVAL = 60 ; memcache: "127.0.0.1:11211" HOST = +[session] +; Either "memory", "file", "redis" or "mysql", default is "memory" +PROVIDER = file +; provider config +; memory: not have any config yet +; file: session file path +; e.g. tmp/sessions +; redis: config like redis server addr,poolSize,password +; e.g. 127.0.0.1:6379,100,astaxie +; mysql: go-sql-driver/mysql dsn config string +; e.g. root:password@/session_table +PROVIDER_CONFIG = data/sessions +; session cookie name +COOKIE_NAME = i_like_gogits +; if you use session in https only, default is false +COOKIE_SECURE = false +; enable set cookie, default is true +ENABLE_SET_COOKIE = true +; session gc time interval, default is 86400 +GC_INTERVAL_TIME = 86400 +; session life time, default is 86400 +SESSION_LIFE_TIME = 86400 +; session id hash func, default is sha1 +SESSION_ID_HASHFUNC = sha1 +; session hash key, default is use random string +SESSION_ID_HASHKEY = + [picture] ; The place to picture data, either "server" or "qiniu", default is "server" SERVICE = server diff --git a/modules/auth/user.go b/modules/auth/user.go index f8d8f6614..cb8db1b29 100644 --- a/modules/auth/user.go +++ b/modules/auth/user.go @@ -9,7 +9,8 @@ import ( "reflect" "github.com/codegangsta/martini" - "github.com/martini-contrib/sessions" + + "github.com/gogits/session" "github.com/gogits/binding" @@ -19,7 +20,7 @@ import ( ) // SignedInId returns the id of signed in user. -func SignedInId(session sessions.Session) int64 { +func SignedInId(session session.SessionStore) int64 { userId := session.Get("userId") if userId == nil { return 0 @@ -34,7 +35,7 @@ func SignedInId(session sessions.Session) int64 { } // SignedInName returns the name of signed in user. -func SignedInName(session sessions.Session) string { +func SignedInName(session session.SessionStore) string { userName := session.Get("userName") if userName == nil { return "" @@ -46,7 +47,7 @@ func SignedInName(session sessions.Session) string { } // SignedInUser returns the user object of signed user. -func SignedInUser(session sessions.Session) *models.User { +func SignedInUser(session session.SessionStore) *models.User { id := SignedInId(session) if id <= 0 { return nil @@ -61,7 +62,7 @@ func SignedInUser(session sessions.Session) *models.User { } // IsSignedIn check if any user has signed in. -func IsSignedIn(session sessions.Session) bool { +func IsSignedIn(session session.SessionStore) bool { return SignedInId(session) > 0 } diff --git a/modules/base/conf.go b/modules/base/conf.go index 8c6ee6281..d5e27d043 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -16,6 +16,7 @@ import ( "github.com/Unknwon/goconfig" "github.com/gogits/cache" + "github.com/gogits/session" "github.com/gogits/gogs/modules/log" ) @@ -49,6 +50,10 @@ var ( LogMode string LogConfig string + + SessionProvider string + SessionConfig *session.Config + SessionManager *session.Manager ) var Service struct { @@ -164,6 +169,30 @@ func newCacheService() { log.Info("Cache Service Enabled") } +func newSessionService() { + SessionProvider = Cfg.MustValue("session", "PROVIDER", "memory") + + SessionConfig = new(session.Config) + SessionConfig.ProviderConfig = Cfg.MustValue("session", "PROVIDER_CONFIG") + SessionConfig.CookieName = Cfg.MustValue("session", "COOKIE_NAME", "i_like_gogits") + SessionConfig.CookieSecure = Cfg.MustBool("session", "COOKIE_SECURE") + SessionConfig.EnableSetCookie = Cfg.MustBool("session", "ENABLE_SET_COOKIE", true) + SessionConfig.GcIntervalTime = Cfg.MustInt64("session", "GC_INTERVAL_TIME", 86400) + SessionConfig.SessionLifeTime = Cfg.MustInt64("session", "SESSION_LIFE_TIME", 86400) + SessionConfig.SessionIDHashFunc = Cfg.MustValue("session", "SESSION_ID_HASHFUNC", "sha1") + SessionConfig.SessionIDHashKey = Cfg.MustValue("session", "SESSION_ID_HASHKEY") + + var err error + SessionManager, err = session.NewManager(SessionProvider, *SessionConfig) + if err != nil { + fmt.Printf("Init session system failed, provider: %s, %v\n", + SessionProvider, err) + os.Exit(2) + } + + log.Info("Session Service Enabled") +} + func newMailService() { // Check mailer setting. if Cfg.MustBool("mailer", "ENABLED") { @@ -234,6 +263,7 @@ func NewServices() { newService() newLogService() newCacheService() + newSessionService() newMailService() newRegisterMailService() } diff --git a/modules/middleware/context.go b/modules/middleware/context.go index a25a3dbbe..c958c1d6c 100644 --- a/modules/middleware/context.go +++ b/modules/middleware/context.go @@ -10,9 +10,9 @@ import ( "time" "github.com/codegangsta/martini" - "github.com/martini-contrib/sessions" "github.com/gogits/cache" + "github.com/gogits/session" "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/auth" @@ -27,7 +27,7 @@ type Context struct { p martini.Params Req *http.Request Res http.ResponseWriter - Session sessions.Session + Session session.SessionStore Cache cache.Cache User *models.User IsSigned bool @@ -92,21 +92,25 @@ func (ctx *Context) Handle(status int, title string, err error) { // InitContext initializes a classic context for a request. func InitContext() martini.Handler { - return func(res http.ResponseWriter, r *http.Request, c martini.Context, - session sessions.Session, rd *Render) { + return func(res http.ResponseWriter, r *http.Request, c martini.Context, rd *Render) { ctx := &Context{ c: c, // p: p, - Req: r, - Res: res, - Session: session, - Cache: base.Cache, - Render: rd, + Req: r, + Res: res, + Cache: base.Cache, + Render: rd, } + // start session + ctx.Session = base.SessionManager.SessionStart(res, r) + defer func() { + ctx.Session.SessionRelease(res) + }() + // Get user from session if logined. - user := auth.SignedInUser(session) + user := auth.SignedInUser(ctx.Session) ctx.User = user ctx.IsSigned = user != nil diff --git a/routers/user/user.go b/routers/user/user.go index d38eb1ceb..224469771 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -88,7 +88,7 @@ func SignIn(ctx *middleware.Context, form auth.LogInForm) { user, err := models.LoginUserPlain(form.UserName, form.Password) if err != nil { - if err.Error() == models.ErrUserNotExist.Error() { + if err == models.ErrUserNotExist { ctx.RenderWithErr("Username or password is not correct", "user/signin", &form) return } diff --git a/web.go b/web.go index 595b8f74e..ac5761d72 100644 --- a/web.go +++ b/web.go @@ -12,7 +12,6 @@ import ( "github.com/codegangsta/cli" "github.com/codegangsta/martini" - "github.com/martini-contrib/sessions" "github.com/gogits/binding" @@ -81,10 +80,6 @@ func runWeb(*cli.Context) { // Middlewares. m.Use(middleware.Renderer(middleware.RenderOptions{Funcs: []template.FuncMap{base.TemplateFuncs}})) - // TODO: should use other store because cookie store is not secure. - store := sessions.NewCookieStore([]byte("secret123")) - m.Use(sessions.Sessions("my_session", store)) - m.Use(middleware.InitContext()) reqSignIn := middleware.SignInRequire(true) From 01e781dedb3c6d48349516de0eee5cea41c077e1 Mon Sep 17 00:00:00 2001 From: slene Date: Sat, 22 Mar 2014 21:19:27 +0800 Subject: [PATCH 06/19] add comment --- conf/app.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/conf/app.ini b/conf/app.ini index cf2ae31d8..6b3ce8d24 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -94,7 +94,7 @@ ENABLE_SET_COOKIE = true GC_INTERVAL_TIME = 86400 ; session life time, default is 86400 SESSION_LIFE_TIME = 86400 -; session id hash func, default is sha1 +; session id hash func, Either "sha1", "sha256" or "md5" default is sha1 SESSION_ID_HASHFUNC = sha1 ; session hash key, default is use random string SESSION_ID_HASHKEY = From fd1831052c3a79492643b89512282fc66f34dd8d Mon Sep 17 00:00:00 2001 From: Unknown Date: Sat, 22 Mar 2014 09:21:57 -0400 Subject: [PATCH 07/19] Update session --- .gopmfile | 1 - README.md | 2 +- conf/app.ini | 25 +++++----- gogs.go | 2 +- modules/base/conf.go | 16 ++++--- modules/base/tool.go | 84 +++++++++++++++++++++++++++++++++- routers/admin/admin.go | 12 ++++- templates/admin/config.tmpl | 19 ++++++++ templates/admin/dashboard.tmpl | 1 + 9 files changed, 135 insertions(+), 27 deletions(-) diff --git a/.gopmfile b/.gopmfile index 5b690a06a..6e6b59c62 100644 --- a/.gopmfile +++ b/.gopmfile @@ -4,7 +4,6 @@ path=github.com/gogits/gogs [deps] github.com/codegangsta/cli= github.com/codegangsta/martini= -github.com/martini-contrib/sessions= github.com/Unknwon/com= github.com/Unknwon/cae= github.com/Unknwon/goconfig= diff --git a/README.md b/README.md index a9ab7fe49..35044927f 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ 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). +- Mail Service is based on [WeTalk](https://github.com/beego/wetalk). - System Monitor Status is based on [GoBlog](https://github.com/fuxiaohei/goblog). ## Contributors diff --git a/conf/app.ini b/conf/app.ini index cf2ae31d8..30d6c7d48 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -75,28 +75,25 @@ HOST = [session] ; Either "memory", "file", "redis" or "mysql", default is "memory" PROVIDER = file -; provider config +; Provider config options ; memory: not have any config yet -; file: session file path -; e.g. tmp/sessions -; redis: config like redis server addr,poolSize,password -; e.g. 127.0.0.1:6379,100,astaxie -; mysql: go-sql-driver/mysql dsn config string -; e.g. root:password@/session_table +; file: session file path, e.g. data/sessions +; redis: config like redis server addr, poolSize, password, e.g. 127.0.0.1:6379,100,astaxie +; mysql: go-sql-driver/mysql dsn config string, e.g. root:password@/session_table PROVIDER_CONFIG = data/sessions -; session cookie name +; Session cookie name COOKIE_NAME = i_like_gogits -; if you use session in https only, default is false +; If you use session in https only, default is false COOKIE_SECURE = false -; enable set cookie, default is true +; Enable set cookie, default is true ENABLE_SET_COOKIE = true -; session gc time interval, default is 86400 +; Session GC time interval, default is 86400 GC_INTERVAL_TIME = 86400 -; session life time, default is 86400 +; Session life time, default is 86400 SESSION_LIFE_TIME = 86400 -; session id hash func, default is sha1 +; Session id hash func, default is sha1 SESSION_ID_HASHFUNC = sha1 -; session hash key, default is use random string +; Session hash key, default is use random string SESSION_ID_HASHKEY = [picture] diff --git a/gogs.go b/gogs.go index 8ec4fd42f..a60903209 100644 --- a/gogs.go +++ b/gogs.go @@ -20,7 +20,7 @@ import ( // Test that go1.2 tag above is included in builds. main.go refers to this definition. const go12tag = true -const APP_VER = "0.1.5.0322" +const APP_VER = "0.1.5.0322.2" func init() { base.AppVer = APP_VER diff --git a/modules/base/conf.go b/modules/base/conf.go index d5e27d043..7c8ed9365 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -41,19 +41,19 @@ var ( Cfg *goconfig.ConfigFile MailService *Mailer + LogMode string + LogConfig string + Cache cache.Cache CacheAdapter string CacheConfig string - PictureService string - PictureRootPath string - - LogMode string - LogConfig string - SessionProvider string SessionConfig *session.Config SessionManager *session.Manager + + PictureService string + PictureRootPath string ) var Service struct { @@ -182,6 +182,10 @@ func newSessionService() { SessionConfig.SessionIDHashFunc = Cfg.MustValue("session", "SESSION_ID_HASHFUNC", "sha1") SessionConfig.SessionIDHashKey = Cfg.MustValue("session", "SESSION_ID_HASHKEY") + if SessionProvider == "file" { + os.MkdirAll(path.Dir(SessionConfig.ProviderConfig), os.ModePerm) + } + var err error SessionManager, err = session.NewManager(SessionProvider, *SessionConfig) if err != nil { diff --git a/modules/base/tool.go b/modules/base/tool.go index 8fabb8c53..4f368aa58 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -111,6 +111,85 @@ const ( Year = 12 * Month ) +func computeTimeDiff(diff int64) (int64, string) { + diffStr := "" + switch { + case diff <= 0: + diff = 0 + diffStr = "now" + case diff < 2: + diff = 0 + diffStr = "1 second" + case diff < 1*Minute: + diffStr = fmt.Sprintf("%d seconds", diff) + diff = 0 + + case diff < 2*Minute: + diff -= 1 * Minute + diffStr = "1 minute" + case diff < 1*Hour: + diffStr = fmt.Sprintf("%d minutes", diff/Minute) + diff -= diff / Minute * Minute + + case diff < 2*Hour: + diff -= 1 * Hour + diffStr = "1 hour" + case diff < 1*Day: + diffStr = fmt.Sprintf("%d hours", diff/Hour) + diff -= diff / Hour * Hour + + case diff < 2*Day: + diff -= 1 * Day + diffStr = "1 day" + case diff < 1*Week: + diffStr = fmt.Sprintf("%d days", diff/Day) + diff -= diff / Day * Day + + case diff < 2*Week: + diff -= 1 * Week + diffStr = "1 week" + case diff < 1*Month: + diffStr = fmt.Sprintf("%d weeks", diff/Week) + diff -= diff / Week * Week + + case diff < 2*Month: + diff -= 1 * Month + diffStr = "1 month" + case diff < 1*Year: + diffStr = fmt.Sprintf("%d months", diff/Month) + diff -= diff / Month * Month + + case diff < 2*Year: + diff -= 1 * Year + diffStr = "1 year" + default: + diffStr = fmt.Sprintf("%d years", diff/Year) + diff = 0 + } + return diff, diffStr +} + +// TimeSincePro calculates the time interval and generate full user-friendly string. +func TimeSincePro(then time.Time) string { + now := time.Now() + diff := now.Unix() - then.Unix() + + if then.After(now) { + return "future" + } + + var timeStr, diffStr string + for { + if diff == 0 { + break + } + + diff, diffStr = computeTimeDiff(diff) + timeStr += ", " + diffStr + } + return strings.TrimPrefix(timeStr, ", ") +} + // TimeSince calculates the time interval and generate user-friendly string. func TimeSince(then time.Time) string { now := time.Now() @@ -123,7 +202,6 @@ func TimeSince(then time.Time) string { } switch { - case diff <= 0: return "now" case diff <= 2: @@ -156,8 +234,10 @@ func TimeSince(then time.Time) string { case diff < 1*Year: return fmt.Sprintf("%d months %s", diff/Month, lbl) - case diff < 18*Month: + case diff < 2*Year: return fmt.Sprintf("1 year %s", lbl) + default: + return fmt.Sprintf("%d years %s", diff/Year, lbl) } return then.String() } diff --git a/routers/admin/admin.go b/routers/admin/admin.go index 57a46d1df..c0f39f715 100644 --- a/routers/admin/admin.go +++ b/routers/admin/admin.go @@ -17,7 +17,10 @@ import ( "github.com/gogits/gogs/modules/middleware" ) +var startTime = time.Now() + var sysStatus struct { + Uptime string NumGoroutine int // General statistics. @@ -58,6 +61,8 @@ var sysStatus struct { } func updateSystemStatus() { + sysStatus.Uptime = base.TimeSincePro(startTime) + m := new(runtime.MemStats) runtime.ReadMemStats(m) sysStatus.NumGoroutine = runtime.NumGoroutine() @@ -88,8 +93,8 @@ func updateSystemStatus() { sysStatus.NextGC = base.FileSize(int64(m.NextGC)) sysStatus.LastGC = fmt.Sprintf("%.1fs", float64(time.Now().UnixNano()-int64(m.LastGC))/1000/1000/1000) - sysStatus.PauseTotalNs = fmt.Sprintf("%.1fs", float64(m.PauseTotalNs/1000/1000/1000)) - sysStatus.PauseNs = fmt.Sprintf("%.3fs", float64(m.PauseNs[(m.NumGC+255)%256]/1000/1000/1000)) + sysStatus.PauseTotalNs = fmt.Sprintf("%.1fs", float64(m.PauseTotalNs)/1000/1000/1000) + sysStatus.PauseNs = fmt.Sprintf("%.3fs", float64(m.PauseNs[(m.NumGC+255)%256])/1000/1000/1000) sysStatus.NumGC = m.NumGC } @@ -151,6 +156,9 @@ func Config(ctx *middleware.Context) { ctx.Data["CacheAdapter"] = base.CacheAdapter ctx.Data["CacheConfig"] = base.CacheConfig + ctx.Data["SessionProvider"] = base.SessionProvider + ctx.Data["SessionConfig"] = base.SessionConfig + ctx.Data["PictureService"] = base.PictureService ctx.Data["PictureRootPath"] = base.PictureRootPath diff --git a/templates/admin/config.tmpl b/templates/admin/config.tmpl index e3f69ee6e..048740e61 100644 --- a/templates/admin/config.tmpl +++ b/templates/admin/config.tmpl @@ -77,6 +77,25 @@
+
+
+ Session Configuration +
+ +
+
Session Provider: {{.SessionProvider}}
+
Cookie Name: {{.SessionConfig.CookieName}}
+
Enable Set Cookie:
+
GC Interval Time: {{.SessionConfig.GcIntervalTime}} seconds
+
Session Life Time: {{.SessionConfig.SessionLifeTime}} seconds
+
HTTPS Only:
+
Cookie Life Time: {{.SessionConfig.CookieLifeTime}} seconds
+
Session ID Hash Function: {{.SessionConfig.SessionIDHashFunc}}
+
Session ID Hash Key: {{.SessionConfig.SessionIDHashKey}}
+
Provider Config: {{.SessionConfig.ProviderConfig}}
+
+
+
Picture Configuration diff --git a/templates/admin/dashboard.tmpl b/templates/admin/dashboard.tmpl index 0bebf8318..2a5a161e0 100644 --- a/templates/admin/dashboard.tmpl +++ b/templates/admin/dashboard.tmpl @@ -19,6 +19,7 @@
+
Server Uptime: {{.SysStatus.Uptime}}
Current Goroutines: {{.SysStatus.NumGoroutine}}

Current Memory Usage: {{.SysStatus.MemAllocated}}
From e3f55ca0fb0c8aee84f2935b76353ef8ce66384f Mon Sep 17 00:00:00 2001 From: Unknown Date: Sat, 22 Mar 2014 11:59:14 -0400 Subject: [PATCH 08/19] Need a field to specify if repository is bare --- models/action.go | 1 + models/repo.go | 6 ++++-- routers/repo/single.go | 10 ++-------- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/models/action.go b/models/action.go index 12122ae24..4e1107f89 100644 --- a/models/action.go +++ b/models/action.go @@ -87,6 +87,7 @@ func CommitRepoAction(userId int64, userName string, if err != nil { return err } + repo.IsBare = false repo.Updated = time.Now() if err = UpdateRepository(repo); err != nil { return err diff --git a/models/repo.go b/models/repo.go index 1961b31e9..fb115de59 100644 --- a/models/repo.go +++ b/models/repo.go @@ -83,10 +83,11 @@ type Repository struct { Name string `xorm:"index not null"` Description string Website string - Private bool NumWatches int NumStars int NumForks int + IsPrivate bool + IsBare bool Created time.Time `xorm:"created"` Updated time.Time `xorm:"updated"` } @@ -139,7 +140,8 @@ func CreateRepository(user *User, repoName, desc, repoLang, license string, priv Name: repoName, LowerName: strings.ToLower(repoName), Description: desc, - Private: private, + IsPrivate: private, + IsBare: repoLang == "" && license == "" && !initReadme, } repoPath := RepoPath(user.Name, repoName) diff --git a/routers/repo/single.go b/routers/repo/single.go index 37c0fabd7..5906e64fb 100644 --- a/routers/repo/single.go +++ b/routers/repo/single.go @@ -69,7 +69,7 @@ func Single(ctx *middleware.Context, params martini.Params) { log.Error("repo.Single(GetBranches): %v", err) ctx.Error(404) return - } else if len(brs) == 0 { + } else if ctx.Repo.Repository.IsBare { ctx.Data["IsBareRepo"] = true ctx.HTML(200, "repo/single") return @@ -224,13 +224,7 @@ func Setting(ctx *middleware.Context, params martini.Params) { ctx.Data["IsRepoToolbarSetting"] = true - // Branches. - brs, err := models.GetBranches(params["username"], params["reponame"]) - if err != nil { - log.Error("repo.Setting(GetBranches): %v", err) - ctx.Error(404) - return - } else if len(brs) == 0 { + if ctx.Repo.Repository.IsBare { ctx.Data["IsBareRepo"] = true ctx.HTML(200, "repo/setting") return From 076fc98d981aea3533eea363ca1c7e43f77b9802 Mon Sep 17 00:00:00 2001 From: slene Date: Sun, 23 Mar 2014 01:44:02 +0800 Subject: [PATCH 09/19] add csrf check --- modules/base/tool.go | 10 ++- modules/middleware/auth.go | 58 +++++++++-------- modules/middleware/context.go | 107 +++++++++++++++++++++++++++++++- modules/middleware/render.go | 5 +- public/js/app.js | 33 ++++++++++ templates/admin/users/edit.tmpl | 1 + templates/admin/users/new.tmpl | 1 + templates/base/head.tmpl | 1 + templates/repo/create.tmpl | 1 + templates/repo/setting.tmpl | 1 + templates/user/active.tmpl | 3 +- templates/user/delete.tmpl | 1 + templates/user/password.tmpl | 4 +- templates/user/publickey.tmpl | 1 + templates/user/setting.tmpl | 1 + templates/user/signin.tmpl | 1 + templates/user/signup.tmpl | 1 + web.go | 24 +++---- 18 files changed, 208 insertions(+), 46 deletions(-) diff --git a/modules/base/tool.go b/modules/base/tool.go index 8fabb8c53..a2aeebf1b 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -25,13 +25,17 @@ func EncodeMd5(str string) string { return hex.EncodeToString(m.Sum(nil)) } -// Random generate string -func GetRandomString(n int) string { +// GetRandomString generate random string by specify chars. +func GetRandomString(n int, alphabets ...byte) string { const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" var bytes = make([]byte, n) rand.Read(bytes) for i, b := range bytes { - bytes[i] = alphanum[b%byte(len(alphanum))] + if len(alphabets) == 0 { + bytes[i] = alphanum[b%byte(len(alphanum))] + } else { + bytes[i] = alphabets[b%byte(len(alphabets))] + } } return string(bytes) } diff --git a/modules/middleware/auth.go b/modules/middleware/auth.go index f211de32b..b557188ee 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 } } diff --git a/modules/middleware/context.go b/modules/middleware/context.go index c958c1d6c..b28953fc0 100644 --- a/modules/middleware/context.go +++ b/modules/middleware/context.go @@ -6,6 +6,7 @@ package middleware import ( "fmt" + "html/template" "net/http" "time" @@ -32,6 +33,8 @@ type Context struct { User *models.User IsSigned bool + csrfToken string + Repo struct { IsValid bool IsOwner bool @@ -90,6 +93,95 @@ func (ctx *Context) Handle(status int, title string, err error) { ctx.HTML(status, fmt.Sprintf("status/%d", status)) } +func (ctx *Context) GetCookie(name string) string { + cookie, err := ctx.Req.Cookie(name) + if err != nil { + return "" + } + return cookie.Value +} + +func (ctx *Context) SetCookie(name string, value string, others ...interface{}) { + cookie := http.Cookie{} + cookie.Name = name + cookie.Value = value + + if len(others) > 0 { + switch v := others[0].(type) { + case int: + cookie.MaxAge = v + case int64: + cookie.MaxAge = int(v) + case int32: + cookie.MaxAge = int(v) + } + } + + // default "/" + if len(others) > 1 { + if v, ok := others[1].(string); ok && len(v) > 0 { + cookie.Path = v + } + } else { + cookie.Path = "/" + } + + // default empty + if len(others) > 2 { + if v, ok := others[2].(string); ok && len(v) > 0 { + cookie.Domain = v + } + } + + // default empty + if len(others) > 3 { + switch v := others[3].(type) { + case bool: + cookie.Secure = v + default: + if others[3] != nil { + cookie.Secure = true + } + } + } + + // default false. for session cookie default true + if len(others) > 4 { + if v, ok := others[4].(bool); ok && v { + cookie.HttpOnly = true + } + } + + ctx.Res.Header().Add("Set-Cookie", cookie.String()) +} + +func (ctx *Context) CsrfToken() string { + if len(ctx.csrfToken) > 0 { + return ctx.csrfToken + } + + token := ctx.GetCookie("_csrf") + if len(token) == 0 { + token = base.GetRandomString(30) + ctx.SetCookie("_csrf", token) + } + ctx.csrfToken = token + return token +} + +func (ctx *Context) CsrfTokenValid() bool { + token := ctx.Query("_csrf") + if token == "" { + token = ctx.Req.Header.Get("X-Csrf-Token") + } + if token == "" { + return false + } else if ctx.csrfToken != token { + return false + } + return true +} + // InitContext initializes a classic context for a request. func InitContext() martini.Handler { return func(res http.ResponseWriter, r *http.Request, c martini.Context, rd *Render) { @@ -103,11 +195,14 @@ func InitContext() martini.Handler { Render: rd, } + ctx.Data["PageStartTime"] = time.Now() + // start session ctx.Session = base.SessionManager.SessionStart(res, r) - defer func() { + rw := res.(martini.ResponseWriter) + rw.Before(func(martini.ResponseWriter) { ctx.Session.SessionRelease(res) - }() + }) // Get user from session if logined. user := auth.SignedInUser(ctx.Session) @@ -121,9 +216,15 @@ 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 + } } - ctx.Data["PageStartTime"] = time.Now() + // get or create csrf token + ctx.Data["CsrfToken"] = ctx.CsrfToken() + ctx.Data["CsrfTokenHtml"] = template.HTML(``) c.Map(ctx) diff --git a/modules/middleware/render.go b/modules/middleware/render.go index 8a5418313..869ef9aba 100644 --- a/modules/middleware/render.go +++ b/modules/middleware/render.go @@ -242,8 +242,11 @@ func (r *Render) HTMLString(name string, binding interface{}, htmlOpt ...HTMLOpt } } -func (r *Render) Error(status int) { +func (r *Render) Error(status int, message ...string) { r.WriteHeader(status) + if len(message) > 0 { + r.Write([]byte(message[0])) + } } func (r *Render) Redirect(location string, status ...int) { diff --git a/public/js/app.js b/public/js/app.js index f179342f4..df755727b 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -2,6 +2,39 @@ var Gogits = { "PageIsSignup": false }; +(function($){ + // extend jQuery ajax, set csrf token value + var ajax = $.ajax; + $.extend({ + ajax: function(url, options) { + if (typeof url === 'object') { + options = url; + url = undefined; + } + options = options || {}; + url = options.url; + var csrftoken = $('meta[name=_csrf]').attr('content'); + var headers = options.headers || {}; + var domain = document.domain.replace(/\./ig, '\\.'); + if (!/^(http:|https:).*/.test(url) || eval('/^(http:|https:)\\/\\/(.+\\.)*' + domain + '.*/').test(url)) { + headers = $.extend(headers, {'X-Csrf-Token':csrftoken}); + } + options.headers = headers; + var callback = options.success; + options.success = function(data){ + if(data.once){ + // change all _once value if ajax data.once exist + $('[name=_once]').val(data.once); + } + if(callback){ + callback.apply(this, arguments); + } + }; + return ajax(url, options); + } + }); +}(jQuery)); + (function ($) { Gogits.showTab = function (selector, index) { diff --git a/templates/admin/users/edit.tmpl b/templates/admin/users/edit.tmpl index 2a9882423..08f11fcb1 100644 --- a/templates/admin/users/edit.tmpl +++ b/templates/admin/users/edit.tmpl @@ -12,6 +12,7 @@
{{if .IsSuccess}}

Account profile has been successfully updated.

{{else if .HasError}}

{{.ErrorMsg}}

{{end}} + {{.CsrfTokenHtml}}
diff --git a/templates/admin/users/new.tmpl b/templates/admin/users/new.tmpl index 01d976caa..7b41ae43a 100644 --- a/templates/admin/users/new.tmpl +++ b/templates/admin/users/new.tmpl @@ -11,6 +11,7 @@

+ {{.CsrfTokenHtml}}
{{.ErrorMsg}}
diff --git a/templates/base/head.tmpl b/templates/base/head.tmpl index f02ea095c..7f56ed708 100644 --- a/templates/base/head.tmpl +++ b/templates/base/head.tmpl @@ -8,6 +8,7 @@ + diff --git a/templates/repo/create.tmpl b/templates/repo/create.tmpl index 2de92f515..a43f51048 100644 --- a/templates/repo/create.tmpl +++ b/templates/repo/create.tmpl @@ -2,6 +2,7 @@ {{template "base/navbar" .}}
+ {{.CsrfTokenHtml}}

Create New Repository

{{.ErrorMsg}}
diff --git a/templates/repo/setting.tmpl b/templates/repo/setting.tmpl index a2fb1771d..38c3fd3bc 100644 --- a/templates/repo/setting.tmpl +++ b/templates/repo/setting.tmpl @@ -40,6 +40,7 @@