From e41ab839c7dbbdffc60a4e02775f24add9d126d9 Mon Sep 17 00:00:00 2001 From: Unknown Date: Fri, 4 Apr 2014 18:55:17 -0400 Subject: [PATCH 01/24] Use session for rolling back --- gogs.go | 2 +- models/access.go | 11 +++++++++++ models/repo.go | 43 ++++++++++++++++++++++++++++++++++++------- models/user.go | 18 +++++++++++++++--- 4 files changed, 63 insertions(+), 11 deletions(-) diff --git a/gogs.go b/gogs.go index 034e131b..8d9159d6 100644 --- a/gogs.go +++ b/gogs.go @@ -19,7 +19,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.2.0.0403 Alpha" +const APP_VER = "0.2.0.0404 Alpha" func init() { base.AppVer = APP_VER diff --git a/models/access.go b/models/access.go index 83261575..2c090015 100644 --- a/models/access.go +++ b/models/access.go @@ -7,6 +7,8 @@ package models import ( "strings" "time" + + "github.com/lunny/xorm" ) // Access types. @@ -40,6 +42,15 @@ func UpdateAccess(access *Access) error { return err } +// UpdateAccess updates access information with session for rolling back. +func UpdateAccessWithSession(sess *xorm.Session, access *Access) error { + if _, err := sess.Id(access.Id).Update(access); err != nil { + sess.Rollback() + return err + } + return nil +} + // HasAccess returns true if someone can read or write to given repository. func HasAccess(userName, repoName string, mode int) (bool, error) { return orm.Get(&Access{ diff --git a/models/repo.go b/models/repo.go index e8ebce92..acee6f6a 100644 --- a/models/repo.go +++ b/models/repo.go @@ -381,45 +381,62 @@ func TransferOwnership(user *User, newOwner string, repo *Repository) (err error if err = orm.Find(&accesses, &Access{RepoName: user.LowerName + "/" + repo.LowerName}); err != nil { return err } + + sess := orm.NewSession() + defer sess.Close() + if err = sess.Begin(); err != nil { + return err + } + for i := range accesses { accesses[i].RepoName = newUser.LowerName + "/" + repo.LowerName if accesses[i].UserName == user.LowerName { accesses[i].UserName = newUser.LowerName } - if err = UpdateAccess(&accesses[i]); err != nil { + if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil { return err } } // Update repository. repo.OwnerId = newUser.Id - if _, err := orm.Id(repo.Id).Update(repo); err != nil { + if _, err := sess.Id(repo.Id).Update(repo); err != nil { + sess.Rollback() return err } // Update user repository number. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?" - if _, err = orm.Exec(rawSql, newUser.Id); err != nil { + if _, err = sess.Exec(rawSql, newUser.Id); err != nil { + sess.Rollback() return err } rawSql = "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?" - if _, err = orm.Exec(rawSql, user.Id); err != nil { + if _, err = sess.Exec(rawSql, user.Id); err != nil { + sess.Rollback() return err } // Add watch of new owner to repository. if !IsWatching(newUser.Id, repo.Id) { if err = WatchRepo(newUser.Id, repo.Id, true); err != nil { + sess.Rollback() return err } } if err = TransferRepoAction(user, newUser, repo); err != nil { + sess.Rollback() return err } // Change repository directory name. - return os.Rename(RepoPath(user.Name, repo.Name), RepoPath(newUser.Name, repo.Name)) + if err = os.Rename(RepoPath(user.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil { + sess.Rollback() + return err + } + + return sess.Commit() } // ChangeRepositoryName changes all corresponding setting from old repository name to new one. @@ -429,15 +446,27 @@ func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) if err = orm.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}); err != nil { return err } + + sess := orm.NewSession() + defer sess.Close() + if err = sess.Begin(); err != nil { + return err + } + for i := range accesses { accesses[i].RepoName = userName + "/" + newRepoName - if err = UpdateAccess(&accesses[i]); err != nil { + if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil { return err } } // Change repository directory name. - return os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)) + if err = os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)); err != nil { + sess.Rollback() + return err + } + + return sess.Commit() } func UpdateRepository(repo *Repository) error { diff --git a/models/user.go b/models/user.go index 2641a15f..1ec3b295 100644 --- a/models/user.go +++ b/models/user.go @@ -218,11 +218,18 @@ func ChangeUserName(user *User, newUserName string) (err error) { if err = orm.Find(&accesses, &Access{UserName: user.LowerName}); err != nil { return err } + + sess := orm.NewSession() + defer sess.Close() + if err = sess.Begin(); err != nil { + return err + } + for i := range accesses { accesses[i].UserName = newUserName if strings.HasPrefix(accesses[i].RepoName, user.LowerName+"/") { accesses[i].RepoName = strings.Replace(accesses[i].RepoName, user.LowerName, newUserName, 1) - if err = UpdateAccess(&accesses[i]); err != nil { + if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil { return err } } @@ -241,14 +248,19 @@ func ChangeUserName(user *User, newUserName string) (err error) { for j := range accesses { accesses[j].RepoName = newUserName + "/" + repos[i].LowerName - if err = UpdateAccess(&accesses[j]); err != nil { + if err = UpdateAccessWithSession(sess, &accesses[j]); err != nil { return err } } } // Change user directory name. - return os.Rename(UserPath(user.LowerName), UserPath(newUserName)) + if err = os.Rename(UserPath(user.LowerName), UserPath(newUserName)); err != nil { + sess.Rollback() + return err + } + + return sess.Commit() } // UpdateUser updates user's information. From 493b0c5ac212a28f46938cf8dfb2efb79f658548 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sat, 5 Apr 2014 15:17:57 +0800 Subject: [PATCH 02/24] add ssl support for web --- conf/app.ini | 5 +- routers/repo/repo.go | 96 ++++++++++++++++++++++++++++++++++++++- templates/status/401.tmpl | 6 +++ web.go | 18 ++++++-- 4 files changed, 118 insertions(+), 7 deletions(-) create mode 100644 templates/status/401.tmpl diff --git a/conf/app.ini b/conf/app.ini index abc27c39..f88c750e 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -12,10 +12,13 @@ LANG_IGNS = Google Go|C|C++|Python|Ruby|C Sharp LICENSES = Apache v2 License|GPL v2|MIT License|Affero GPL|Artistic License 2.0|BSD (3-Clause) License [server] +PROTOCOL = http DOMAIN = localhost -ROOT_URL = http://%(DOMAIN)s:%(HTTP_PORT)s/ +ROOT_URL = %(PROTOCOL)://%(DOMAIN)s:%(HTTP_PORT)s/ HTTP_ADDR = HTTP_PORT = 3000 +CERT_FILE = cert.pem +KEY_FILE = key.pem [database] ; Either "mysql", "postgres" or "sqlite3"(binary release only), it's your choice diff --git a/routers/repo/repo.go b/routers/repo/repo.go index ae51c551..cb7febd2 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -5,6 +5,8 @@ package repo import ( + "encoding/base64" + "errors" "fmt" "path" "path/filepath" @@ -237,15 +239,105 @@ func SingleDownload(ctx *middleware.Context, params martini.Params) { ctx.Res.Write(data) } -func Http(ctx *middleware.Context, params martini.Params) { - // TODO: access check +func basicEncode(username, password string) string { + auth := username + ":" + password + return base64.StdEncoding.EncodeToString([]byte(auth)) +} +func basicDecode(encoded string) (user string, name string, err error) { + var s []byte + s, err = base64.StdEncoding.DecodeString(encoded) + if err != nil { + return + } + + a := strings.Split(string(s), ":") + if len(a) == 2 { + user, name = a[0], a[1] + } else { + err = errors.New("decode failed") + } + return +} + +func authRequired(ctx *middleware.Context) { + ctx.ResponseWriter.Header().Set("WWW-Authenticate", `Basic realm="Gogs Auth"`) + ctx.Data["ErrorMsg"] = "no basic auth and digit auth" + ctx.HTML(401, fmt.Sprintf("status/401")) +} + +func Http(ctx *middleware.Context, params martini.Params) { username := params["username"] reponame := params["reponame"] if strings.HasSuffix(reponame, ".git") { reponame = reponame[:len(reponame)-4] } + repoUser, err := models.GetUserByName(username) + if err != nil { + ctx.Handle(500, "repo.GetUserByName", nil) + return + } + + repo, err := models.GetRepositoryByName(repoUser.Id, reponame) + if err != nil { + ctx.Handle(500, "repo.GetRepositoryByName", nil) + return + } + + isPull := webdav.IsPullMethod(ctx.Req.Method) + var askAuth = !(!repo.IsPrivate && isPull) + + //authRequired(ctx) + //return + + // check access + if askAuth { + // check digit auth + + // check basic auth + baHead := ctx.Req.Header.Get("Authorization") + if baHead != "" { + auths := strings.Fields(baHead) + if len(auths) != 2 || auths[0] != "Basic" { + ctx.Handle(401, "no basic auth and digit auth", nil) + return + } + authUsername, passwd, err := basicDecode(auths[1]) + if err != nil { + ctx.Handle(401, "no basic auth and digit auth", nil) + return + } + + authUser, err := models.GetUserByName(authUsername) + if err != nil { + ctx.Handle(401, "no basic auth and digit auth", nil) + return + } + + newUser := &models.User{Passwd: passwd} + newUser.EncodePasswd() + if authUser.Passwd != newUser.Passwd { + ctx.Handle(401, "no basic auth and digit auth", nil) + return + } + + var tp = models.AU_WRITABLE + if isPull { + tp = models.AU_READABLE + } + + has, err := models.HasAccess(authUsername, username+"/"+reponame, tp) + if err != nil || !has { + ctx.Handle(401, "no basic auth and digit auth", nil) + return + } + } else { + authRequired(ctx) + return + } + } + prefix := path.Join("/", username, params["reponame"]) server := webdav.NewServer( models.RepoPath(username, reponame), diff --git a/templates/status/401.tmpl b/templates/status/401.tmpl new file mode 100644 index 00000000..98995381 --- /dev/null +++ b/templates/status/401.tmpl @@ -0,0 +1,6 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +
+ 401 Unauthorized +
+{{template "base/footer" .}} \ No newline at end of file diff --git a/web.go b/web.go index 5fc3350f..18e48b84 100644 --- a/web.go +++ b/web.go @@ -169,12 +169,22 @@ func runWeb(*cli.Context) { // Not found handler. m.NotFound(routers.NotFound) + protocol := base.Cfg.MustValue("server", "PROTOCOL", "http") listenAddr := fmt.Sprintf("%s:%s", base.Cfg.MustValue("server", "HTTP_ADDR"), base.Cfg.MustValue("server", "HTTP_PORT", "3000")) - log.Info("Listen: %s", listenAddr) - if err := http.ListenAndServe(listenAddr, m); err != nil { - fmt.Println(err.Error()) - //log.Critical(err.Error()) // not working now + + if protocol == "http" { + log.Info("Listen: http://%s", listenAddr) + if err := http.ListenAndServe(listenAddr, m); err != nil { + fmt.Println(err.Error()) + //log.Critical(err.Error()) // not working now + } + } else if protocol == "https" { + log.Info("Listen: https://%s", listenAddr) + if err := http.ListenAndServeTLS(listenAddr, base.Cfg.MustValue("server", "CERT_FILE"), + base.Cfg.MustValue("server", "KEY_FILE"), m); err != nil { + fmt.Println(err.Error()) + } } } From 9791e70da67091d244728070b80ee92c98d6aa8b Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sat, 5 Apr 2014 22:24:10 +0800 Subject: [PATCH 03/24] bug fixed --- models/publickey.go | 4 +-- routers/repo/repo.go | 76 +++++++++++++++++++++++--------------------- 2 files changed, 41 insertions(+), 39 deletions(-) diff --git a/models/publickey.go b/models/publickey.go index 42d2523b..426e6b0b 100644 --- a/models/publickey.go +++ b/models/publickey.go @@ -77,8 +77,8 @@ func init() { // PublicKey represents a SSH key of user. type PublicKey struct { Id int64 - OwnerId int64 `xorm:" index not null"` - Name string `xorm:" not null"` //UNIQUE(s) + OwnerId int64 `xorm:"unique(s) index not null"` + Name string `xorm:"unique(s) not null"` //UNIQUE(s) Fingerprint string Content string `xorm:"TEXT not null"` Created time.Time `xorm:"created"` diff --git a/routers/repo/repo.go b/routers/repo/repo.go index b6a5d178..d223600c 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -261,7 +261,7 @@ func basicDecode(encoded string) (user string, name string, err error) { } func authRequired(ctx *middleware.Context) { - ctx.ResponseWriter.Header().Set("WWW-Authenticate", `Basic realm="Gogs Auth"`) + ctx.ResponseWriter.Header().Set("WWW-Authenticate", "Basic realm=\".\"") ctx.Data["ErrorMsg"] = "no basic auth and digit auth" ctx.HTML(401, fmt.Sprintf("status/401")) } @@ -273,6 +273,8 @@ func Http(ctx *middleware.Context, params martini.Params) { reponame = reponame[:len(reponame)-4] } + //fmt.Println("req:", ctx.Req.Header) + repoUser, err := models.GetUserByName(username) if err != nil { ctx.Handle(500, "repo.GetUserByName", nil) @@ -297,45 +299,45 @@ func Http(ctx *middleware.Context, params martini.Params) { // check basic auth baHead := ctx.Req.Header.Get("Authorization") - if baHead != "" { - auths := strings.Fields(baHead) - if len(auths) != 2 || auths[0] != "Basic" { - ctx.Handle(401, "no basic auth and digit auth", nil) - return - } - authUsername, passwd, err := basicDecode(auths[1]) - if err != nil { - ctx.Handle(401, "no basic auth and digit auth", nil) - return - } - - authUser, err := models.GetUserByName(authUsername) - if err != nil { - ctx.Handle(401, "no basic auth and digit auth", nil) - return - } - - newUser := &models.User{Passwd: passwd} - newUser.EncodePasswd() - if authUser.Passwd != newUser.Passwd { - ctx.Handle(401, "no basic auth and digit auth", nil) - return - } - - var tp = models.AU_WRITABLE - if isPull { - tp = models.AU_READABLE - } - - has, err := models.HasAccess(authUsername, username+"/"+reponame, tp) - if err != nil || !has { - ctx.Handle(401, "no basic auth and digit auth", nil) - return - } - } else { + if baHead == "" { authRequired(ctx) return } + + auths := strings.Fields(baHead) + if len(auths) != 2 || auths[0] != "Basic" { + ctx.Handle(401, "no basic auth and digit auth", nil) + return + } + authUsername, passwd, err := basicDecode(auths[1]) + if err != nil { + ctx.Handle(401, "no basic auth and digit auth", nil) + return + } + + authUser, err := models.GetUserByName(authUsername) + if err != nil { + ctx.Handle(401, "no basic auth and digit auth", nil) + return + } + + newUser := &models.User{Passwd: passwd} + newUser.EncodePasswd() + if authUser.Passwd != newUser.Passwd { + ctx.Handle(401, "no basic auth and digit auth", nil) + return + } + + var tp = models.AU_WRITABLE + if isPull { + tp = models.AU_READABLE + } + + has, err := models.HasAccess(authUsername, username+"/"+reponame, tp) + if err != nil || !has { + ctx.Handle(401, "no basic auth and digit auth", nil) + return + } } dir := models.RepoPath(username, reponame) From ce350a737a63aeb4e2ca5924adf28862a6a6cfb1 Mon Sep 17 00:00:00 2001 From: skyblue Date: Sat, 5 Apr 2014 22:46:32 +0800 Subject: [PATCH 04/24] update models, add licence in start.sh --- models/models.go | 17 +++++++++++------ start.sh | 4 ++++ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/models/models.go b/models/models.go index 384f1fc4..0dc4d51e 100644 --- a/models/models.go +++ b/models/models.go @@ -18,7 +18,9 @@ import ( ) var ( - orm *xorm.Engine + orm *xorm.Engine + tables []interface{} + HasEngine bool DbCfg struct { @@ -28,6 +30,11 @@ var ( UseSQLite3 bool ) +func init() { + tables = append(tables, new(User), new(PublicKey), new(Repository), new(Watch), + new(Action), new(Access), new(Issue), new(Comment)) +} + func LoadModelsConfig() { DbCfg.Type = base.Cfg.MustValue("database", "DB_TYPE") if DbCfg.Type == "sqlite3" { @@ -58,9 +65,7 @@ func NewTestEngine(x *xorm.Engine) (err error) { if err != nil { return fmt.Errorf("models.init(fail to conntect database): %v\n", err) } - - return x.Sync(new(User), new(PublicKey), new(Repository), new(Watch), - new(Action), new(Access), new(Issue), new(Comment)) + return x.Sync(tables...) } func SetEngine() (err error) { @@ -102,8 +107,8 @@ func SetEngine() (err error) { func NewEngine() (err error) { if err = SetEngine(); err != nil { return err - } else if err = orm.Sync(new(User), new(PublicKey), new(Repository), new(Watch), - new(Action), new(Access), new(Issue), new(Comment)); err != nil { + } + if err = orm.Sync(tables...); err != nil { return fmt.Errorf("sync database struct error: %v\n", err) } return nil diff --git a/start.sh b/start.sh index 331d340c..b0c9af50 100755 --- a/start.sh +++ b/start.sh @@ -1,5 +1,9 @@ #!/bin/bash - # +# 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. +# # start gogs web # cd "$(dirname $0)" From 3ebc9b991a70e10c4b2c6319c1ff6195c0d75a17 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sat, 5 Apr 2014 11:22:14 -0400 Subject: [PATCH 05/24] Use gogits/session for oauth2 --- .gopmfile | 42 +++++++++++++-------------- README.md | 4 +-- README_ZH.md | 4 +-- gogs.go | 2 +- models/publickey.go | 2 +- modules/oauth2/oauth2.go | 61 +++++++++++++++++++++------------------- routers/install.go | 1 + web.go | 23 +++++++-------- 8 files changed, 69 insertions(+), 70 deletions(-) diff --git a/.gopmfile b/.gopmfile index ae92d45e..d3f0b3ca 100644 --- a/.gopmfile +++ b/.gopmfile @@ -1,28 +1,26 @@ [target] -path=github.com/gogits/gogs +path = github.com/gogits/gogs [deps] -github.com/codegangsta/cli= -github.com/go-martini/martini= -github.com/Unknwon/com= -github.com/Unknwon/cae= -github.com/Unknwon/goconfig= -github.com/dchest/scrypt= -github.com/nfnt/resize= -github.com/lunny/xorm= -github.com/go-sql-driver/mysql= -github.com/lib/pq= -github.com/gogits/logs= -github.com/gogits/binding= -github.com/gogits/git= -github.com/gogits/gfm= -github.com/gogits/cache= -github.com/gogits/session= -github.com/gogits/webdav= -github.com/martini-contrib/oauth2= -github.com/martini-contrib/sessions= -code.google.com/p/goauth2= +github.com/codegangsta/cli = +github.com/go-martini/martini = +github.com/Unknwon/com = +github.com/Unknwon/cae = +github.com/Unknwon/goconfig = +github.com/dchest/scrypt = +github.com/nfnt/resize = +github.com/lunny/xorm = +github.com/go-sql-driver/mysql = +github.com/lib/pq = +github.com/gogits/logs = +github.com/gogits/binding = +github.com/gogits/git = +github.com/gogits/gfm = +github.com/gogits/cache = +github.com/gogits/session = +github.com/gogits/webdav = +code.google.com/p/goauth2 = [res] -include=templates|public|conf +include = templates|public|conf diff --git a/README.md b/README.md index 6061f5a7..ede1894a 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Gogs(Go Git Service) is a Self Hosted Git Service in the Go Programming Language ![Demo](http://gowalker.org/public/gogs_demo.gif) -##### Current version: 0.2.0 Alpha +##### Current version: 0.2.1 Alpha #### Due to testing purpose, data of [try.gogits.org](http://try.gogits.org) has been reset in March 29, 2014 and will reset multiple times after. Please do NOT put your important data on the site. @@ -31,7 +31,7 @@ More importantly, Gogs only needs one binary to setup your own project hosting o - Activity timeline - SSH/HTTPS(Clone only) protocol support. - Register/delete/rename account. -- Create/delete/watch/rename public repository. +- Create/delete/watch/rename/transfer public repository. - Repository viewer. - Issue tracker. - Gravatar and cache support. diff --git a/README_ZH.md b/README_ZH.md index e66f607a..9b5e4641 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -5,7 +5,7 @@ Gogs(Go Git Service) 是一个由 Go 语言编写的自助 Git 托管服务。 ![Demo](http://gowalker.org/public/gogs_demo.gif) -##### 当前版本:0.2.0 Alpha +##### 当前版本:0.2.1 Alpha ## 开发目的 @@ -25,7 +25,7 @@ Gogs 完全使用 Go 语言来实现对 Git 数据的操作,实现 **零** 依 - 活动时间线 - SSH/HTTPS(仅限 Clone) 协议支持 - 注册/删除/重命名用户 -- 创建/删除/关注/重命名公开仓库 +- 创建/删除/关注/重命名/转移公开仓库 - 仓库浏览器 - Bug 追踪系统 - Gravatar 以及缓存支持 diff --git a/gogs.go b/gogs.go index 8d9159d6..13b9d377 100644 --- a/gogs.go +++ b/gogs.go @@ -19,7 +19,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.2.0.0404 Alpha" +const APP_VER = "0.2.1.0405 Alpha" func init() { base.AppVer = APP_VER diff --git a/models/publickey.go b/models/publickey.go index 426e6b0b..ed47ff20 100644 --- a/models/publickey.go +++ b/models/publickey.go @@ -78,7 +78,7 @@ func init() { type PublicKey struct { Id int64 OwnerId int64 `xorm:"unique(s) index not null"` - Name string `xorm:"unique(s) not null"` //UNIQUE(s) + Name string `xorm:"unique(s) not null"` Fingerprint string Content string `xorm:"TEXT not null"` Created time.Time `xorm:"created"` diff --git a/modules/oauth2/oauth2.go b/modules/oauth2/oauth2.go index 088d65dd..6612b95a 100644 --- a/modules/oauth2/oauth2.go +++ b/modules/oauth2/oauth2.go @@ -26,7 +26,10 @@ import ( "code.google.com/p/goauth2/oauth" "github.com/go-martini/martini" - "github.com/martini-contrib/sessions" + + "github.com/gogits/session" + + "github.com/gogits/gogs/modules/middleware" ) const ( @@ -142,23 +145,23 @@ func NewOAuth2Provider(opts *Options) martini.Handler { Transport: http.DefaultTransport, } - return func(s sessions.Session, c martini.Context, w http.ResponseWriter, r *http.Request) { - if r.Method == "GET" { - switch r.URL.Path { + return func(c martini.Context, ctx *middleware.Context) { + if ctx.Req.Method == "GET" { + switch ctx.Req.URL.Path { case PathLogin: - login(transport, s, w, r) + login(transport, ctx) case PathLogout: - logout(transport, s, w, r) + logout(transport, ctx) case PathCallback: - handleOAuth2Callback(transport, s, w, r) + handleOAuth2Callback(transport, ctx) } } - tk := unmarshallToken(s) + tk := unmarshallToken(ctx.Session) if tk != nil { // check if the access token is expired if tk.IsExpired() && tk.Refresh() == "" { - s.Delete(keyToken) + ctx.Session.Delete(keyToken) tk = nil } } @@ -172,49 +175,49 @@ func NewOAuth2Provider(opts *Options) martini.Handler { // Sample usage: // m.Get("/login-required", oauth2.LoginRequired, func() ... {}) var LoginRequired martini.Handler = func() martini.Handler { - return func(s sessions.Session, c martini.Context, w http.ResponseWriter, r *http.Request) { - token := unmarshallToken(s) + return func(c martini.Context, ctx *middleware.Context) { + token := unmarshallToken(ctx.Session) if token == nil || token.IsExpired() { - next := url.QueryEscape(r.URL.RequestURI()) - http.Redirect(w, r, PathLogin+"?next="+next, codeRedirect) + next := url.QueryEscape(ctx.Req.URL.RequestURI()) + ctx.Redirect(PathLogin+"?next="+next, codeRedirect) } } }() -func login(t *oauth.Transport, s sessions.Session, w http.ResponseWriter, r *http.Request) { - next := extractPath(r.URL.Query().Get(keyNextPage)) - if s.Get(keyToken) == nil { +func login(t *oauth.Transport, ctx *middleware.Context) { + next := extractPath(ctx.Req.URL.Query().Get(keyNextPage)) + if ctx.Session.Get(keyToken) == nil { // User is not logged in. - http.Redirect(w, r, t.Config.AuthCodeURL(next), codeRedirect) + ctx.Redirect(t.Config.AuthCodeURL(next), codeRedirect) return } // No need to login, redirect to the next page. - http.Redirect(w, r, next, codeRedirect) + ctx.Redirect(next, codeRedirect) } -func logout(t *oauth.Transport, s sessions.Session, w http.ResponseWriter, r *http.Request) { - next := extractPath(r.URL.Query().Get(keyNextPage)) - s.Delete(keyToken) - http.Redirect(w, r, next, codeRedirect) +func logout(t *oauth.Transport, ctx *middleware.Context) { + next := extractPath(ctx.Req.URL.Query().Get(keyNextPage)) + ctx.Session.Delete(keyToken) + ctx.Redirect(next, codeRedirect) } -func handleOAuth2Callback(t *oauth.Transport, s sessions.Session, w http.ResponseWriter, r *http.Request) { - next := extractPath(r.URL.Query().Get("state")) - code := r.URL.Query().Get("code") +func handleOAuth2Callback(t *oauth.Transport, ctx *middleware.Context) { + next := extractPath(ctx.Req.URL.Query().Get("state")) + code := ctx.Req.URL.Query().Get("code") tk, err := t.Exchange(code) if err != nil { // Pass the error message, or allow dev to provide its own // error handler. - http.Redirect(w, r, PathError, codeRedirect) + ctx.Redirect(PathError, codeRedirect) return } // Store the credentials in the session. val, _ := json.Marshal(tk) - s.Set(keyToken, val) - http.Redirect(w, r, next, codeRedirect) + ctx.Session.Set(keyToken, val) + ctx.Redirect(next, codeRedirect) } -func unmarshallToken(s sessions.Session) (t *token) { +func unmarshallToken(s session.SessionStore) (t *token) { if s.Get(keyToken) == nil { return } diff --git a/routers/install.go b/routers/install.go index 032af480..48c1b5e1 100644 --- a/routers/install.go +++ b/routers/install.go @@ -183,6 +183,7 @@ func Install(ctx *middleware.Context, form auth.InstallForm) { if _, err := models.RegisterUser(&models.User{Name: form.AdminName, Email: form.AdminEmail, Passwd: form.AdminPasswd, IsAdmin: true, IsActive: true}); err != nil { if err != models.ErrUserAlreadyExist { + base.InstallLock = false ctx.RenderWithErr("Admin account setting is invalid: "+err.Error(), "install", &form) return } diff --git a/web.go b/web.go index 18e48b84..0594d8e6 100644 --- a/web.go +++ b/web.go @@ -11,8 +11,6 @@ import ( "github.com/codegangsta/cli" "github.com/go-martini/martini" - // "github.com/martini-contrib/oauth2" - // "github.com/martini-contrib/sessions" "github.com/gogits/binding" @@ -21,6 +19,7 @@ import ( "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/middleware" + "github.com/gogits/gogs/modules/oauth2" "github.com/gogits/gogs/routers" "github.com/gogits/gogs/routers/admin" "github.com/gogits/gogs/routers/api/v1" @@ -59,19 +58,17 @@ func runWeb(*cli.Context) { // Middlewares. m.Use(middleware.Renderer(middleware.RenderOptions{Funcs: []template.FuncMap{base.TemplateFuncs}})) - - // scope := "https://api.github.com/user" - // oauth2.PathCallback = "/oauth2callback" - // m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123")))) - // m.Use(oauth2.Github(&oauth2.Options{ - // ClientId: "09383403ff2dc16daaa1", - // ClientSecret: "5f6e7101d30b77952aab22b75eadae17551ea6b5", - // RedirectURL: base.AppUrl + oauth2.PathCallback, - // Scopes: []string{scope}, - // })) - m.Use(middleware.InitContext()) + scope := "https://api.github.com/user" + oauth2.PathCallback = "/oauth2callback" + m.Use(oauth2.Github(&oauth2.Options{ + ClientId: "09383403ff2dc16daaa1", + ClientSecret: "5f6e7101d30b77952aab22b75eadae17551ea6b5", + RedirectURL: base.AppUrl + oauth2.PathCallback, + Scopes: []string{scope}, + })) + reqSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true}) ignSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: base.Service.RequireSignInView}) reqSignOut := middleware.Toggle(&middleware.ToggleOptions{SignOutRequire: true}) From b7c3b0cc73ad8721e2eec59d018a91850ba7f750 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sat, 5 Apr 2014 12:32:34 -0400 Subject: [PATCH 06/24] Add reset password, fix #58 --- models/user.go | 15 +++++ modules/base/template.go | 4 ++ modules/mailer/mail.go | 22 ++++++- routers/user/user.go | 84 ++++++++++++++++++++++++- templates/mail/auth/reset_passwd.tmpl | 33 ++++++++++ templates/mail/auth/reset_password.html | 25 -------- templates/user/forgot_passwd.tmpl | 30 +++++++++ templates/user/reset_passwd.tmpl | 26 ++++++++ templates/user/signin.tmpl | 2 +- web.go | 2 + 10 files changed, 214 insertions(+), 29 deletions(-) create mode 100644 templates/mail/auth/reset_passwd.tmpl delete mode 100644 templates/mail/auth/reset_password.html create mode 100644 templates/user/forgot_passwd.tmpl create mode 100644 templates/user/reset_passwd.tmpl diff --git a/models/user.go b/models/user.go index 1ec3b295..2196eae8 100644 --- a/models/user.go +++ b/models/user.go @@ -367,6 +367,21 @@ func GetUserByName(name string) (*User, error) { return user, nil } +// GetUserByEmail returns the user object by given e-mail if exists. +func GetUserByEmail(email string) (*User, error) { + if len(email) == 0 { + return nil, ErrUserNotExist + } + user := &User{Email: strings.ToLower(email)} + has, err := orm.Get(user) + if err != nil { + return nil, err + } else if !has { + return nil, ErrUserNotExist + } + return user, nil +} + // LoginUserPlain validates user by raw user name and password. func LoginUserPlain(name, passwd string) (*User, error) { user := User{LowerName: strings.ToLower(name), Passwd: passwd} diff --git a/modules/base/template.go b/modules/base/template.go index dfcae931..56b77a5d 100644 --- a/modules/base/template.go +++ b/modules/base/template.go @@ -67,6 +67,10 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{ "DateFormat": DateFormat, "List": List, "Mail2Domain": func(mail string) string { + if !strings.Contains(mail, "@") { + return "try.gogits.org" + } + suffix := strings.SplitN(mail, "@", 2)[1] domain, ok := mailDomains[suffix] if !ok { diff --git a/modules/mailer/mail.go b/modules/mailer/mail.go index b99fc8fd..eee6b916 100644 --- a/modules/mailer/mail.go +++ b/modules/mailer/mail.go @@ -86,7 +86,27 @@ func SendActiveMail(r *middleware.Render, user *models.User) { } msg := NewMailMessage([]string{user.Email}, subject, body) - msg.Info = fmt.Sprintf("UID: %d, send email verify mail", user.Id) + msg.Info = fmt.Sprintf("UID: %d, send active mail", user.Id) + + SendAsync(&msg) +} + +// Send reset password email. +func SendResetPasswdMail(r *middleware.Render, user *models.User) { + code := CreateUserActiveCode(user, nil) + + subject := "Reset your password" + + data := GetMailTmplData(user) + data["Code"] = code + body, err := r.HTMLString("mail/auth/reset_passwd", data) + if err != nil { + log.Error("mail.SendResetPasswdMail(fail to render): %v", err) + return + } + + msg := NewMailMessage([]string{user.Email}, subject, body) + msg.Info = fmt.Sprintf("UID: %d, send reset password email", user.Id) SendAsync(&msg) } diff --git a/routers/user/user.go b/routers/user/user.go index 08930e22..872ed0d6 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -403,9 +403,12 @@ func Activate(ctx *middleware.Context) { if user := models.VerifyUserActiveCode(code); user != nil { user.IsActive = true user.Rands = models.GetUserSalt() - models.UpdateUser(user) + if err := models.UpdateUser(user); err != nil { + ctx.Handle(404, "user.Activate", err) + return + } - log.Trace("%s User activated: %s", ctx.Req.RequestURI, user.LowerName) + log.Trace("%s User activated: %s", ctx.Req.RequestURI, user.Name) ctx.Session.Set("userId", user.Id) ctx.Session.Set("userName", user.Name) @@ -416,3 +419,80 @@ func Activate(ctx *middleware.Context) { ctx.Data["IsActivateFailed"] = true ctx.HTML(200, "user/active") } + +func ForgotPasswd(ctx *middleware.Context) { + ctx.Data["Title"] = "Forgot Password" + + if base.MailService == nil { + ctx.Data["IsResetDisable"] = true + ctx.HTML(200, "user/forgot_passwd") + return + } + + ctx.Data["IsResetRequest"] = true + if ctx.Req.Method == "GET" { + ctx.HTML(200, "user/forgot_passwd") + return + } + + email := ctx.Query("email") + u, err := models.GetUserByEmail(email) + if err != nil { + if err == models.ErrUserNotExist { + ctx.RenderWithErr("This e-mail address does not associate to any account.", "user/forgot_passwd", nil) + } else { + ctx.Handle(404, "user.ResetPasswd(check existence)", err) + } + return + } + + mailer.SendResetPasswdMail(ctx.Render, u) + ctx.Data["Email"] = email + ctx.Data["Hours"] = base.Service.ActiveCodeLives / 60 + ctx.Data["IsResetSent"] = true + ctx.HTML(200, "user/forgot_passwd") +} + +func ResetPasswd(ctx *middleware.Context) { + code := ctx.Query("code") + if len(code) == 0 { + ctx.Error(404) + return + } + ctx.Data["Code"] = code + + if ctx.Req.Method == "GET" { + ctx.Data["IsResetForm"] = true + ctx.HTML(200, "user/reset_passwd") + return + } + + if u := models.VerifyUserActiveCode(code); u != nil { + // Validate password length. + passwd := ctx.Query("passwd") + if len(passwd) < 6 || len(passwd) > 30 { + ctx.Data["IsResetForm"] = true + ctx.RenderWithErr("Password length should be in 6 and 30.", "user/reset_passwd", nil) + return + } + + u.Passwd = passwd + if err := u.EncodePasswd(); err != nil { + ctx.Handle(404, "user.ResetPasswd(EncodePasswd)", err) + return + } + + u.Rands = models.GetUserSalt() + if err := models.UpdateUser(u); err != nil { + ctx.Handle(404, "user.ResetPasswd(UpdateUser)", err) + return + } + + log.Trace("%s User password reset: %s", ctx.Req.RequestURI, u.Name) + ctx.Redirect("/user/login") + return + } + + ctx.Data["IsResetFailed"] = true + ctx.HTML(200, "user/reset_passwd") +} diff --git a/templates/mail/auth/reset_passwd.tmpl b/templates/mail/auth/reset_passwd.tmpl new file mode 100644 index 00000000..11861f4e --- /dev/null +++ b/templates/mail/auth/reset_passwd.tmpl @@ -0,0 +1,33 @@ + + + + +{{.User.Name}}, please reset your password + + +
+
+
+
+

{{.AppName}}

+
+
+ Hi {{.User.Name}}, +
+
+

Please click following link to reset your password within {{.ActiveCodeLives}} hours.

+

+ {{.AppUrl}}user/reset_password?code={{.Code}} +

+

Copy and paste it to your browser if the link is not working.

+
+
+
+
+
+ © 2014 Gogs: Go Git Service +
+
+
+ + \ No newline at end of file diff --git a/templates/mail/auth/reset_password.html b/templates/mail/auth/reset_password.html deleted file mode 100644 index 40a9efa8..00000000 --- a/templates/mail/auth/reset_password.html +++ /dev/null @@ -1,25 +0,0 @@ -{{template "mail/base.html" .}} -{{define "title"}} - {{if eq .Lang "zh-CN"}} - {{.User.NickName}},重置账户密码 - {{end}} - {{if eq .Lang "en-US"}} - {{.User.NickName}}, reset your password - {{end}} -{{end}} -{{define "body"}} - {{if eq .Lang "zh-CN"}} -

点击链接重置密码,{{.ResetPwdCodeLives}} 分钟内有效

-

- {{.AppUrl}}reset/{{.Code}} -

-

如果链接点击无反应,请复制到浏览器打开。

- {{end}} - {{if eq .Lang "en-US"}} -

Please click following link to reset your password in {{.ResetPwdCodeLives}} hours

-

- {{.AppUrl}}reset/{{.Code}} -

-

Copy and paste it to your browser if it's not working.

- {{end}} -{{end}} \ No newline at end of file diff --git a/templates/user/forgot_passwd.tmpl b/templates/user/forgot_passwd.tmpl new file mode 100644 index 00000000..ff25406f --- /dev/null +++ b/templates/user/forgot_passwd.tmpl @@ -0,0 +1,30 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +
+
+ {{.CsrfTokenHtml}} +

Reset Your Password

+
{{.ErrorMsg}}
+ {{if .IsResetSent}} +

A confirmation e-mail has been sent to {{.Email}}, please check your inbox within {{.Hours}} hours.

+
+ Sign in to your e-mail + {{else if .IsResetRequest}} +
+ +
+ +
+
+
+
+
+ +
+
+ {{else if .IsResetDisable}} +

Sorry, mail service is not enabled.

+ {{end}} +
+
+{{template "base/footer" .}} \ No newline at end of file diff --git a/templates/user/reset_passwd.tmpl b/templates/user/reset_passwd.tmpl new file mode 100644 index 00000000..9190c7c1 --- /dev/null +++ b/templates/user/reset_passwd.tmpl @@ -0,0 +1,26 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +
+
+ {{.CsrfTokenHtml}} +

Reset Your Pasword

+
{{.ErrorMsg}}
+ {{if .IsResetForm}} +
+ +
+ +
+
+
+
+
+ +
+
+ {{else}} +

Sorry, your confirmation code has been exipired or not valid.

+ {{end}} +
+
+{{template "base/footer" .}} \ No newline at end of file diff --git a/templates/user/signin.tmpl b/templates/user/signin.tmpl index b6c39af1..43f47e41 100644 --- a/templates/user/signin.tmpl +++ b/templates/user/signin.tmpl @@ -33,7 +33,7 @@ diff --git a/web.go b/web.go index 0594d8e6..b5e4af3e 100644 --- a/web.go +++ b/web.go @@ -92,6 +92,8 @@ func runWeb(*cli.Context) { // r.Any("/login/github", user.SocialSignIn) r.Any("/login", binding.BindIgnErr(auth.LogInForm{}), user.SignIn) r.Any("/sign_up", binding.BindIgnErr(auth.RegisterForm{}), user.SignUp) + r.Any("/forget_password", user.ForgotPasswd) + r.Any("/reset_password", user.ResetPasswd) }, reqSignOut) m.Group("/user", func(r martini.Router) { r.Any("/logout", user.SignOut) From 3ede496383bc0e5ad2cb9c5f034890bb6d626b3c Mon Sep 17 00:00:00 2001 From: FuXiaoHei Date: Sun, 6 Apr 2014 14:54:28 +0800 Subject: [PATCH 07/24] add release-new route --- routers/repo/release.go | 8 ++++++++ templates/release/new.tmpl | 15 +++++++++++++++ templates/repo/toolbar.tmpl | 2 +- web.go | 1 + 4 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 templates/release/new.tmpl diff --git a/routers/repo/release.go b/routers/repo/release.go index 8e8b93c9..279fc169 100644 --- a/routers/repo/release.go +++ b/routers/repo/release.go @@ -12,6 +12,7 @@ import ( func Releases(ctx *middleware.Context) { ctx.Data["Title"] = "Releases" ctx.Data["IsRepoToolbarReleases"] = true + ctx.Data["IsRepoReleaseNew"] = false tags, err := models.GetTags(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) if err != nil { ctx.Handle(404, "repo.Releases(GetTags)", err) @@ -20,3 +21,10 @@ func Releases(ctx *middleware.Context) { ctx.Data["Releases"] = tags ctx.HTML(200, "release/list") } + +func ReleasesNew(ctx *middleware.Context) { + ctx.Data["Title"] = "New Release" + ctx.Data["IsRepoToolbarReleases"] = true + ctx.Data["IsRepoReleaseNew"] = true + ctx.HTML(200, "release/new") +} diff --git a/templates/release/new.tmpl b/templates/release/new.tmpl new file mode 100644 index 00000000..a7dc905a --- /dev/null +++ b/templates/release/new.tmpl @@ -0,0 +1,15 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +{{template "repo/nav" .}} +{{template "repo/toolbar" .}} +
+
+

New Release

+
+
+ +
+
+
+
+{{template "base/footer" .}} \ No newline at end of file diff --git a/templates/repo/toolbar.tmpl b/templates/repo/toolbar.tmpl index 54842048..d8ab2621 100644 --- a/templates/repo/toolbar.tmpl +++ b/templates/repo/toolbar.tmpl @@ -15,7 +15,7 @@ {{end}}
  • {{if .Repository.NumReleases}}{{.Repository.NumReleases}} {{end}}Releases
  • {{if .IsRepoToolbarReleases}} -
  • +
  • {{if not .IsRepoReleaseNew}}{{end}}
  • {{end}}