From 3ebc9b991a70e10c4b2c6319c1ff6195c0d75a17 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sat, 5 Apr 2014 11:22:14 -0400 Subject: Use gogits/session for oauth2 --- modules/oauth2/oauth2.go | 61 +++++++++++++++++++++++++----------------------- 1 file changed, 32 insertions(+), 29 deletions(-) (limited to 'modules') 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 } -- cgit v1.2.3 From b7c3b0cc73ad8721e2eec59d018a91850ba7f750 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sat, 5 Apr 2014 12:32:34 -0400 Subject: 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 (limited to 'modules') 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) -- cgit v1.2.3 From 2846ff7d31fc93659a2e90fe869ff51c885decfa Mon Sep 17 00:00:00 2001 From: Unknown Date: Sun, 6 Apr 2014 13:00:20 -0400 Subject: Fix bug related to log --- .gopmfile | 3 ++- bee.json | 2 ++ modules/base/conf.go | 36 ++++++++++++++---------------------- modules/log/log.go | 2 -- routers/install.go | 5 ++--- update.go | 45 ++++++++++++++++++++++----------------------- web.go | 10 ++++------ 7 files changed, 46 insertions(+), 57 deletions(-) (limited to 'modules') diff --git a/.gopmfile b/.gopmfile index d3f0b3ca..9bdca49f 100644 --- a/.gopmfile +++ b/.gopmfile @@ -12,6 +12,8 @@ github.com/nfnt/resize = github.com/lunny/xorm = github.com/go-sql-driver/mysql = github.com/lib/pq = +github.com/qiniu/log = +code.google.com/p/goauth2 = github.com/gogits/logs = github.com/gogits/binding = github.com/gogits/git = @@ -19,7 +21,6 @@ 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 diff --git a/bee.json b/bee.json index 4f7f7a77..ff120f0c 100644 --- a/bee.json +++ b/bee.json @@ -13,6 +13,8 @@ "others": [ "modules", "$GOPATH/src/github.com/gogits/binding", + "$GOPATH/src/github.com/gogits/webdav", + "$GOPATH/src/github.com/gogits/logs", "$GOPATH/src/github.com/gogits/git", "$GOPATH/src/github.com/gogits/gfm" ] diff --git a/modules/base/conf.go b/modules/base/conf.go index 3ebc4ede..4a6eec70 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -14,6 +14,7 @@ import ( "github.com/Unknwon/com" "github.com/Unknwon/goconfig" + qlog "github.com/qiniu/log" "github.com/gogits/cache" "github.com/gogits/session" @@ -105,16 +106,14 @@ func newLogService() { LogMode = Cfg.MustValue("log", "MODE", "console") modeSec := "log." + LogMode if _, err := Cfg.GetSection(modeSec); err != nil { - fmt.Printf("Unknown log mode: %s\n", LogMode) - os.Exit(2) + qlog.Fatalf("Unknown log mode: %s\n", LogMode) } // Log level. levelName := Cfg.MustValue("log."+LogMode, "LEVEL", "Trace") level, ok := logLevels[levelName] if !ok { - fmt.Printf("Unknown log level: %s\n", levelName) - os.Exit(2) + qlog.Fatalf("Unknown log level: %s\n", levelName) } // Generate log configuration. @@ -164,16 +163,14 @@ func newCacheService() { case "redis", "memcache": CacheConfig = fmt.Sprintf(`{"conn":"%s"}`, Cfg.MustValue("cache", "HOST")) default: - fmt.Printf("Unknown cache adapter: %s\n", CacheAdapter) - os.Exit(2) + qlog.Fatalf("Unknown cache adapter: %s\n", CacheAdapter) } var err error Cache, err = cache.NewCache(CacheAdapter, CacheConfig) if err != nil { - fmt.Printf("Init cache system failed, adapter: %s, config: %s, %v\n", + qlog.Fatalf("Init cache system failed, adapter: %s, config: %s, %v\n", CacheAdapter, CacheConfig, err) - os.Exit(2) } log.Info("Cache Service Enabled") @@ -199,9 +196,8 @@ func newSessionService() { var err error SessionManager, err = session.NewManager(SessionProvider, *SessionConfig) if err != nil { - fmt.Printf("Init session system failed, provider: %s, %v\n", + qlog.Fatalf("Init session system failed, provider: %s, %v\n", SessionProvider, err) - os.Exit(2) } log.Info("Session Service Enabled") @@ -246,23 +242,20 @@ func NewConfigContext() { //var err error workDir, err := ExecDir() if err != nil { - fmt.Printf("Fail to get work directory: %s\n", err) - os.Exit(2) + qlog.Fatalf("Fail to get work directory: %s\n", err) } cfgPath := filepath.Join(workDir, "conf/app.ini") Cfg, err = goconfig.LoadConfigFile(cfgPath) if err != nil { - fmt.Printf("Cannot load config file(%s): %v\n", cfgPath, err) - os.Exit(2) + qlog.Fatalf("Cannot load config file(%s): %v\n", cfgPath, err) } Cfg.BlockMode = false cfgPath = filepath.Join(workDir, "custom/conf/app.ini") if com.IsFile(cfgPath) { if err = Cfg.AppendFiles(cfgPath); err != nil { - fmt.Printf("Cannot load config file(%s): %v\n", cfgPath, err) - os.Exit(2) + qlog.Fatalf("Cannot load config file(%s): %v\n", cfgPath, err) } } @@ -281,8 +274,7 @@ func NewConfigContext() { } // Does not check run user when the install lock is off. if InstallLock && RunUser != curUser { - fmt.Printf("Expect user(%s) but current user is: %s\n", RunUser, curUser) - os.Exit(2) + qlog.Fatalf("Expect user(%s) but current user is: %s\n", RunUser, curUser) } LogInRememberDays = Cfg.MustInt("security", "LOGIN_REMEMBER_DAYS") @@ -294,14 +286,14 @@ func NewConfigContext() { // Determine and create root git reposiroty path. homeDir, err := com.HomeDir() if err != nil { - fmt.Printf("Fail to get home directory): %v\n", err) - os.Exit(2) + qlog.Fatalf("Fail to get home directory): %v\n", err) } RepoRootPath = Cfg.MustValue("repository", "ROOT", filepath.Join(homeDir, "git/gogs-repositories")) if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil { - fmt.Printf("Fail to create RepoRootPath(%s): %v\n", RepoRootPath, err) - os.Exit(2) + qlog.Fatalf("Fail to create RepoRootPath(%s): %v\n", RepoRootPath, err) } + + log.Info("%s %s", AppName, AppVer) } func NewServices() { diff --git a/modules/log/log.go b/modules/log/log.go index 65150237..f21897b9 100644 --- a/modules/log/log.go +++ b/modules/log/log.go @@ -21,8 +21,6 @@ func init() { func NewLogger(bufLen int64, mode, config string) { Mode, Config = mode, config logger = logs.NewLogger(bufLen) - logger.EnableFuncCallDepth(true) - logger.SetLogFuncCallDepth(4) logger.SetLogger(mode, config) } diff --git a/routers/install.go b/routers/install.go index 48c1b5e1..1c4e6181 100644 --- a/routers/install.go +++ b/routers/install.go @@ -6,13 +6,13 @@ package routers import ( "errors" - "fmt" "os" "strings" "github.com/Unknwon/goconfig" "github.com/go-martini/martini" "github.com/lunny/xorm" + qlog "github.com/qiniu/log" "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/auth" @@ -43,8 +43,7 @@ func GlobalInit() { if base.InstallLock { if err := models.NewEngine(); err != nil { - fmt.Println(err) - os.Exit(2) + qlog.Fatal(err) } models.HasEngine = true diff --git a/update.go b/update.go index 5ccb72fd..97d92408 100644 --- a/update.go +++ b/update.go @@ -6,7 +6,6 @@ package main import ( "container/list" - "fmt" "os" "os/exec" "path" @@ -14,11 +13,11 @@ import ( "strings" "github.com/codegangsta/cli" + qlog "github.com/qiniu/log" + "github.com/gogits/git" "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/base" - "github.com/gogits/gogs/modules/log" - //"github.com/qiniu/log" ) var CmdUpdate = cli.Command{ @@ -31,11 +30,15 @@ gogs serv provide access auth for repositories`, } func newUpdateLogger(execDir string) { - level := "0" logPath := execDir + "/log/update.log" os.MkdirAll(path.Dir(logPath), os.ModePerm) - log.NewLogger(0, "file", fmt.Sprintf(`{"level":%s,"filename":"%s"}`, level, logPath)) - log.Trace("start logging...") + f, err := os.Open(logPath) + if err != nil { + qlog.Fatal(err) + } + + qlog.SetOutput(f) + qlog.Info("Start logging update...") } // for command: ./gogs update @@ -54,14 +57,12 @@ func runUpdate(c *cli.Context) { args := c.Args() if len(args) != 3 { - log.Error("received less 3 parameters") - return + qlog.Fatal("received less 3 parameters") } refName := args[0] if refName == "" { - log.Error("refName is empty, shouldn't use") - return + qlog.Fatal("refName is empty, shouldn't use") } oldCommitId := args[1] newCommitId := args[2] @@ -69,8 +70,7 @@ func runUpdate(c *cli.Context) { isNew := strings.HasPrefix(oldCommitId, "0000000") if isNew && strings.HasPrefix(newCommitId, "0000000") { - log.Error("old rev and new rev both 000000") - return + qlog.Fatal("old rev and new rev both 000000") } userName := os.Getenv("userName") @@ -86,19 +86,18 @@ func runUpdate(c *cli.Context) { repo, err := git.OpenRepository(f) if err != nil { - log.Error("runUpdate.Open repoId: %v", err) - return + qlog.Fatalf("runUpdate.Open repoId: %v", err) } newOid, err := git.NewOidFromString(newCommitId) if err != nil { - log.Error("runUpdate.Ref repoId: %v", err) + qlog.Fatalf("runUpdate.Ref repoId: %v", err) return } newCommit, err := repo.LookupCommit(newOid) if err != nil { - log.Error("runUpdate.Ref repoId: %v", err) + qlog.Fatalf("runUpdate.Ref repoId: %v", err) return } @@ -107,38 +106,38 @@ func runUpdate(c *cli.Context) { if isNew { l, err = repo.CommitsBefore(newCommit.Id()) if err != nil { - log.Error("Find CommitsBefore erro:", err) + qlog.Fatalf("Find CommitsBefore erro:", err) return } } else { oldOid, err := git.NewOidFromString(oldCommitId) if err != nil { - log.Error("runUpdate.Ref repoId: %v", err) + qlog.Fatalf("runUpdate.Ref repoId: %v", err) return } oldCommit, err := repo.LookupCommit(oldOid) if err != nil { - log.Error("runUpdate.Ref repoId: %v", err) + qlog.Fatalf("runUpdate.Ref repoId: %v", err) return } l = repo.CommitsBetween(newCommit, oldCommit) } if err != nil { - log.Error("runUpdate.Commit repoId: %v", err) + qlog.Fatalf("runUpdate.Commit repoId: %v", err) return } sUserId, err := strconv.Atoi(userId) if err != nil { - log.Error("runUpdate.Parse userId: %v", err) + qlog.Fatalf("runUpdate.Parse userId: %v", err) return } repos, err := models.GetRepositoryByName(int64(sUserId), repoName) if err != nil { - log.Error("runUpdate.GetRepositoryByName userId: %v", err) + qlog.Fatalf("runUpdate.GetRepositoryByName userId: %v", err) return } @@ -163,6 +162,6 @@ func runUpdate(c *cli.Context) { //commits = append(commits, []string{lastCommit.Id().String(), lastCommit.Message()}) if err = models.CommitRepoAction(int64(sUserId), userName, actEmail, repos.Id, repoName, git.BranchName(refName), &base.PushCommits{l.Len(), commits}); err != nil { - log.Error("runUpdate.models.CommitRepoAction: %v", err) + qlog.Fatalf("runUpdate.models.CommitRepoAction: %v", err) } } diff --git a/web.go b/web.go index cab3dfec..00fa72cb 100644 --- a/web.go +++ b/web.go @@ -11,6 +11,7 @@ import ( "github.com/codegangsta/cli" "github.com/go-martini/martini" + qlog "github.com/qiniu/log" "github.com/gogits/binding" @@ -50,9 +51,7 @@ func newMartini() *martini.ClassicMartini { } func runWeb(*cli.Context) { - fmt.Println("Server is running...") routers.GlobalInit() - log.Info("%s %s", base.AppName, base.AppVer) m := newMartini() @@ -147,7 +146,7 @@ func runWeb(*cli.Context) { r.Get("/issues", repo.Issues) r.Get("/issues/:index", repo.ViewIssue) r.Get("/releases", repo.Releases) - r.Any("/releases/new",repo.ReleasesNew) + r.Any("/releases/new", repo.ReleasesNew) r.Get("/pulls", repo.Pulls) r.Get("/branches", repo.Branches) }, ignSignIn, middleware.RepoAssignment(true)) @@ -177,14 +176,13 @@ func runWeb(*cli.Context) { 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 + qlog.Error(err.Error()) } } 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()) + qlog.Error(err.Error()) } } } -- cgit v1.2.3 From 6a16866f4e0908e62c5e5b30e3dc0ef8e4cb0819 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sun, 6 Apr 2014 13:41:58 -0400 Subject: Fix bug related to log --- conf/app.ini | 2 +- modules/base/conf.go | 2 +- serve.go | 3 ++- update.go | 3 ++- 4 files changed, 6 insertions(+), 4 deletions(-) (limited to 'modules') diff --git a/conf/app.ini b/conf/app.ini index f88c750e..43033eaa 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -14,7 +14,7 @@ LICENSES = Apache v2 License|GPL v2|MIT License|Affero GPL|Artistic License 2.0| [server] PROTOCOL = http DOMAIN = localhost -ROOT_URL = %(PROTOCOL)://%(DOMAIN)s:%(HTTP_PORT)s/ +ROOT_URL = %(PROTOCOL)s://%(DOMAIN)s:%(HTTP_PORT)s/ HTTP_ADDR = HTTP_PORT = 3000 CERT_FILE = cert.pem diff --git a/modules/base/conf.go b/modules/base/conf.go index 4a6eec70..4285b523 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -288,7 +288,7 @@ func NewConfigContext() { if err != nil { qlog.Fatalf("Fail to get home directory): %v\n", err) } - RepoRootPath = Cfg.MustValue("repository", "ROOT", filepath.Join(homeDir, "git/gogs-repositories")) + RepoRootPath = Cfg.MustValue("repository", "ROOT", filepath.Join(homeDir, "gogs-repositories")) if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil { qlog.Fatalf("Fail to create RepoRootPath(%s): %v\n", RepoRootPath, err) } diff --git a/serve.go b/serve.go index e7649476..7e00db47 100644 --- a/serve.go +++ b/serve.go @@ -46,7 +46,8 @@ gogs serv provide access auth for repositories`, func newLogger(execDir string) { logPath := execDir + "/log/serv.log" os.MkdirAll(path.Dir(logPath), os.ModePerm) - f, err := os.Open(logPath) + + f, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModePerm) if err != nil { qlog.Fatal(err) } diff --git a/update.go b/update.go index aae2e710..79ce8f52 100644 --- a/update.go +++ b/update.go @@ -32,7 +32,8 @@ gogs serv provide access auth for repositories`, func newUpdateLogger(execDir string) { logPath := execDir + "/log/update.log" os.MkdirAll(path.Dir(logPath), os.ModePerm) - f, err := os.Open(logPath) + + f, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModePerm) if err != nil { qlog.Fatal(err) } -- cgit v1.2.3 From db1fe3483ed2c8c0962ee4395073e0b190310602 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sun, 6 Apr 2014 13:54:48 -0400 Subject: Fix bug related to log --- modules/base/conf.go | 3 +-- update.go | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) (limited to 'modules') diff --git a/modules/base/conf.go b/modules/base/conf.go index 4285b523..0a618ab1 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -150,6 +150,7 @@ func newLogService() { Cfg.MustValue(modeSec, "CONN")) } + log.Info("%s %s", AppName, AppVer) log.NewLogger(Cfg.MustInt64("log", "BUFFER_LEN", 10000), LogMode, LogConfig) log.Info("Log Mode: %s(%s)", strings.Title(LogMode), levelName) } @@ -292,8 +293,6 @@ func NewConfigContext() { if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil { qlog.Fatalf("Fail to create RepoRootPath(%s): %v\n", RepoRootPath, err) } - - log.Info("%s %s", AppName, AppVer) } func NewServices() { diff --git a/update.go b/update.go index 79ce8f52..c9cbb35b 100644 --- a/update.go +++ b/update.go @@ -45,7 +45,7 @@ func newUpdateLogger(execDir string) { // for command: ./gogs update func runUpdate(c *cli.Context) { execDir, _ := base.ExecDir() - newLogger(execDir) + newUpdateLogger(execDir) base.NewConfigContext() models.LoadModelsConfig() -- cgit v1.2.3 From e7c8a3cb8d26da68b09f799585c03970cd243be1 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sun, 6 Apr 2014 16:10:57 -0400 Subject: Add salt for every single user --- .gopmfile | 1 - README.md | 4 ++-- README_ZH.md | 2 +- gogs.go | 2 +- models/user.go | 31 ++++++++++++++++--------------- modules/base/tool.go | 40 ++++++++++++++++++++++++++++++++++++++++ routers/user/setting.go | 7 ++----- routers/user/user.go | 7 ++----- 8 files changed, 64 insertions(+), 30 deletions(-) (limited to 'modules') diff --git a/.gopmfile b/.gopmfile index 9bdca49f..c9fad8a0 100644 --- a/.gopmfile +++ b/.gopmfile @@ -7,7 +7,6 @@ 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 = diff --git a/README.md b/README.md index ede1894a..fe15328b 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,9 @@ 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.1 Alpha +##### Current version: 0.2.2 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. +#### Due to testing purpose, data of [try.gogits.org](http://try.gogits.org) has been reset in April 6, 2014 and will reset multiple times after. Please do NOT put your important data on the site. #### Other language version diff --git a/README_ZH.md b/README_ZH.md index 9b5e4641..015ee0af 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.1 Alpha +##### 当前版本:0.2.2 Alpha ## 开发目的 diff --git a/gogs.go b/gogs.go index 0e48ff7b..e7197482 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.1.0406 Alpha" +const APP_VER = "0.2.2.0406 Alpha" func init() { base.AppVer = APP_VER diff --git a/models/user.go b/models/user.go index 2196eae8..a5a6de09 100644 --- a/models/user.go +++ b/models/user.go @@ -5,6 +5,7 @@ package models import ( + "crypto/sha256" "encoding/hex" "errors" "fmt" @@ -13,8 +14,6 @@ import ( "strings" "time" - "github.com/dchest/scrypt" - "github.com/gogits/git" "github.com/gogits/gogs/modules/base" @@ -62,6 +61,7 @@ type User struct { IsActive bool IsAdmin bool Rands string `xorm:"VARCHAR(10)"` + Salt string `xorm:"VARCHAR(10)"` Created time.Time `xorm:"created"` Updated time.Time `xorm:"updated"` } @@ -89,10 +89,9 @@ func (user *User) NewGitSig() *git.Signature { } // EncodePasswd encodes password to safe format. -func (user *User) EncodePasswd() error { - newPasswd, err := scrypt.Key([]byte(user.Passwd), []byte(base.SecretKey), 16384, 8, 1, 64) +func (user *User) EncodePasswd() { + newPasswd := base.PBKDF2([]byte(user.Passwd), []byte(user.Salt), 10000, 50, sha256.New) user.Passwd = fmt.Sprintf("%x", newPasswd) - return err } // Member represents user is member of organization. @@ -148,9 +147,9 @@ func RegisterUser(user *User) (*User, error) { user.Avatar = base.EncodeMd5(user.Email) user.AvatarEmail = user.Email user.Rands = GetUserSalt() - if err = user.EncodePasswd(); err != nil { - return nil, err - } else if _, err = orm.Insert(user); err != nil { + user.Salt = GetUserSalt() + user.EncodePasswd() + if _, err = orm.Insert(user); err != nil { return nil, err } else if err = os.MkdirAll(UserPath(user.Name), os.ModePerm); err != nil { if _, err := orm.Id(user.Id).Delete(&User{}); err != nil { @@ -384,18 +383,20 @@ func GetUserByEmail(email string) (*User, error) { // LoginUserPlain validates user by raw user name and password. func LoginUserPlain(name, passwd string) (*User, error) { - user := User{LowerName: strings.ToLower(name), Passwd: passwd} - if err := user.EncodePasswd(); err != nil { - return nil, err - } - + user := User{LowerName: strings.ToLower(name)} has, err := orm.Get(&user) if err != nil { return nil, err } else if !has { - err = ErrUserNotExist + return nil, ErrUserNotExist + } + + newUser := &User{Passwd: passwd, Salt: user.Salt} + newUser.EncodePasswd() + if user.Passwd != newUser.Passwd { + return nil, ErrUserNotExist } - return &user, err + return &user, nil } // Follow is connection request for receiving user notifycation. diff --git a/modules/base/tool.go b/modules/base/tool.go index 3946c4b5..f7d1bc2c 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -6,12 +6,14 @@ package base import ( "bytes" + "crypto/hmac" "crypto/md5" "crypto/rand" "crypto/sha1" "encoding/hex" "encoding/json" "fmt" + "hash" "math" "strconv" "strings" @@ -40,6 +42,44 @@ func GetRandomString(n int, alphabets ...byte) string { return string(bytes) } +// http://code.google.com/p/go/source/browse/pbkdf2/pbkdf2.go?repo=crypto +func PBKDF2(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte { + prf := hmac.New(h, password) + hashLen := prf.Size() + numBlocks := (keyLen + hashLen - 1) / hashLen + + var buf [4]byte + dk := make([]byte, 0, numBlocks*hashLen) + U := make([]byte, hashLen) + for block := 1; block <= numBlocks; block++ { + // N.B.: || means concatenation, ^ means XOR + // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter + // U_1 = PRF(password, salt || uint(i)) + prf.Reset() + prf.Write(salt) + buf[0] = byte(block >> 24) + buf[1] = byte(block >> 16) + buf[2] = byte(block >> 8) + buf[3] = byte(block) + prf.Write(buf[:4]) + dk = prf.Sum(dk) + T := dk[len(dk)-hashLen:] + copy(U, T) + + // U_n = PRF(password, U_(n-1)) + for n := 2; n <= iter; n++ { + prf.Reset() + prf.Write(U) + U = U[:0] + U = prf.Sum(U) + for x := range U { + T[x] ^= U[x] + } + } + } + return dk[:keyLen] +} + // verify time limit code func VerifyTimeLimitCode(data string, minutes int, code string) bool { if len(code) <= 18 { diff --git a/routers/user/setting.go b/routers/user/setting.go index 4b6d88a3..ea779e85 100644 --- a/routers/user/setting.go +++ b/routers/user/setting.go @@ -73,11 +73,7 @@ func SettingPassword(ctx *middleware.Context, form auth.UpdatePasswdForm) { user := ctx.User newUser := &models.User{Passwd: form.NewPasswd} - if err := newUser.EncodePasswd(); err != nil { - ctx.Handle(200, "setting.SettingPassword", err) - return - } - + newUser.EncodePasswd() if user.Passwd != newUser.Passwd { ctx.Data["HasError"] = true ctx.Data["ErrorMsg"] = "Old password is not correct" @@ -85,6 +81,7 @@ func SettingPassword(ctx *middleware.Context, form auth.UpdatePasswdForm) { ctx.Data["HasError"] = true ctx.Data["ErrorMsg"] = "New password and re-type password are not same" } else { + newUser.Salt = models.GetUserSalt() user.Passwd = newUser.Passwd if err := models.UpdateUser(user); err != nil { ctx.Handle(200, "setting.SettingPassword", err) diff --git a/routers/user/user.go b/routers/user/user.go index 872ed0d6..12f2bd8c 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -477,12 +477,9 @@ func ResetPasswd(ctx *middleware.Context) { } u.Passwd = passwd - if err := u.EncodePasswd(); err != nil { - ctx.Handle(404, "user.ResetPasswd(EncodePasswd)", err) - return - } - u.Rands = models.GetUserSalt() + u.Salt = models.GetUserSalt() + u.EncodePasswd() if err := models.UpdateUser(u); err != nil { ctx.Handle(404, "user.ResetPasswd(UpdateUser)", err) return -- cgit v1.2.3 From e2fe2209057b90e6c78a84b7c66c3395cf100e30 Mon Sep 17 00:00:00 2001 From: Unknown Date: Mon, 7 Apr 2014 00:47:19 -0400 Subject: Work on comment --- modules/base/markdown.go | 27 +++++++++++- modules/base/template.go | 106 +++++++++++++++++++++++++++++++++++++++++++++++ modules/base/tool.go | 106 ----------------------------------------------- 3 files changed, 131 insertions(+), 108 deletions(-) (limited to 'modules') diff --git a/modules/base/markdown.go b/modules/base/markdown.go index 962e1ae1..828f87de 100644 --- a/modules/base/markdown.go +++ b/modules/base/markdown.go @@ -6,9 +6,11 @@ package base import ( "bytes" + "fmt" "net/http" "path" "path/filepath" + "regexp" "strings" "github.com/gogits/gfm" @@ -87,7 +89,28 @@ func (options *CustomRender) Link(out *bytes.Buffer, link []byte, title []byte, options.Renderer.Link(out, link, title, content) } +var ( + mentionPattern = regexp.MustCompile(`@[0-9a-zA-Z_]{1,}`) + commitPattern = regexp.MustCompile(`[^>]http[s]{0,}.*commit/[0-9a-zA-Z]{1,}`) +) + +func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte { + ms := mentionPattern.FindAll(rawBytes, -1) + for _, m := range ms { + rawBytes = bytes.Replace(rawBytes, m, + []byte(fmt.Sprintf(`%s`, m[1:], m)), -1) + } + ms = commitPattern.FindAll(rawBytes, -1) + for _, m := range ms { + rawBytes = bytes.Replace(rawBytes, m, + []byte(fmt.Sprintf(`%s`, m, m)), -1) + } + return rawBytes +} + func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte { + body := RenderSpecialLink(rawBytes, urlPrefix) + fmt.Println(string(body)) htmlFlags := 0 // htmlFlags |= gfm.HTML_USE_XHTML // htmlFlags |= gfm.HTML_USE_SMARTYPANTS @@ -115,7 +138,7 @@ func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte { extensions |= gfm.EXTENSION_SPACE_HEADERS extensions |= gfm.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK - body := gfm.Markdown(rawBytes, renderer, extensions) - + body = gfm.Markdown(body, renderer, extensions) + fmt.Println(string(body)) return body } diff --git a/modules/base/template.go b/modules/base/template.go index 56b77a5d..6cd8ade6 100644 --- a/modules/base/template.go +++ b/modules/base/template.go @@ -5,7 +5,9 @@ package base import ( + "bytes" "container/list" + "encoding/json" "fmt" "html/template" "strings" @@ -85,3 +87,107 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{ "DiffLineTypeToStr": DiffLineTypeToStr, "ShortSha": ShortSha, } + +type Actioner interface { + GetOpType() int + GetActUserName() string + GetActEmail() string + GetRepoName() string + GetBranch() string + GetContent() string +} + +// ActionIcon accepts a int that represents action operation type +// and returns a icon class name. +func ActionIcon(opType int) string { + switch opType { + case 1: // Create repository. + return "plus-circle" + case 5: // Commit repository. + return "arrow-circle-o-right" + case 6: // Create issue. + return "exclamation-circle" + case 8: // Transfer repository. + return "share" + default: + return "invalid type" + } +} + +const ( + TPL_CREATE_REPO = `%s created repository %s` + TPL_COMMIT_REPO = `%s pushed to %s at %s%s` + TPL_COMMIT_REPO_LI = `
user-avatar %s %s
` + TPL_CREATE_ISSUE = `%s opened issue %s#%s +
user-avatar %s
` + TPL_TRANSFER_REPO = `%s transfered repository %s to %s` +) + +type PushCommit struct { + Sha1 string + Message string + AuthorEmail string + AuthorName string +} + +type PushCommits struct { + Len int + Commits []*PushCommit +} + +// ActionDesc accepts int that represents action operation type +// and returns the description. +func ActionDesc(act Actioner) string { + actUserName := act.GetActUserName() + email := act.GetActEmail() + repoName := act.GetRepoName() + repoLink := actUserName + "/" + repoName + branch := act.GetBranch() + content := act.GetContent() + switch act.GetOpType() { + case 1: // Create repository. + return fmt.Sprintf(TPL_CREATE_REPO, actUserName, actUserName, repoLink, repoName) + case 5: // Commit repository. + var push *PushCommits + if err := json.Unmarshal([]byte(content), &push); err != nil { + return err.Error() + } + buf := bytes.NewBuffer([]byte("\n")) + for _, commit := range push.Commits { + buf.WriteString(fmt.Sprintf(TPL_COMMIT_REPO_LI, AvatarLink(commit.AuthorEmail), repoLink, commit.Sha1, commit.Sha1[:7], commit.Message) + "\n") + } + if push.Len > 3 { + buf.WriteString(fmt.Sprintf(``, actUserName, repoName, branch, push.Len)) + } + return fmt.Sprintf(TPL_COMMIT_REPO, actUserName, actUserName, repoLink, branch, branch, repoLink, repoLink, + buf.String()) + case 6: // Create issue. + infos := strings.SplitN(content, "|", 2) + return fmt.Sprintf(TPL_CREATE_ISSUE, actUserName, actUserName, repoLink, infos[0], repoLink, infos[0], + AvatarLink(email), infos[1]) + case 8: // Transfer repository. + newRepoLink := content + "/" + repoName + return fmt.Sprintf(TPL_TRANSFER_REPO, actUserName, actUserName, repoLink, newRepoLink, newRepoLink) + default: + return "invalid type" + } +} + +func DiffTypeToStr(diffType int) string { + diffTypes := map[int]string{ + 1: "add", 2: "modify", 3: "del", + } + return diffTypes[diffType] +} + +func DiffLineTypeToStr(diffType int) string { + switch diffType { + case 2: + return "add" + case 3: + return "del" + case 4: + return "tag" + } + return "same" +} diff --git a/modules/base/tool.go b/modules/base/tool.go index f7d1bc2c..0f06b3e0 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -5,13 +5,11 @@ package base import ( - "bytes" "crypto/hmac" "crypto/md5" "crypto/rand" "crypto/sha1" "encoding/hex" - "encoding/json" "fmt" "hash" "math" @@ -514,107 +512,3 @@ func (a argInt) Get(i int, args ...int) (r int) { } return } - -type Actioner interface { - GetOpType() int - GetActUserName() string - GetActEmail() string - GetRepoName() string - GetBranch() string - GetContent() string -} - -// ActionIcon accepts a int that represents action operation type -// and returns a icon class name. -func ActionIcon(opType int) string { - switch opType { - case 1: // Create repository. - return "plus-circle" - case 5: // Commit repository. - return "arrow-circle-o-right" - case 6: // Create issue. - return "exclamation-circle" - case 8: // Transfer repository. - return "share" - default: - return "invalid type" - } -} - -const ( - TPL_CREATE_REPO = `%s created repository %s` - TPL_COMMIT_REPO = `%s pushed to %s at %s%s` - TPL_COMMIT_REPO_LI = `
user-avatar %s %s
` - TPL_CREATE_ISSUE = `%s opened issue %s#%s -
user-avatar %s
` - TPL_TRANSFER_REPO = `%s transfered repository %s to %s` -) - -type PushCommit struct { - Sha1 string - Message string - AuthorEmail string - AuthorName string -} - -type PushCommits struct { - Len int - Commits []*PushCommit -} - -// ActionDesc accepts int that represents action operation type -// and returns the description. -func ActionDesc(act Actioner) string { - actUserName := act.GetActUserName() - email := act.GetActEmail() - repoName := act.GetRepoName() - repoLink := actUserName + "/" + repoName - branch := act.GetBranch() - content := act.GetContent() - switch act.GetOpType() { - case 1: // Create repository. - return fmt.Sprintf(TPL_CREATE_REPO, actUserName, actUserName, repoLink, repoName) - case 5: // Commit repository. - var push *PushCommits - if err := json.Unmarshal([]byte(content), &push); err != nil { - return err.Error() - } - buf := bytes.NewBuffer([]byte("\n")) - for _, commit := range push.Commits { - buf.WriteString(fmt.Sprintf(TPL_COMMIT_REPO_LI, AvatarLink(commit.AuthorEmail), repoLink, commit.Sha1, commit.Sha1[:7], commit.Message) + "\n") - } - if push.Len > 3 { - buf.WriteString(fmt.Sprintf(``, actUserName, repoName, branch, push.Len)) - } - return fmt.Sprintf(TPL_COMMIT_REPO, actUserName, actUserName, repoLink, branch, branch, repoLink, repoLink, - buf.String()) - case 6: // Create issue. - infos := strings.SplitN(content, "|", 2) - return fmt.Sprintf(TPL_CREATE_ISSUE, actUserName, actUserName, repoLink, infos[0], repoLink, infos[0], - AvatarLink(email), infos[1]) - case 8: // Transfer repository. - newRepoLink := content + "/" + repoName - return fmt.Sprintf(TPL_TRANSFER_REPO, actUserName, actUserName, repoLink, newRepoLink, newRepoLink) - default: - return "invalid type" - } -} - -func DiffTypeToStr(diffType int) string { - diffTypes := map[int]string{ - 1: "add", 2: "modify", 3: "del", - } - return diffTypes[diffType] -} - -func DiffLineTypeToStr(diffType int) string { - switch diffType { - case 2: - return "add" - case 3: - return "del" - case 4: - return "tag" - } - return "same" -} -- cgit v1.2.3 From 8c9a0494ecb477a641c07be68a9c0cb8fa661d29 Mon Sep 17 00:00:00 2001 From: Unknown Date: Mon, 7 Apr 2014 01:55:22 -0400 Subject: Add @ # commit link detect on all markdown render --- modules/base/markdown.go | 45 ++++++++++++++++++++++++++++++++--------- routers/api/v1/miscellaneous.go | 2 +- routers/repo/issue.go | 8 ++++---- templates/issue/view.tmpl | 2 +- 4 files changed, 41 insertions(+), 16 deletions(-) (limited to 'modules') diff --git a/modules/base/markdown.go b/modules/base/markdown.go index 828f87de..f0992d04 100644 --- a/modules/base/markdown.go +++ b/modules/base/markdown.go @@ -90,8 +90,10 @@ func (options *CustomRender) Link(out *bytes.Buffer, link []byte, title []byte, } var ( - mentionPattern = regexp.MustCompile(`@[0-9a-zA-Z_]{1,}`) - commitPattern = regexp.MustCompile(`[^>]http[s]{0,}.*commit/[0-9a-zA-Z]{1,}`) + mentionPattern = regexp.MustCompile(`@[0-9a-zA-Z_]{1,}`) + commitPattern = regexp.MustCompile(`(\s|^)https?.*commit/[0-9a-zA-Z]+(#+[0-9a-zA-Z-]*)?`) + issueFullPattern = regexp.MustCompile(`(\s|^)https?.*issues/[0-9]+(#+[0-9a-zA-Z-]*)?`) + issueIndexPattern = regexp.MustCompile(`(\s|^)#[0-9]+`) ) func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte { @@ -102,8 +104,31 @@ func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte { } ms = commitPattern.FindAll(rawBytes, -1) for _, m := range ms { - rawBytes = bytes.Replace(rawBytes, m, - []byte(fmt.Sprintf(`%s`, m, m)), -1) + m = bytes.TrimPrefix(m, []byte(" ")) + i := strings.Index(string(m), "commit/") + j := strings.Index(string(m), "#") + if j == -1 { + j = len(m) + } + rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf( + ` %s`, m, ShortSha(string(m[i+7:j])))), -1) + } + ms = issueFullPattern.FindAll(rawBytes, -1) + for _, m := range ms { + m = bytes.TrimPrefix(m, []byte(" ")) + i := strings.Index(string(m), "issues/") + j := strings.Index(string(m), "#") + if j == -1 { + j = len(m) + } + rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf( + ` #%s`, m, ShortSha(string(m[i+7:j])))), -1) + } + ms = issueIndexPattern.FindAll(rawBytes, -1) + for _, m := range ms { + m = bytes.TrimPrefix(m, []byte(" ")) + rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf( + ` %s`, urlPrefix, m[1:], m)), -1) } return rawBytes } @@ -122,10 +147,10 @@ func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte { htmlFlags |= gfm.HTML_GITHUB_BLOCKCODE htmlFlags |= gfm.HTML_OMIT_CONTENTS // htmlFlags |= gfm.HTML_COMPLETE_PAGE - renderer := &CustomRender{ - Renderer: gfm.HtmlRenderer(htmlFlags, "", ""), - urlPrefix: urlPrefix, - } + // renderer := &CustomRender{ + // Renderer: gfm.HtmlRenderer(htmlFlags, "", ""), + // urlPrefix: urlPrefix, + // } // set up the parser extensions := 0 @@ -138,7 +163,7 @@ func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte { extensions |= gfm.EXTENSION_SPACE_HEADERS extensions |= gfm.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK - body = gfm.Markdown(body, renderer, extensions) - fmt.Println(string(body)) + // body = gfm.Markdown(body, renderer, extensions) + // fmt.Println(string(body)) return body } diff --git a/routers/api/v1/miscellaneous.go b/routers/api/v1/miscellaneous.go index 0ff1eb04..babdfce9 100644 --- a/routers/api/v1/miscellaneous.go +++ b/routers/api/v1/miscellaneous.go @@ -13,6 +13,6 @@ func Markdown(ctx *middleware.Context) { content := ctx.Query("content") ctx.Render.JSON(200, map[string]interface{}{ "ok": true, - "content": string(base.RenderMarkdown([]byte(content), "")), + "content": string(base.RenderMarkdown([]byte(content), ctx.Query("repoLink"))), }) } diff --git a/routers/repo/issue.go b/routers/repo/issue.go index be925426..38522e0c 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -147,7 +147,7 @@ func ViewIssue(ctx *middleware.Context, params martini.Params) { return } issue.Poster = u - issue.RenderedContent = string(base.RenderMarkdown([]byte(issue.Content), "")) + issue.RenderedContent = string(base.RenderMarkdown([]byte(issue.Content), ctx.Repo.RepoLink)) // Get comments. comments, err := models.GetIssueComments(issue.Id) @@ -164,7 +164,7 @@ func ViewIssue(ctx *middleware.Context, params martini.Params) { return } comments[i].Poster = u - comments[i].Content = string(base.RenderMarkdown([]byte(comments[i].Content), "")) + comments[i].Content = string(base.RenderMarkdown([]byte(comments[i].Content), ctx.Repo.RepoLink)) } ctx.Data["Title"] = issue.Name @@ -193,7 +193,7 @@ func UpdateIssue(ctx *middleware.Context, params martini.Params, form auth.Creat return } - if ctx.User.Id != issue.PosterId { + if ctx.User.Id != issue.PosterId && !ctx.Repo.IsOwner { ctx.Handle(404, "issue.UpdateIssue", nil) return } @@ -211,7 +211,7 @@ func UpdateIssue(ctx *middleware.Context, params martini.Params, form auth.Creat ctx.JSON(200, map[string]interface{}{ "ok": true, "title": issue.Name, - "content": string(base.RenderMarkdown([]byte(issue.Content), "")), + "content": string(base.RenderMarkdown([]byte(issue.Content), ctx.Repo.RepoLink)), }) } diff --git a/templates/issue/view.tmpl b/templates/issue/view.tmpl index e619451c..16d60d35 100644 --- a/templates/issue/view.tmpl +++ b/templates/issue/view.tmpl @@ -72,7 +72,7 @@
-- cgit v1.2.3 From 9ea9818d3255e5b08293205e278240dece36687d Mon Sep 17 00:00:00 2001 From: Unknown Date: Mon, 7 Apr 2014 12:56:40 -0400 Subject: Fix issue with log in with GitHub but need more error handle after --- conf/app.ini | 8 +++++++ gogs.go | 2 +- models/user.go | 13 +++++++++++ modules/base/conf.go | 53 +++++++++++++++++++++++++++++++++++---------- modules/base/markdown.go | 13 +++++------ modules/mailer/mail.go | 31 ++++++++++++++++++++------ modules/oauth2/oauth2.go | 33 +++++++++++++++++----------- routers/repo/issue.go | 28 +++++++++++++++++++----- routers/user/social.go | 12 ++++++---- routers/user/user.go | 5 +++++ templates/issue/create.tmpl | 2 +- templates/user/signin.tmpl | 5 ++++- web.go | 22 ++++++++++--------- 13 files changed, 167 insertions(+), 60 deletions(-) (limited to 'modules') diff --git a/conf/app.ini b/conf/app.ini index 43033eaa..c9024600 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -72,6 +72,14 @@ FROM = USER = PASSWD = +[oauth] +ENABLED = false + +[oauth.github] +ENABLED = +CLIENT_ID = +CLIENT_SECRET = + [cache] ; Either "memory", "redis", or "memcache", default is "memory" ADAPTER = memory diff --git a/gogs.go b/gogs.go index e7197482..df268980 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.2.0406 Alpha" +const APP_VER = "0.2.2.0407 Alpha" func init() { base.AppVer = APP_VER diff --git a/models/user.go b/models/user.go index a5a6de09..0fcf7243 100644 --- a/models/user.go +++ b/models/user.go @@ -366,6 +366,19 @@ func GetUserByName(name string) (*User, error) { return user, nil } +// GetUserEmailsByNames returns a slice of e-mails corresponds to names. +func GetUserEmailsByNames(names []string) []string { + mails := make([]string, 0, len(names)) + for _, name := range names { + u, err := GetUserByName(name) + if err != nil { + continue + } + mails = append(mails, u.Email) + } + return mails +} + // GetUserByEmail returns the user object by given e-mail if exists. func GetUserByEmail(email string) (*User, error) { if len(email) == 0 { diff --git a/modules/base/conf.go b/modules/base/conf.go index 0a618ab1..ba9c320d 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -22,13 +22,21 @@ import ( "github.com/gogits/gogs/modules/log" ) -// Mailer represents a mail service. +// Mailer represents mail service. type Mailer struct { Name string Host string User, Passwd string } +// Oauther represents oauth service. +type Oauther struct { + GitHub struct { + Enabled bool + ClientId, ClientSecret string + } +} + var ( AppVer string AppName string @@ -45,8 +53,9 @@ var ( CookieUserName string CookieRememberName string - Cfg *goconfig.ConfigFile - MailService *Mailer + Cfg *goconfig.ConfigFile + MailService *Mailer + OauthService *Oauther LogMode string LogConfig string @@ -206,15 +215,17 @@ func newSessionService() { func newMailService() { // Check mailer setting. - if Cfg.MustBool("mailer", "ENABLED") { - MailService = &Mailer{ - Name: Cfg.MustValue("mailer", "NAME", AppName), - Host: Cfg.MustValue("mailer", "HOST"), - User: Cfg.MustValue("mailer", "USER"), - Passwd: Cfg.MustValue("mailer", "PASSWD"), - } - log.Info("Mail Service Enabled") + if !Cfg.MustBool("mailer", "ENABLED") { + return + } + + MailService = &Mailer{ + Name: Cfg.MustValue("mailer", "NAME", AppName), + Host: Cfg.MustValue("mailer", "HOST"), + User: Cfg.MustValue("mailer", "USER"), + Passwd: Cfg.MustValue("mailer", "PASSWD"), } + log.Info("Mail Service Enabled") } func newRegisterMailService() { @@ -239,6 +250,25 @@ func newNotifyMailService() { log.Info("Notify Mail Service Enabled") } +func newOauthService() { + if !Cfg.MustBool("oauth", "ENABLED") { + return + } + + OauthService = &Oauther{} + oauths := make([]string, 0, 10) + + // GitHub. + if Cfg.MustBool("oauth.github", "ENABLED") { + OauthService.GitHub.Enabled = true + OauthService.GitHub.ClientId = Cfg.MustValue("oauth.github", "CLIENT_ID") + OauthService.GitHub.ClientSecret = Cfg.MustValue("oauth.github", "CLIENT_SECRET") + oauths = append(oauths, "GitHub") + } + + log.Info("Oauth Service Enabled %s", oauths) +} + func NewConfigContext() { //var err error workDir, err := ExecDir() @@ -303,4 +333,5 @@ func NewServices() { newMailService() newRegisterMailService() newNotifyMailService() + newOauthService() } diff --git a/modules/base/markdown.go b/modules/base/markdown.go index f0992d04..ce1e2f5b 100644 --- a/modules/base/markdown.go +++ b/modules/base/markdown.go @@ -90,21 +90,21 @@ func (options *CustomRender) Link(out *bytes.Buffer, link []byte, title []byte, } var ( - mentionPattern = regexp.MustCompile(`@[0-9a-zA-Z_]{1,}`) + MentionPattern = regexp.MustCompile(`@[0-9a-zA-Z_]{1,}`) commitPattern = regexp.MustCompile(`(\s|^)https?.*commit/[0-9a-zA-Z]+(#+[0-9a-zA-Z-]*)?`) issueFullPattern = regexp.MustCompile(`(\s|^)https?.*issues/[0-9]+(#+[0-9a-zA-Z-]*)?`) - issueIndexPattern = regexp.MustCompile(`(\s|^)#[0-9]+`) + issueIndexPattern = regexp.MustCompile(`#[0-9]+`) ) func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte { - ms := mentionPattern.FindAll(rawBytes, -1) + ms := MentionPattern.FindAll(rawBytes, -1) for _, m := range ms { rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(`%s`, m[1:], m)), -1) } ms = commitPattern.FindAll(rawBytes, -1) for _, m := range ms { - m = bytes.TrimPrefix(m, []byte(" ")) + m = bytes.TrimSpace(m) i := strings.Index(string(m), "commit/") j := strings.Index(string(m), "#") if j == -1 { @@ -115,7 +115,7 @@ func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte { } ms = issueFullPattern.FindAll(rawBytes, -1) for _, m := range ms { - m = bytes.TrimPrefix(m, []byte(" ")) + m = bytes.TrimSpace(m) i := strings.Index(string(m), "issues/") j := strings.Index(string(m), "#") if j == -1 { @@ -126,9 +126,8 @@ func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte { } ms = issueIndexPattern.FindAll(rawBytes, -1) for _, m := range ms { - m = bytes.TrimPrefix(m, []byte(" ")) rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf( - ` %s`, urlPrefix, m[1:], m)), -1) + `%s`, urlPrefix, m[1:], m)), -1) } return rawBytes } diff --git a/modules/mailer/mail.go b/modules/mailer/mail.go index eee6b916..d2bf1310 100644 --- a/modules/mailer/mail.go +++ b/modules/mailer/mail.go @@ -111,11 +111,11 @@ func SendResetPasswdMail(r *middleware.Render, user *models.User) { SendAsync(&msg) } -// SendNotifyMail sends mail notification of all watchers. -func SendNotifyMail(user, owner *models.User, repo *models.Repository, issue *models.Issue) error { +// SendIssueNotifyMail sends mail notification of all watchers of repository. +func SendIssueNotifyMail(user, owner *models.User, repo *models.Repository, issue *models.Issue) ([]string, error) { watches, err := models.GetWatches(repo.Id) if err != nil { - return errors.New("mail.NotifyWatchers(get watches): " + err.Error()) + return nil, errors.New("mail.NotifyWatchers(get watches): " + err.Error()) } tos := make([]string, 0, len(watches)) @@ -126,20 +126,37 @@ func SendNotifyMail(user, owner *models.User, repo *models.Repository, issue *mo } u, err := models.GetUserById(uid) if err != nil { - return errors.New("mail.NotifyWatchers(get user): " + err.Error()) + return nil, errors.New("mail.NotifyWatchers(get user): " + err.Error()) } tos = append(tos, u.Email) } if len(tos) == 0 { - return nil + return tos, nil } subject := fmt.Sprintf("[%s] %s", repo.Name, issue.Name) content := fmt.Sprintf("%s
-
View it on Gogs.", - issue.Content, base.AppUrl, owner.Name, repo.Name, issue.Index) + base.RenderSpecialLink([]byte(issue.Content), owner.Name+"/"+repo.Name), + base.AppUrl, owner.Name, repo.Name, issue.Index) + msg := NewMailMessageFrom(tos, user.Name, subject, content) + msg.Info = fmt.Sprintf("Subject: %s, send issue notify emails", subject) + SendAsync(&msg) + return tos, nil +} + +// SendIssueMentionMail sends mail notification for who are mentioned in issue. +func SendIssueMentionMail(user, owner *models.User, repo *models.Repository, issue *models.Issue, tos []string) error { + if len(tos) == 0 { + return nil + } + + issueLink := fmt.Sprintf("%s%s/%s/issues/%d", base.AppUrl, owner.Name, repo.Name, issue.Index) + body := fmt.Sprintf(`%s mentioned you.`) + subject := fmt.Sprintf("[%s] %s", repo.Name, issue.Name) + content := fmt.Sprintf("%s
-
View it on Gogs.", body, issueLink) msg := NewMailMessageFrom(tos, user.Name, subject, content) - msg.Info = fmt.Sprintf("Subject: %s, send notify emails", subject) + msg.Info = fmt.Sprintf("Subject: %s, send issue mention emails", subject) SendAsync(&msg) return nil } diff --git a/modules/oauth2/oauth2.go b/modules/oauth2/oauth2.go index 6612b95a..180c52ca 100644 --- a/modules/oauth2/oauth2.go +++ b/modules/oauth2/oauth2.go @@ -29,13 +29,13 @@ import ( "github.com/gogits/session" + "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/middleware" ) const ( - codeRedirect = 302 - keyToken = "oauth2_token" - keyNextPage = "next" + keyToken = "oauth2_token" + keyNextPage = "next" ) var ( @@ -179,42 +179,49 @@ var LoginRequired martini.Handler = func() martini.Handler { token := unmarshallToken(ctx.Session) if token == nil || token.IsExpired() { next := url.QueryEscape(ctx.Req.URL.RequestURI()) - ctx.Redirect(PathLogin+"?next="+next, codeRedirect) + ctx.Redirect(PathLogin + "?next=" + next) + return } } }() func login(t *oauth.Transport, ctx *middleware.Context) { - next := extractPath(ctx.Req.URL.Query().Get(keyNextPage)) + next := extractPath(ctx.Query(keyNextPage)) if ctx.Session.Get(keyToken) == nil { // User is not logged in. - ctx.Redirect(t.Config.AuthCodeURL(next), codeRedirect) + ctx.Redirect(t.Config.AuthCodeURL(next)) return } // No need to login, redirect to the next page. - ctx.Redirect(next, codeRedirect) + ctx.Redirect(next) } func logout(t *oauth.Transport, ctx *middleware.Context) { - next := extractPath(ctx.Req.URL.Query().Get(keyNextPage)) + next := extractPath(ctx.Query(keyNextPage)) ctx.Session.Delete(keyToken) - ctx.Redirect(next, codeRedirect) + ctx.Redirect(next) } func handleOAuth2Callback(t *oauth.Transport, ctx *middleware.Context) { - next := extractPath(ctx.Req.URL.Query().Get("state")) - code := ctx.Req.URL.Query().Get("code") + if errMsg := ctx.Query("error_description"); len(errMsg) > 0 { + log.Error("oauth2.handleOAuth2Callback: %s", errMsg) + return + } + + next := extractPath(ctx.Query("state")) + code := ctx.Query("code") tk, err := t.Exchange(code) if err != nil { // Pass the error message, or allow dev to provide its own // error handler. - ctx.Redirect(PathError, codeRedirect) + log.Error("oauth2.handleOAuth2Callback(token.Exchange): %v", err) + // ctx.Redirect(PathError) return } // Store the credentials in the session. val, _ := json.Marshal(tk) ctx.Session.Set(keyToken, val) - ctx.Redirect(next, codeRedirect) + ctx.Redirect(next) } func unmarshallToken(s session.SessionStore) (t *token) { diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 38522e0c..9688fd4d 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -9,6 +9,7 @@ import ( "net/url" "strings" + "github.com/Unknwon/com" "github.com/go-martini/martini" "github.com/gogits/gogs/models" @@ -99,7 +100,7 @@ func CreateIssue(ctx *middleware.Context, params martini.Params, form auth.Creat issue, err := models.CreateIssue(ctx.User.Id, ctx.Repo.Repository.Id, form.MilestoneId, form.AssigneeId, ctx.Repo.Repository.NumIssues, form.IssueName, form.Labels, form.Content, false) if err != nil { - ctx.Handle(200, "issue.CreateIssue", err) + ctx.Handle(200, "issue.CreateIssue(CreateIssue)", err) return } @@ -107,14 +108,31 @@ func CreateIssue(ctx *middleware.Context, params martini.Params, form auth.Creat if err = models.NotifyWatchers(&models.Action{ActUserId: ctx.User.Id, ActUserName: ctx.User.Name, ActEmail: ctx.User.Email, OpType: models.OP_CREATE_ISSUE, Content: fmt.Sprintf("%d|%s", issue.Index, issue.Name), RepoId: ctx.Repo.Repository.Id, RepoName: ctx.Repo.Repository.Name, RefName: ""}); err != nil { - ctx.Handle(200, "issue.CreateIssue", err) + ctx.Handle(200, "issue.CreateIssue(NotifyWatchers)", err) return } - // Mail watchers. + // Mail watchers and mentions. if base.Service.NotifyMail { - if err = mailer.SendNotifyMail(ctx.User, ctx.Repo.Owner, ctx.Repo.Repository, issue); err != nil { - ctx.Handle(200, "issue.CreateIssue", err) + tos, err := mailer.SendIssueNotifyMail(ctx.User, ctx.Repo.Owner, ctx.Repo.Repository, issue) + if err != nil { + ctx.Handle(200, "issue.CreateIssue(SendIssueNotifyMail)", err) + return + } + + tos = append(tos, ctx.User.LowerName) + ms := base.MentionPattern.FindAllString(issue.Content, -1) + newTos := make([]string, 0, len(ms)) + for _, m := range ms { + if com.IsSliceContainsStr(tos, m[1:]) { + continue + } + + newTos = append(newTos, m[1:]) + } + if err = mailer.SendIssueMentionMail(ctx.User, ctx.Repo.Owner, ctx.Repo.Repository, + issue, models.GetUserEmailsByNames(newTos)); err != nil { + ctx.Handle(200, "issue.CreateIssue(SendIssueMentionMail)", err) return } } diff --git a/routers/user/social.go b/routers/user/social.go index f5577d80..08cfcd83 100644 --- a/routers/user/social.go +++ b/routers/user/social.go @@ -1,20 +1,20 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. + package user import ( "encoding/json" "strconv" + "code.google.com/p/goauth2/oauth" + "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/middleware" - //"github.com/gogits/gogs/modules/oauth2" - - "code.google.com/p/goauth2/oauth" - "github.com/martini-contrib/oauth2" + "github.com/gogits/gogs/modules/oauth2" ) type SocialConnector interface { @@ -80,6 +80,10 @@ func SocialSignIn(ctx *middleware.Context, tokens oauth2.Tokens) { Extra: tokens.ExtraData(), }, } + if len(tokens.Access()) == 0 { + log.Error("empty access") + return + } var err error var u *models.User if err = gh.Update(); err != nil { diff --git a/routers/user/user.go b/routers/user/user.go index 12f2bd8c..f6a39b86 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -78,6 +78,11 @@ func SignIn(ctx *middleware.Context, form auth.LogInForm) { ctx.Data["Title"] = "Log In" if ctx.Req.Method == "GET" { + if base.OauthService != nil { + ctx.Data["OauthEnabled"] = true + ctx.Data["OauthGitHubEnabled"] = base.OauthService.GitHub.Enabled + } + // Check auto-login. userName := ctx.GetCookie(base.CookieUserName) if len(userName) == 0 { diff --git a/templates/issue/create.tmpl b/templates/issue/create.tmpl index 01784cd2..5375040b 100644 --- a/templates/issue/create.tmpl +++ b/templates/issue/create.tmpl @@ -19,7 +19,7 @@
diff --git a/templates/user/signin.tmpl b/templates/user/signin.tmpl index 43f47e41..eb4cb9cc 100644 --- a/templates/user/signin.tmpl +++ b/templates/user/signin.tmpl @@ -43,9 +43,12 @@
+ {{if .OauthEnabled}}
- Register new account +

Log In with Social Accounts

+ {{if .OauthGitHubEnabled}}{{end}}
+ {{end}}
{{template "base/footer" .}} \ No newline at end of file diff --git a/web.go b/web.go index c8fb8dc0..8d53b9e1 100644 --- a/web.go +++ b/web.go @@ -20,16 +20,13 @@ 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/modules/oauth2" "github.com/gogits/gogs/routers" "github.com/gogits/gogs/routers/admin" "github.com/gogits/gogs/routers/api/v1" "github.com/gogits/gogs/routers/dev" "github.com/gogits/gogs/routers/repo" "github.com/gogits/gogs/routers/user" - - "github.com/martini-contrib/oauth2" - "github.com/martini-contrib/sessions" ) var CmdWeb = cli.Command{ @@ -63,12 +60,17 @@ func runWeb(*cli.Context) { m.Use(middleware.InitContext()) scope := "https://api.github.com/user" - oauth2.PathCallback = "/oauth2callback" - m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123")))) + // 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(oauth2.Github(&oauth2.Options{ - ClientId: "09383403ff2dc16daaa1", - ClientSecret: "5f6e7101d30b77952aab22b75eadae17551ea6b5", - RedirectURL: base.AppUrl + oauth2.PathCallback, + ClientId: "ba323b44192e65c7c320", + ClientSecret: "6818ffed53bea5815bf1a6412d1933f25fa10619", + RedirectURL: base.AppUrl + oauth2.PathCallback[1:], Scopes: []string{scope}, })) @@ -92,8 +94,8 @@ func runWeb(*cli.Context) { m.Get("/avatar/:hash", avt.ServeHTTP) m.Group("/user", func(r martini.Router) { - r.Any("/login/github", reqSignOut, oauth2.LoginRequired, user.SocialSignIn) r.Any("/login", binding.BindIgnErr(auth.LogInForm{}), user.SignIn) + r.Any("/login/github", oauth2.LoginRequired, user.SocialSignIn) r.Any("/sign_up", binding.BindIgnErr(auth.RegisterForm{}), user.SignUp) r.Any("/forget_password", user.ForgotPasswd) r.Any("/reset_password", user.ResetPasswd) -- cgit v1.2.3 From 7776f407b6cf7e4897377b73ef6235ecfd9f2a53 Mon Sep 17 00:00:00 2001 From: Unknown Date: Mon, 7 Apr 2014 13:00:59 -0400 Subject: Fix issue with log in with GitHub but need more error handle after --- conf/app.ini | 1 + modules/base/conf.go | 2 ++ web.go | 24 ++++++++++-------------- 3 files changed, 13 insertions(+), 14 deletions(-) (limited to 'modules') diff --git a/conf/app.ini b/conf/app.ini index c9024600..575e18a4 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -79,6 +79,7 @@ ENABLED = false ENABLED = CLIENT_ID = CLIENT_SECRET = +SCOPES = https://api.github.com/user [cache] ; Either "memory", "redis", or "memcache", default is "memory" diff --git a/modules/base/conf.go b/modules/base/conf.go index ba9c320d..69df49dc 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -34,6 +34,7 @@ type Oauther struct { GitHub struct { Enabled bool ClientId, ClientSecret string + Scopes string } } @@ -263,6 +264,7 @@ func newOauthService() { OauthService.GitHub.Enabled = true OauthService.GitHub.ClientId = Cfg.MustValue("oauth.github", "CLIENT_ID") OauthService.GitHub.ClientSecret = Cfg.MustValue("oauth.github", "CLIENT_SECRET") + OauthService.GitHub.Scopes = Cfg.MustValue("oauth.github", "SCOPES") oauths = append(oauths, "GitHub") } diff --git a/web.go b/web.go index 8d53b9e1..b8fa9eb7 100644 --- a/web.go +++ b/web.go @@ -59,20 +59,16 @@ func runWeb(*cli.Context) { m.Use(middleware.Renderer(middleware.RenderOptions{Funcs: []template.FuncMap{base.TemplateFuncs}})) m.Use(middleware.InitContext()) - scope := "https://api.github.com/user" - // 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(oauth2.Github(&oauth2.Options{ - ClientId: "ba323b44192e65c7c320", - ClientSecret: "6818ffed53bea5815bf1a6412d1933f25fa10619", - RedirectURL: base.AppUrl + oauth2.PathCallback[1:], - Scopes: []string{scope}, - })) + if base.OauthService != nil { + if base.OauthService.GitHub.Enabled { + m.Use(oauth2.Github(&oauth2.Options{ + ClientId: base.OauthService.GitHub.ClientId, + ClientSecret: base.OauthService.GitHub.ClientSecret, + RedirectURL: base.AppUrl + oauth2.PathCallback[1:], + Scopes: []string{base.OauthService.GitHub.Scopes}, + })) + } + } reqSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true}) ignSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: base.Service.RequireSignInView}) -- cgit v1.2.3 From 22feddf804c7fbf3418cbbc8e7302da271da4e5a Mon Sep 17 00:00:00 2001 From: Unknown Date: Mon, 7 Apr 2014 14:24:58 -0400 Subject: Fix #66 --- models/repo.go | 14 ++++++++++---- modules/base/markdown.go | 14 +++++++------- 2 files changed, 17 insertions(+), 11 deletions(-) (limited to 'modules') diff --git a/models/repo.go b/models/repo.go index acee6f6a..bb5c3637 100644 --- a/models/repo.go +++ b/models/repo.go @@ -138,11 +138,8 @@ func CreateRepository(user *User, repoName, desc, repoLang, license string, priv IsPrivate: private, IsBare: repoLang == "" && license == "" && !initReadme, } - repoPath := RepoPath(user.Name, repoName) - if err = initRepository(repoPath, user, repo, initReadme, repoLang, license); err != nil { - return nil, err - } + sess := orm.NewSession() defer sess.Close() sess.Begin() @@ -207,6 +204,10 @@ func CreateRepository(user *User, repoName, desc, repoLang, license string, priv log.Error("repo.CreateRepository(WatchRepo): %v", err) } + if err = initRepository(repoPath, user, repo, initReadme, repoLang, license); err != nil { + return nil, err + } + return repo, nil } @@ -332,6 +333,11 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep return nil } + // for update use + os.Setenv("userName", user.Name) + os.Setenv("userId", base.ToStr(user.Id)) + os.Setenv("repoName", repo.Name) + // Apply changes and commit. return initRepoCommit(tmpDir, user.NewGitSig()) } diff --git a/modules/base/markdown.go b/modules/base/markdown.go index ce1e2f5b..1893ccee 100644 --- a/modules/base/markdown.go +++ b/modules/base/markdown.go @@ -133,8 +133,8 @@ func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte { } func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte { - body := RenderSpecialLink(rawBytes, urlPrefix) - fmt.Println(string(body)) + // body := RenderSpecialLink(rawBytes, urlPrefix) + // fmt.Println(string(body)) htmlFlags := 0 // htmlFlags |= gfm.HTML_USE_XHTML // htmlFlags |= gfm.HTML_USE_SMARTYPANTS @@ -146,10 +146,10 @@ func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte { htmlFlags |= gfm.HTML_GITHUB_BLOCKCODE htmlFlags |= gfm.HTML_OMIT_CONTENTS // htmlFlags |= gfm.HTML_COMPLETE_PAGE - // renderer := &CustomRender{ - // Renderer: gfm.HtmlRenderer(htmlFlags, "", ""), - // urlPrefix: urlPrefix, - // } + renderer := &CustomRender{ + Renderer: gfm.HtmlRenderer(htmlFlags, "", ""), + urlPrefix: urlPrefix, + } // set up the parser extensions := 0 @@ -162,7 +162,7 @@ func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte { extensions |= gfm.EXTENSION_SPACE_HEADERS extensions |= gfm.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK - // body = gfm.Markdown(body, renderer, extensions) + body := gfm.Markdown(rawBytes, renderer, extensions) // fmt.Println(string(body)) return body } -- cgit v1.2.3 From 115a349131242201953a3f5693141679049355c6 Mon Sep 17 00:00:00 2001 From: Unknown Date: Tue, 8 Apr 2014 12:41:33 -0400 Subject: Fix #67 --- README.md | 2 +- README_ZH.md | 2 +- gogs.go | 2 +- models/repo.go | 12 ++++++++---- modules/base/conf.go | 1 + modules/base/template.go | 3 +++ routers/install.go | 1 + serve.go | 5 +---- templates/base/head.tmpl | 16 +++++++++++++--- 9 files changed, 30 insertions(+), 14 deletions(-) (limited to 'modules') diff --git a/README.md b/README.md index fe15328b..a4e8901c 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ More importantly, Gogs only needs one binary to setup your own project hosting o ## Features - Activity timeline -- SSH/HTTPS(Clone only) protocol support. +- SSH/HTTP(S) protocol support. - Register/delete/rename account. - Create/delete/watch/rename/transfer public repository. - Repository viewer. diff --git a/README_ZH.md b/README_ZH.md index 015ee0af..2f801541 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -23,7 +23,7 @@ Gogs 完全使用 Go 语言来实现对 Git 数据的操作,实现 **零** 依 ## 功能特性 - 活动时间线 -- SSH/HTTPS(仅限 Clone) 协议支持 +- SSH/HTTP(S) 协议支持 - 注册/删除/重命名用户 - 创建/删除/关注/重命名/转移公开仓库 - 仓库浏览器 diff --git a/gogs.go b/gogs.go index df268980..4616141e 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.2.0407 Alpha" +const APP_VER = "0.2.2.0408 Alpha" func init() { base.AppVer = APP_VER diff --git a/models/repo.go b/models/repo.go index bb5c3637..4f58f407 100644 --- a/models/repo.go +++ b/models/repo.go @@ -261,6 +261,13 @@ func createHookUpdate(hookPath, content string) error { return err } +// SetRepoEnvs sets environment variables for command update. +func SetRepoEnvs(userId int64, userName, repoName string) { + os.Setenv("userId", base.ToStr(userId)) + os.Setenv("userName", userName) + os.Setenv("repoName", repoName) +} + // InitRepository initializes README and .gitignore if needed. func initRepository(f string, user *User, repo *Repository, initReadme bool, repoLang, license string) error { repoPath := RepoPath(user.Name, repo.Name) @@ -333,10 +340,7 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep return nil } - // for update use - os.Setenv("userName", user.Name) - os.Setenv("userId", base.ToStr(user.Id)) - os.Setenv("repoName", repo.Name) + SetRepoEnvs(user.Id, user.Name, repo.Name) // Apply changes and commit. return initRepoCommit(tmpDir, user.NewGitSig()) diff --git a/modules/base/conf.go b/modules/base/conf.go index 69df49dc..871595e4 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -43,6 +43,7 @@ var ( AppName string AppLogo string AppUrl string + IsProdMode bool Domain string SecretKey string RunUser string diff --git a/modules/base/template.go b/modules/base/template.go index 6cd8ade6..5a42107c 100644 --- a/modules/base/template.go +++ b/modules/base/template.go @@ -56,6 +56,9 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{ "AppDomain": func() string { return Domain }, + "IsProdMode": func() bool { + return IsProdMode + }, "LoadTimes": func(startTime time.Time) string { return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms" }, diff --git a/routers/install.go b/routers/install.go index 1c4e6181..b9e8bb29 100644 --- a/routers/install.go +++ b/routers/install.go @@ -27,6 +27,7 @@ func checkRunMode() { switch base.Cfg.MustValue("", "RUN_MODE") { case "prod": martini.Env = martini.Prod + base.IsProdMode = true case "test": martini.Env = martini.Test } diff --git a/serve.go b/serve.go index 7e00db47..3843da61 100644 --- a/serve.go +++ b/serve.go @@ -177,10 +177,7 @@ func runServ(k *cli.Context) { qlog.Fatal("Unknown command") } - // for update use - os.Setenv("userName", user.Name) - os.Setenv("userId", strconv.Itoa(int(user.Id))) - os.Setenv("repoName", repoName) + models.SetRepoEnvs(user.Id, user.Name, repoName) gitcmd := exec.Command(verb, repoPath) gitcmd.Dir = base.RepoRootPath diff --git a/templates/base/head.tmpl b/templates/base/head.tmpl index 7f56ed70..2f88e918 100644 --- a/templates/base/head.tmpl +++ b/templates/base/head.tmpl @@ -11,14 +11,24 @@ + {{if IsProdMode}} + + + + + + {{else}} - - - + {{end}} + + + + + {{if .Title}}{{.Title}} - {{end}}{{AppName}} -- cgit v1.2.3 From a773cf1d876d59ab036ebf8a6843bf78da83531e Mon Sep 17 00:00:00 2001 From: Unknown Date: Wed, 9 Apr 2014 14:11:24 -0400 Subject: Mirror fix --- models/oauth2.go | 20 ++++++++++---------- modules/oauth2/oauth2.go | 15 +++------------ 2 files changed, 13 insertions(+), 22 deletions(-) (limited to 'modules') diff --git a/models/oauth2.go b/models/oauth2.go index 4da98006..cde57b87 100644 --- a/models/oauth2.go +++ b/models/oauth2.go @@ -1,3 +1,7 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + package models import "errors" @@ -16,7 +20,7 @@ var ( type Oauth2 struct { Id int64 - Uid int64 `xorm:"pk"` // userId + Uid int64 // userId User *User `xorm:"-"` Type int `xorm:"pk unique(oauth)"` // twitter,github,google... Identity string `xorm:"pk unique(oauth)"` // id.. @@ -31,18 +35,14 @@ func AddOauth2(oa *Oauth2) (err error) { } func GetOauth2(identity string) (oa *Oauth2, err error) { - oa = &Oauth2{} - oa.Identity = identity - exists, err := orm.Get(oa) + oa = &Oauth2{Identity: identity} + isExist, err := orm.Get(oa) if err != nil { return - } - if !exists { + } else if !isExist { return nil, ErrOauth2RecordNotExists - } - if oa.Uid == 0 { + } else if oa.Uid == 0 { return oa, ErrOauth2NotAssociatedWithUser } - oa.User, err = GetUserById(oa.Uid) - return + return GetUserById(oa.Uid) } diff --git a/modules/oauth2/oauth2.go b/modules/oauth2/oauth2.go index 180c52ca..05ae4606 100644 --- a/modules/oauth2/oauth2.go +++ b/modules/oauth2/oauth2.go @@ -1,16 +1,7 @@ // Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright 2014 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. // Package oauth2 contains Martini handlers to provide // user login via an OAuth 2.0 backend. -- cgit v1.2.3 From 3487f1728530fd2b0a447fe6fd7ef079cb53eed4 Mon Sep 17 00:00:00 2001 From: slene Date: Thu, 10 Apr 2014 08:21:51 +0800 Subject: markdown render html --- modules/base/markdown.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'modules') diff --git a/modules/base/markdown.go b/modules/base/markdown.go index 1893ccee..e1ff3856 100644 --- a/modules/base/markdown.go +++ b/modules/base/markdown.go @@ -140,7 +140,7 @@ func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte { // htmlFlags |= gfm.HTML_USE_SMARTYPANTS // htmlFlags |= gfm.HTML_SMARTYPANTS_FRACTIONS // htmlFlags |= gfm.HTML_SMARTYPANTS_LATEX_DASHES - htmlFlags |= gfm.HTML_SKIP_HTML + // htmlFlags |= gfm.HTML_SKIP_HTML htmlFlags |= gfm.HTML_SKIP_STYLE htmlFlags |= gfm.HTML_SKIP_SCRIPT htmlFlags |= gfm.HTML_GITHUB_BLOCKCODE -- cgit v1.2.3 From 0f9e07de2d232f19d4201ed739b2039e1881ee3f Mon Sep 17 00:00:00 2001 From: slene Date: Thu, 10 Apr 2014 08:34:19 +0800 Subject: fix render bug --- modules/middleware/render.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'modules') diff --git a/modules/middleware/render.go b/modules/middleware/render.go index 98d485af..66289988 100644 --- a/modules/middleware/render.go +++ b/modules/middleware/render.go @@ -146,7 +146,7 @@ func compile(options RenderOptions) *template.Template { tmpl := t.New(filepath.ToSlash(name)) for _, funcs := range options.Funcs { - tmpl.Funcs(funcs) + tmpl = tmpl.Funcs(funcs) } template.Must(tmpl.Funcs(helperFuncs).Parse(string(buf))) -- cgit v1.2.3 From 5d4025cb5a629716bf84f4f5bf3baa97af716df4 Mon Sep 17 00:00:00 2001 From: Unknown Date: Wed, 9 Apr 2014 21:42:25 -0400 Subject: Add go get meta support --- README.md | 2 +- README_ZH.md | 2 +- gogs.go | 2 +- models/repo.go | 1 + models/user.go | 11 ++++++++++- modules/base/markdown.go | 4 ++-- routers/repo/repo.go | 1 + routers/user/user.go | 14 ++++++++++++++ templates/base/head.tmpl | 1 + templates/repo/setting.tmpl | 13 +++++++++++++ templates/repo/single_bare.tmpl | 14 ++++++++++++++ templates/repo/toolbar.tmpl | 2 +- templates/user/forgot_passwd.tmpl | 2 ++ 13 files changed, 62 insertions(+), 7 deletions(-) (limited to 'modules') diff --git a/README.md b/README.md index a4e8901c..619f9a9d 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.2 Alpha +##### Current version: 0.2.3 Alpha #### Due to testing purpose, data of [try.gogits.org](http://try.gogits.org) has been reset in April 6, 2014 and will reset multiple times after. Please do NOT put your important data on the site. diff --git a/README_ZH.md b/README_ZH.md index 2f801541..35a0b763 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.2 Alpha +##### 当前版本:0.2.3 Alpha ## 开发目的 diff --git a/gogs.go b/gogs.go index 45be7e87..29710071 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.2.0409 Alpha" +const APP_VER = "0.2.3.0409 Alpha" func init() { base.AppVer = APP_VER diff --git a/models/repo.go b/models/repo.go index 4f58f407..573e0f4e 100644 --- a/models/repo.go +++ b/models/repo.go @@ -79,6 +79,7 @@ type Repository struct { NumOpenIssues int `xorm:"-"` IsPrivate bool IsBare bool + IsGoget bool Created time.Time `xorm:"created"` Updated time.Time `xorm:"updated"` } diff --git a/models/user.go b/models/user.go index 0fcf7243..b2fddd0a 100644 --- a/models/user.go +++ b/models/user.go @@ -289,11 +289,21 @@ func DeleteUser(user *User) error { // TODO: check issues, other repos' commits + // Delete all followers. + if _, err = orm.Delete(&Follow{FollowId: user.Id}); err != nil { + return err + } + // Delete all feeds. if _, err = orm.Delete(&Action{UserId: user.Id}); err != nil { return err } + // Delete all watches. + if _, err = orm.Delete(&Watch{UserId: user.Id}); err != nil { + return err + } + // Delete all accesses. if _, err = orm.Delete(&Access{UserName: user.LowerName}); err != nil { return err @@ -316,7 +326,6 @@ func DeleteUser(user *User) error { } _, err = orm.Delete(user) - // TODO: delete and update follower information. return err } diff --git a/modules/base/markdown.go b/modules/base/markdown.go index e1ff3856..cc180775 100644 --- a/modules/base/markdown.go +++ b/modules/base/markdown.go @@ -133,7 +133,7 @@ func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte { } func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte { - // body := RenderSpecialLink(rawBytes, urlPrefix) + body := RenderSpecialLink(rawBytes, urlPrefix) // fmt.Println(string(body)) htmlFlags := 0 // htmlFlags |= gfm.HTML_USE_XHTML @@ -162,7 +162,7 @@ func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte { extensions |= gfm.EXTENSION_SPACE_HEADERS extensions |= gfm.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK - body := gfm.Markdown(rawBytes, renderer, extensions) + body = gfm.Markdown(body, renderer, extensions) // fmt.Println(string(body)) return body } diff --git a/routers/repo/repo.go b/routers/repo/repo.go index 32c198f2..aebaa65a 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -427,6 +427,7 @@ func SettingPost(ctx *middleware.Context) { ctx.Repo.Repository.Description = ctx.Query("desc") ctx.Repo.Repository.Website = ctx.Query("site") + ctx.Repo.Repository.IsGoget = ctx.Query("goget") == "on" if err := models.UpdateRepository(ctx.Repo.Repository); err != nil { ctx.Handle(404, "repo.SettingPost(update)", err) return diff --git a/routers/user/user.go b/routers/user/user.go index f6a39b86..084d0bbd 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -396,6 +396,10 @@ func Activate(ctx *middleware.Context) { } else { ctx.Data["Hours"] = base.Service.ActiveCodeLives / 60 mailer.SendActiveMail(ctx.Render, ctx.User) + + if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil { + log.Error("Set cache(MailResendLimit) fail: %v", err) + } } } else { ctx.Data["ServiceNotEnabled"] = true @@ -451,7 +455,17 @@ func ForgotPasswd(ctx *middleware.Context) { return } + if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) { + ctx.Data["ResendLimited"] = true + ctx.HTML(200, "user/forgot_passwd") + return + } + mailer.SendResetPasswdMail(ctx.Render, u) + if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { + log.Error("Set cache(MailResendLimit) fail: %v", err) + } + ctx.Data["Email"] = email ctx.Data["Hours"] = base.Service.ActiveCodeLives / 60 ctx.Data["IsResetSent"] = true diff --git a/templates/base/head.tmpl b/templates/base/head.tmpl index 2f88e918..648eb7c4 100644 --- a/templates/base/head.tmpl +++ b/templates/base/head.tmpl @@ -9,6 +9,7 @@ + {{if .Repository.IsGoget}}{{end}} {{if IsProdMode}} diff --git a/templates/repo/setting.tmpl b/templates/repo/setting.tmpl index 85d08c59..1adf0090 100644 --- a/templates/repo/setting.tmpl +++ b/templates/repo/setting.tmpl @@ -43,6 +43,7 @@ +
+ +
+
+
+ +
+
+
+
diff --git a/templates/repo/single_bare.tmpl b/templates/repo/single_bare.tmpl index fc0a3bd9..3f639153 100644 --- a/templates/repo/single_bare.tmpl +++ b/templates/repo/single_bare.tmpl @@ -9,6 +9,20 @@

Quick Guide

+
+ {{.CsrfTokenHtml}} +

Clone from existing repository

+
+ + + + + + + +
+
+

Clone this repository

diff --git a/templates/repo/toolbar.tmpl b/templates/repo/toolbar.tmpl index d8ab2621..9c137e51 100644 --- a/templates/repo/toolbar.tmpl +++ b/templates/repo/toolbar.tmpl @@ -11,7 +11,7 @@
  • {{if .Repository.NumOpenIssues}}{{.Repository.NumOpenIssues}} {{end}}Issues
  • {{if .IsRepoToolbarIssues}}
  • {{if .IsRepoToolbarIssuesList}} - {{else}}{{end}}
  • + {{end}} {{end}}
  • {{if .Repository.NumReleases}}{{.Repository.NumReleases}} {{end}}Releases
  • {{if .IsRepoToolbarReleases}} diff --git a/templates/user/forgot_passwd.tmpl b/templates/user/forgot_passwd.tmpl index ff25406f..a099ff27 100644 --- a/templates/user/forgot_passwd.tmpl +++ b/templates/user/forgot_passwd.tmpl @@ -24,6 +24,8 @@
    {{else if .IsResetDisable}}

    Sorry, mail service is not enabled.

    + {{else if .ResendLimited}} +

    Sorry, you are sending e-mail too frequently, please wait 3 minutes.

    {{end}}
    -- cgit v1.2.3 From af552596cfd7f6fd05dfc38abaaffad1d7fed654 Mon Sep 17 00:00:00 2001 From: Unknown Date: Thu, 10 Apr 2014 14:37:43 -0400 Subject: Work on form resubmit --- gogs.go | 2 +- modules/middleware/context.go | 36 ++++++++++++++++++-- routers/install.go | 76 +++++++++++++++++++++++++------------------ templates/base/alert.tmpl | 1 + templates/install.tmpl | 2 +- web.go | 5 ++- 6 files changed, 85 insertions(+), 37 deletions(-) create mode 100644 templates/base/alert.tmpl (limited to 'modules') diff --git a/gogs.go b/gogs.go index 29710071..228fe89f 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.3.0409 Alpha" +const APP_VER = "0.2.3.0410 Alpha" func init() { base.AppVer = APP_VER diff --git a/modules/middleware/context.go b/modules/middleware/context.go index 8129b13b..272af330 100644 --- a/modules/middleware/context.go +++ b/modules/middleware/context.go @@ -11,6 +11,7 @@ import ( "fmt" "html/template" "net/http" + "net/url" "strconv" "strings" "time" @@ -34,6 +35,7 @@ type Context struct { p martini.Params Req *http.Request Res http.ResponseWriter + Flash *Flash Session session.SessionStore Cache cache.Cache User *models.User @@ -78,6 +80,7 @@ func (ctx *Context) HasError() bool { if !ok { return false } + ctx.Flash.Error(ctx.Data["ErrorMsg"].(string)) return hasErr.(bool) } @@ -88,8 +91,7 @@ func (ctx *Context) HTML(status int, name string, htmlOpt ...HTMLOptions) { // RenderWithErr used for page has form validation but need to prompt error to users. func (ctx *Context) RenderWithErr(msg, tpl string, form auth.Form) { - ctx.Data["HasError"] = true - ctx.Data["ErrorMsg"] = msg + ctx.Flash.Error(msg) if form != nil { auth.AssignForm(form, ctx.Data) } @@ -239,6 +241,21 @@ func (ctx *Context) CsrfTokenValid() bool { return true } +type Flash struct { + url.Values + ErrorMsg, SuccessMsg string +} + +func (f *Flash) Error(msg string) { + f.Set("error", msg) + f.ErrorMsg = msg +} + +func (f *Flash) Success(msg string) { + f.Set("success", msg) + f.SuccessMsg = msg +} + // 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) { @@ -256,9 +273,24 @@ func InitContext() martini.Handler { // start session ctx.Session = base.SessionManager.SessionStart(res, r) + + ctx.Flash = &Flash{} + // Get flash. + values, err := url.ParseQuery(ctx.GetCookie("gogs_flash")) + if err != nil { + log.Error("InitContext.ParseQuery(flash): %v", err) + } else { + ctx.Flash.Values = values + ctx.Data["Flash"] = ctx.Flash + } + rw := res.(martini.ResponseWriter) rw.Before(func(martini.ResponseWriter) { ctx.Session.SessionRelease(res) + + if flash := ctx.Flash.Encode(); len(flash) > 0 { + ctx.SetCookie("gogs_flash", ctx.Flash.Encode(), -1) + } }) // Get user from session if logined. diff --git a/routers/install.go b/routers/install.go index 5d6c65ef..d3686053 100644 --- a/routers/install.go +++ b/routers/install.go @@ -23,6 +23,10 @@ import ( "github.com/gogits/gogs/modules/middleware" ) +type installRouter int + +var InstallRouter installRouter = 1 + // Check run mode(Default of martini is Dev). func checkRunMode() { switch base.Cfg.MustValue("", "RUN_MODE") { @@ -54,7 +58,7 @@ func GlobalInit() { checkRunMode() } -func Install(ctx *middleware.Context, form auth.InstallForm) { +func (r installRouter) Get(ctx *middleware.Context, form auth.InstallForm) { if base.InstallLock { ctx.Handle(404, "install.Install", errors.New("Installation is prohibited")) return @@ -63,42 +67,49 @@ func Install(ctx *middleware.Context, form auth.InstallForm) { ctx.Data["Title"] = "Install" ctx.Data["PageIsInstall"] = true - if ctx.Req.Method == "GET" { - // Get and assign value to install form. - if len(form.Host) == 0 { - form.Host = models.DbCfg.Host - } - if len(form.User) == 0 { - form.User = models.DbCfg.User - } - if len(form.Passwd) == 0 { - form.Passwd = models.DbCfg.Pwd - } - if len(form.DatabaseName) == 0 { - form.DatabaseName = models.DbCfg.Name - } - if len(form.DatabasePath) == 0 { - form.DatabasePath = models.DbCfg.Path - } + // Get and assign value to install form. + if len(form.Host) == 0 { + form.Host = models.DbCfg.Host + } + if len(form.User) == 0 { + form.User = models.DbCfg.User + } + if len(form.Passwd) == 0 { + form.Passwd = models.DbCfg.Pwd + } + if len(form.DatabaseName) == 0 { + form.DatabaseName = models.DbCfg.Name + } + if len(form.DatabasePath) == 0 { + form.DatabasePath = models.DbCfg.Path + } - if len(form.RepoRootPath) == 0 { - form.RepoRootPath = base.RepoRootPath - } - if len(form.RunUser) == 0 { - form.RunUser = base.RunUser - } - if len(form.Domain) == 0 { - form.Domain = base.Domain - } - if len(form.AppUrl) == 0 { - form.AppUrl = base.AppUrl - } + if len(form.RepoRootPath) == 0 { + form.RepoRootPath = base.RepoRootPath + } + if len(form.RunUser) == 0 { + form.RunUser = base.RunUser + } + if len(form.Domain) == 0 { + form.Domain = base.Domain + } + if len(form.AppUrl) == 0 { + form.AppUrl = base.AppUrl + } - auth.AssignForm(form, ctx.Data) - ctx.HTML(200, "install") + auth.AssignForm(form, ctx.Data) + ctx.HTML(200, "install") +} + +func (r installRouter) Post(ctx *middleware.Context, form auth.InstallForm) { + if base.InstallLock { + ctx.Handle(404, "install.Install", errors.New("Installation is prohibited")) return } + ctx.Data["Title"] = "Install" + ctx.Data["PageIsInstall"] = true + if ctx.HasError() { ctx.HTML(200, "install") return @@ -197,5 +208,6 @@ func Install(ctx *middleware.Context, form auth.InstallForm) { } log.Info("First-time run install finished!") + ctx.Flash.Success("Welcome! We're glad that you choose Gogs, have fun and take care.") ctx.Redirect("/user/login") } diff --git a/templates/base/alert.tmpl b/templates/base/alert.tmpl new file mode 100644 index 00000000..699314ac --- /dev/null +++ b/templates/base/alert.tmpl @@ -0,0 +1 @@ +{{if .Flash.ErrorMsg}}
    {{.Flash.ErrorMsg}}
    {{end}} \ No newline at end of file diff --git a/templates/install.tmpl b/templates/install.tmpl index c70cfa3e..3aa64ccd 100644 --- a/templates/install.tmpl +++ b/templates/install.tmpl @@ -3,7 +3,7 @@
    {{.CsrfTokenHtml}}

    Install Steps For First-time Run

    -
    {{.ErrorMsg}}
    + {{template "base/alert" .}}

    Gogs requires MySQL or PostgreSQL, SQLite3 only available for official binary version

    diff --git a/web.go b/web.go index 1a9c292f..0f61bc21 100644 --- a/web.go +++ b/web.go @@ -74,9 +74,12 @@ func runWeb(*cli.Context) { ignSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: base.Service.RequireSignInView}) reqSignOut := middleware.Toggle(&middleware.ToggleOptions{SignOutRequire: true}) + bindIgnErr := binding.BindIgnErr + // Routers. m.Get("/", ignSignIn, routers.Home) - m.Any("/install", binding.BindIgnErr(auth.InstallForm{}), routers.Install) + m.Get("/install", bindIgnErr(auth.InstallForm{}), routers.InstallRouter.Get) + m.Post("/install", bindIgnErr(auth.InstallForm{}), routers.InstallRouter.Post) m.Get("/issues", reqSignIn, user.Issues) m.Get("/pulls", reqSignIn, user.Pulls) m.Get("/stars", reqSignIn, user.Stars) -- cgit v1.2.3 From 45462662e9bdb001f1cf3d4ca0e4d679757c7642 Mon Sep 17 00:00:00 2001 From: Unknown Date: Thu, 10 Apr 2014 16:36:50 -0400 Subject: Add flash --- gogs.go | 2 +- models/git.go | 8 +- modules/log/log.go | 1 + modules/middleware/context.go | 14 ++-- routers/install.go | 8 +- routers/user/setting.go | 24 ++++-- routers/user/social.go | 7 +- routers/user/user.go | 171 +++++++++++++++++++++++--------------- templates/base/alert.tmpl | 3 +- templates/status/500.tmpl | 4 +- templates/user/delete.tmpl | 5 +- templates/user/forgot_passwd.tmpl | 2 +- templates/user/reset_passwd.tmpl | 2 +- templates/user/setting.tmpl | 2 +- templates/user/signin.tmpl | 2 +- templates/user/signup.tmpl | 2 +- web.go | 43 +++++----- 17 files changed, 175 insertions(+), 125 deletions(-) (limited to 'modules') diff --git a/gogs.go b/gogs.go index 228fe89f..72c506af 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.3.0410 Alpha" +const APP_VER = "0.2.4.0410 Alpha" func init() { base.AppVer = APP_VER diff --git a/models/git.go b/models/git.go index 77b7ef2d..68e13905 100644 --- a/models/git.go +++ b/models/git.go @@ -14,6 +14,8 @@ import ( "path" "strings" + "github.com/Unknwon/com" + "github.com/gogits/git" "github.com/gogits/gogs/modules/base" @@ -163,13 +165,11 @@ func getReposFiles(userName, repoName, commitId string, rpath string) ([]*RepoFi return 0 } - cmd := exec.Command("git", "log", "-1", "--pretty=format:%H", commitId, "--", path.Join(dirname, entry.Name)) - cmd.Dir = repopath - out, err := cmd.Output() + stdout, _, err := com.ExecCmdDir(repopath, "git", "log", "-1", "--pretty=format:%H", commitId, "--", path.Join(dirname, entry.Name)) if err != nil { return 0 } - filecm, err := repo.GetCommit(string(out)) + filecm, err := repo.GetCommit(string(stdout)) if err != nil { return 0 } diff --git a/modules/log/log.go b/modules/log/log.go index f21897b9..636ea787 100644 --- a/modules/log/log.go +++ b/modules/log/log.go @@ -21,6 +21,7 @@ func init() { func NewLogger(bufLen int64, mode, config string) { Mode, Config = mode, config logger = logs.NewLogger(bufLen) + logger.SetLogFuncCallDepth(3) logger.SetLogger(mode, config) } diff --git a/modules/middleware/context.go b/modules/middleware/context.go index 272af330..6ee94b96 100644 --- a/modules/middleware/context.go +++ b/modules/middleware/context.go @@ -91,10 +91,11 @@ func (ctx *Context) HTML(status int, name string, htmlOpt ...HTMLOptions) { // RenderWithErr used for page has form validation but need to prompt error to users. func (ctx *Context) RenderWithErr(msg, tpl string, form auth.Form) { - ctx.Flash.Error(msg) if form != nil { auth.AssignForm(form, ctx.Data) } + ctx.Flash.ErrorMsg = msg + ctx.Data["Flash"] = ctx.Flash ctx.HTML(200, tpl) } @@ -274,22 +275,25 @@ func InitContext() martini.Handler { // start session ctx.Session = base.SessionManager.SessionStart(res, r) - ctx.Flash = &Flash{} // Get flash. values, err := url.ParseQuery(ctx.GetCookie("gogs_flash")) if err != nil { log.Error("InitContext.ParseQuery(flash): %v", err) - } else { - ctx.Flash.Values = values + } else if len(values) > 0 { + ctx.Flash = &Flash{Values: values} + ctx.Flash.ErrorMsg = ctx.Flash.Get("error") + ctx.Flash.SuccessMsg = ctx.Flash.Get("success") ctx.Data["Flash"] = ctx.Flash + ctx.SetCookie("gogs_flash", "", -1) } + ctx.Flash = &Flash{Values: url.Values{}} rw := res.(martini.ResponseWriter) rw.Before(func(martini.ResponseWriter) { ctx.Session.SessionRelease(res) if flash := ctx.Flash.Encode(); len(flash) > 0 { - ctx.SetCookie("gogs_flash", ctx.Flash.Encode(), -1) + ctx.SetCookie("gogs_flash", ctx.Flash.Encode(), 0) } }) diff --git a/routers/install.go b/routers/install.go index d3686053..78ba383d 100644 --- a/routers/install.go +++ b/routers/install.go @@ -23,10 +23,6 @@ import ( "github.com/gogits/gogs/modules/middleware" ) -type installRouter int - -var InstallRouter installRouter = 1 - // Check run mode(Default of martini is Dev). func checkRunMode() { switch base.Cfg.MustValue("", "RUN_MODE") { @@ -58,7 +54,7 @@ func GlobalInit() { checkRunMode() } -func (r installRouter) Get(ctx *middleware.Context, form auth.InstallForm) { +func Install(ctx *middleware.Context, form auth.InstallForm) { if base.InstallLock { ctx.Handle(404, "install.Install", errors.New("Installation is prohibited")) return @@ -101,7 +97,7 @@ func (r installRouter) Get(ctx *middleware.Context, form auth.InstallForm) { ctx.HTML(200, "install") } -func (r installRouter) Post(ctx *middleware.Context, form auth.InstallForm) { +func InstallPost(ctx *middleware.Context, form auth.InstallForm) { if base.InstallLock { ctx.Handle(404, "install.Install", errors.New("Installation is prohibited")) return diff --git a/routers/user/setting.go b/routers/user/setting.go index ea779e85..03da04b9 100644 --- a/routers/user/setting.go +++ b/routers/user/setting.go @@ -14,8 +14,16 @@ import ( "github.com/gogits/gogs/modules/middleware" ) +func Setting(ctx *middleware.Context) { + ctx.Data["Title"] = "Setting" + ctx.Data["PageIsUserSetting"] = true + ctx.Data["IsUserPageSetting"] = true + ctx.Data["Owner"] = ctx.User + ctx.HTML(200, "user/setting") +} + // Render user setting page (email, website modify) -func Setting(ctx *middleware.Context, form auth.UpdateProfileForm) { +func SettingPost(ctx *middleware.Context, form auth.UpdateProfileForm) { ctx.Data["Title"] = "Setting" ctx.Data["PageIsUserSetting"] = true // For navbar arrow. ctx.Data["IsUserPageSetting"] = true // For setting nav highlight. @@ -23,7 +31,7 @@ func Setting(ctx *middleware.Context, form auth.UpdateProfileForm) { user := ctx.User ctx.Data["Owner"] = user - if ctx.Req.Method == "GET" || ctx.HasError() { + if ctx.HasError() { ctx.HTML(200, "user/setting") return } @@ -32,13 +40,13 @@ func Setting(ctx *middleware.Context, form auth.UpdateProfileForm) { if user.Name != form.UserName { isExist, err := models.IsUserExist(form.UserName) if err != nil { - ctx.Handle(404, "user.Setting(update: check existence)", err) + ctx.Handle(500, "user.Setting(update: check existence)", err) return } else if isExist { ctx.RenderWithErr("User name has been taken.", "user/setting", &form) return } else if err = models.ChangeUserName(user, form.UserName); err != nil { - ctx.Handle(404, "user.Setting(change user name)", err) + ctx.Handle(500, "user.Setting(change user name)", err) return } log.Trace("%s User name changed: %s -> %s", ctx.Req.RequestURI, user.Name, form.UserName) @@ -52,13 +60,13 @@ func Setting(ctx *middleware.Context, form auth.UpdateProfileForm) { user.Avatar = base.EncodeMd5(form.Avatar) user.AvatarEmail = form.Avatar if err := models.UpdateUser(user); err != nil { - ctx.Handle(200, "setting.Setting", err) + ctx.Handle(500, "setting.Setting", err) return } - - ctx.Data["IsSuccess"] = true - ctx.HTML(200, "user/setting") log.Trace("%s User setting updated: %s", ctx.Req.RequestURI, ctx.User.LowerName) + + ctx.Flash.Success("Your profile has been successfully updated.") + ctx.Redirect("/user/setting") } func SettingPassword(ctx *middleware.Context, form auth.UpdatePasswdForm) { diff --git a/routers/user/social.go b/routers/user/social.go index b87c313f..2b60ab9f 100644 --- a/routers/user/social.go +++ b/routers/user/social.go @@ -93,11 +93,10 @@ func SocialSignIn(ctx *middleware.Context, tokens oauth2.Tokens) { log.Info("login soc id: %v", socid) return } + config := &oauth.Config{ - //ClientId: base.OauthService.Github.ClientId, - //ClientSecret: base.OauthService.Github.ClientSecret, // FIXME: I don't know why compile error here - ClientId: "09383403ff2dc16daaa1", - ClientSecret: "0e4aa0c3630df396cdcea01a9d45cacf79925fea", + ClientId: base.OauthService.GitHub.ClientId, + ClientSecret: base.OauthService.GitHub.ClientSecret, RedirectURL: strings.TrimSuffix(base.AppUrl, "/") + ctx.Req.URL.RequestURI(), Scope: base.OauthService.GitHub.Scopes, AuthURL: "https://github.com/login/oauth/authorize", diff --git a/routers/user/user.go b/routers/user/user.go index 084d0bbd..37c6baa9 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -74,57 +74,63 @@ func Profile(ctx *middleware.Context, params martini.Params) { ctx.HTML(200, "user/profile") } -func SignIn(ctx *middleware.Context, form auth.LogInForm) { +func SignIn(ctx *middleware.Context) { ctx.Data["Title"] = "Log In" - if ctx.Req.Method == "GET" { - if base.OauthService != nil { - ctx.Data["OauthEnabled"] = true - ctx.Data["OauthGitHubEnabled"] = base.OauthService.GitHub.Enabled - } - - // Check auto-login. - userName := ctx.GetCookie(base.CookieUserName) - if len(userName) == 0 { - ctx.HTML(200, "user/signin") - return - } + if base.OauthService != nil { + ctx.Data["OauthEnabled"] = true + ctx.Data["OauthGitHubEnabled"] = base.OauthService.GitHub.Enabled + } - isSucceed := false - defer func() { - if !isSucceed { - log.Trace("%s auto-login cookie cleared: %s", ctx.Req.RequestURI, userName) - ctx.SetCookie(base.CookieUserName, "", -1) - ctx.SetCookie(base.CookieRememberName, "", -1) - } - }() + // Check auto-login. + userName := ctx.GetCookie(base.CookieUserName) + if len(userName) == 0 { + ctx.HTML(200, "user/signin") + return + } - user, err := models.GetUserByName(userName) - if err != nil { - ctx.HTML(200, "user/signin") - return + isSucceed := false + defer func() { + if !isSucceed { + log.Trace("%s auto-login cookie cleared: %s", ctx.Req.RequestURI, userName) + ctx.SetCookie(base.CookieUserName, "", -1) + ctx.SetCookie(base.CookieRememberName, "", -1) } + }() - secret := base.EncodeMd5(user.Rands + user.Passwd) - value, _ := ctx.GetSecureCookie(secret, base.CookieRememberName) - if value != user.Name { - ctx.HTML(200, "user/signin") - return - } + user, err := models.GetUserByName(userName) + if err != nil { + ctx.HTML(200, "user/signin") + return + } - isSucceed = true - ctx.Session.Set("userId", user.Id) - ctx.Session.Set("userName", user.Name) - redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")) - if len(redirectTo) > 0 { - ctx.SetCookie("redirect_to", "", -1) - ctx.Redirect(redirectTo) - } else { - ctx.Redirect("/") - } + secret := base.EncodeMd5(user.Rands + user.Passwd) + value, _ := ctx.GetSecureCookie(secret, base.CookieRememberName) + if value != user.Name { + ctx.HTML(200, "user/signin") return } + isSucceed = true + ctx.Session.Set("userId", user.Id) + ctx.Session.Set("userName", user.Name) + if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 { + ctx.SetCookie("redirect_to", "", -1) + ctx.Redirect(redirectTo) + return + } + + ctx.Redirect("/") +} + +func SignInPost(ctx *middleware.Context, form auth.LogInForm) { + ctx.Data["Title"] = "Log In" + + if base.OauthService != nil { + ctx.Data["OauthEnabled"] = true + ctx.Data["OauthGitHubEnabled"] = base.OauthService.GitHub.Enabled + } + if ctx.HasError() { ctx.HTML(200, "user/signin") return @@ -138,7 +144,7 @@ func SignIn(ctx *middleware.Context, form auth.LogInForm) { return } - ctx.Handle(200, "user.SignIn", err) + ctx.Handle(500, "user.SignIn", err) return } @@ -151,13 +157,13 @@ func SignIn(ctx *middleware.Context, form auth.LogInForm) { ctx.Session.Set("userId", user.Id) ctx.Session.Set("userName", user.Name) - redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")) - if len(redirectTo) > 0 { + if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 { ctx.SetCookie("redirect_to", "", -1) ctx.Redirect(redirectTo) - } else { - ctx.Redirect("/") + return } + + ctx.Redirect("/") } func SignOut(ctx *middleware.Context) { @@ -168,7 +174,7 @@ func SignOut(ctx *middleware.Context) { ctx.Redirect("/") } -func SignUp(ctx *middleware.Context, form auth.RegisterForm) { +func SignUp(ctx *middleware.Context) { ctx.Data["Title"] = "Sign Up" ctx.Data["PageIsSignUp"] = true @@ -178,8 +184,15 @@ func SignUp(ctx *middleware.Context, form auth.RegisterForm) { return } - if ctx.Req.Method == "GET" { - ctx.HTML(200, "user/signup") + ctx.HTML(200, "user/signup") +} + +func SignUpPost(ctx *middleware.Context, form auth.RegisterForm) { + ctx.Data["Title"] = "Sign Up" + ctx.Data["PageIsSignUp"] = true + + if base.Service.DisenableRegisteration { + ctx.Handle(403, "user.SignUpPost", nil) return } @@ -213,7 +226,7 @@ func SignUp(ctx *middleware.Context, form auth.RegisterForm) { case models.ErrUserNameIllegal: ctx.RenderWithErr(models.ErrRepoNameIllegal.Error(), "user/signup", &form) default: - ctx.Handle(200, "user.SignUp", err) + ctx.Handle(500, "user.SignUp", err) } return } @@ -240,25 +253,28 @@ func Delete(ctx *middleware.Context) { ctx.Data["Title"] = "Delete Account" ctx.Data["PageIsUserSetting"] = true ctx.Data["IsUserPageSettingDelete"] = true + ctx.HTML(200, "user/delete") +} - if ctx.Req.Method == "GET" { - ctx.HTML(200, "user/delete") - return - } +func DeletePost(ctx *middleware.Context) { + ctx.Data["Title"] = "Delete Account" + ctx.Data["PageIsUserSetting"] = true + ctx.Data["IsUserPageSettingDelete"] = true - tmpUser := models.User{Passwd: ctx.Query("password")} + tmpUser := models.User{ + Passwd: ctx.Query("password"), + Salt: ctx.User.Salt, + } tmpUser.EncodePasswd() - if len(tmpUser.Passwd) == 0 || tmpUser.Passwd != ctx.User.Passwd { - ctx.Data["HasError"] = true - ctx.Data["ErrorMsg"] = "Password is not correct. Make sure you are owner of this account." + if tmpUser.Passwd != ctx.User.Passwd { + ctx.Flash.Error("Password is not correct. Make sure you are owner of this account.") } else { if err := models.DeleteUser(ctx.User); err != nil { - ctx.Data["HasError"] = true switch err { case models.ErrUserOwnRepos: - ctx.Data["ErrorMsg"] = "Your account still have ownership of repository, you have to delete or transfer them first." + ctx.Flash.Error("Your account still have ownership of repository, you have to delete or transfer them first.") default: - ctx.Handle(200, "user.Delete", err) + ctx.Handle(500, "user.Delete", err) return } } else { @@ -267,7 +283,7 @@ func Delete(ctx *middleware.Context) { } } - ctx.HTML(200, "user/delete") + ctx.Redirect("/user/delete") } const ( @@ -439,10 +455,17 @@ func ForgotPasswd(ctx *middleware.Context) { } ctx.Data["IsResetRequest"] = true - if ctx.Req.Method == "GET" { - ctx.HTML(200, "user/forgot_passwd") + ctx.HTML(200, "user/forgot_passwd") +} + +func ForgotPasswdPost(ctx *middleware.Context) { + ctx.Data["Title"] = "Forgot Password" + + if base.MailService == nil { + ctx.Handle(403, "user.ForgotPasswdPost", nil) return } + ctx.Data["IsResetRequest"] = true email := ctx.Query("email") u, err := models.GetUserByEmail(email) @@ -450,7 +473,7 @@ func ForgotPasswd(ctx *middleware.Context) { 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) + ctx.Handle(500, "user.ResetPasswd(check existence)", err) } return } @@ -473,6 +496,8 @@ func ForgotPasswd(ctx *middleware.Context) { } func ResetPasswd(ctx *middleware.Context) { + ctx.Data["Title"] = "Reset Password" + code := ctx.Query("code") if len(code) == 0 { ctx.Error(404) @@ -480,11 +505,19 @@ func ResetPasswd(ctx *middleware.Context) { } ctx.Data["Code"] = code - if ctx.Req.Method == "GET" { - ctx.Data["IsResetForm"] = true - ctx.HTML(200, "user/reset_passwd") + ctx.Data["IsResetForm"] = true + ctx.HTML(200, "user/reset_passwd") +} + +func ResetPasswdPost(ctx *middleware.Context) { + ctx.Data["Title"] = "Reset Password" + + code := ctx.Query("code") + if len(code) == 0 { + ctx.Error(404) return } + ctx.Data["Code"] = code if u := models.VerifyUserActiveCode(code); u != nil { // Validate password length. @@ -500,7 +533,7 @@ func ResetPasswd(ctx *middleware.Context) { u.Salt = models.GetUserSalt() u.EncodePasswd() if err := models.UpdateUser(u); err != nil { - ctx.Handle(404, "user.ResetPasswd(UpdateUser)", err) + ctx.Handle(500, "user.ResetPasswd(UpdateUser)", err) return } diff --git a/templates/base/alert.tmpl b/templates/base/alert.tmpl index 699314ac..bb1eb6aa 100644 --- a/templates/base/alert.tmpl +++ b/templates/base/alert.tmpl @@ -1 +1,2 @@ -{{if .Flash.ErrorMsg}}
    {{.Flash.ErrorMsg}}
    {{end}} \ No newline at end of file +{{if .Flash.ErrorMsg}}
    {{.Flash.ErrorMsg}}
    {{end}} +{{if .Flash.SuccessMsg}}
    {{.Flash.SuccessMsg}}
    {{end}} \ No newline at end of file diff --git a/templates/status/500.tmpl b/templates/status/500.tmpl index dd735811..07edd362 100644 --- a/templates/status/500.tmpl +++ b/templates/status/500.tmpl @@ -2,8 +2,8 @@ {{template "base/navbar" .}}

    404

    -
    -

    An error is occurred : {{.ErrorMsg}}

    + {{if .ErrorMsg}}
    +

    An error is occurred : {{.ErrorMsg}}

    {{end}}

    Application Version: {{AppVer}}

    diff --git a/templates/user/delete.tmpl b/templates/user/delete.tmpl index 17c9ea89..39949ee2 100644 --- a/templates/user/delete.tmpl +++ b/templates/user/delete.tmpl @@ -12,13 +12,16 @@
  • Delete Account
  • +

    Delete Account

    -

    {{if not .HasError}}The operation will delete your account permanently. Sorry to see you go, but we know you'll back soon.{{else}}{{.ErrorMsg}}{{end}}

    + {{template "base/alert" .}} + {{if not .Flash.ErrorMsg}}

    The operation will delete your account permanently. Sorry to see you go, but we know you'll back soon.

    {{end}}
    +