From b7c3b0cc73ad8721e2eec59d018a91850ba7f750 Mon Sep 17 00:00:00 2001 From: Unknown <joe2010xtmf@163.com> Date: Sat, 5 Apr 2014 12:32:34 -0400 Subject: [PATCH] Add reset password, fix #58 --- models/user.go | 15 +++++ modules/base/template.go | 4 ++ modules/mailer/mail.go | 22 ++++++- routers/user/user.go | 84 ++++++++++++++++++++++++- templates/mail/auth/reset_passwd.tmpl | 33 ++++++++++ templates/mail/auth/reset_password.html | 25 -------- templates/user/forgot_passwd.tmpl | 30 +++++++++ templates/user/reset_passwd.tmpl | 26 ++++++++ templates/user/signin.tmpl | 2 +- web.go | 2 + 10 files changed, 214 insertions(+), 29 deletions(-) create mode 100644 templates/mail/auth/reset_passwd.tmpl delete mode 100644 templates/mail/auth/reset_password.html create mode 100644 templates/user/forgot_passwd.tmpl create mode 100644 templates/user/reset_passwd.tmpl diff --git a/models/user.go b/models/user.go index 1ec3b29520..2196eae84f 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 dfcae93147..56b77a5d60 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 b99fc8fdfc..eee6b916ca 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 08930e22df..872ed0d600 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 0000000000..11861f4e20 --- /dev/null +++ b/templates/mail/auth/reset_passwd.tmpl @@ -0,0 +1,33 @@ +<!DOCTYPE html> +<html> +<head> +<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> +<title>{{.User.Name}}, please reset your password</title> +</head> +<body style="background:#eee;"> +<div style="color:#333; font:12px/1.5 Tahoma,Arial,sans-serif;; text-shadow:1px 1px #fff; padding:0; margin:0;"> + <div style="width:600px;margin:0 auto; padding:40px 0 20px;"> + <div style="border:1px solid #d9d9d9;border-radius:3px; background:#fff; box-shadow: 0px 2px 5px rgba(0, 0, 0,.05); -webkit-box-shadow: 0px 2px 5px rgba(0, 0, 0,.05);"> + <div style="padding: 20px 15px;"> + <h1 style="font-size:20px; padding:10px 0 20px; margin:0; border-bottom:1px solid #ddd;"><img src="{{.AppUrl}}/{{.AppLogo}}" style="height: 32px; margin-bottom: -10px;"> <a style="color:#333;text-decoration:none;" target="_blank" href="{{.AppUrl}}">{{.AppName}}</a></h1> + <div style="padding:40px 15px;"> + <div style="font-size:16px; padding-bottom:30px; font-weight:bold;"> + Hi <span style="color: #00BFFF;">{{.User.Name}}</span>, + </div> + <div style="font-size:14px; padding:0 15px;"> + <p style="margin:0;padding:0 0 9px 0;">Please click following link to reset your password within <b>{{.ActiveCodeLives}} hours</b>.</p> + <p style="margin:0;padding:0 0 9px 0;"> + <a href="{{.AppUrl}}user/reset_password?code={{.Code}}">{{.AppUrl}}user/reset_password?code={{.Code}}</a> + </p> + <p style="margin:0;padding:0 0 9px 0;">Copy and paste it to your browser if the link is not working.</p> + </div> + </div> + </div> + </div> + <div style="color:#aaa;padding:10px;text-align:center;"> + © 2014 <a style="color:#888;text-decoration:none;" target="_blank" href="http://gogits.org">Gogs: Go Git Service</a> + </div> + </div> +</div> +</body> +</html> \ 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 40a9efa855..0000000000 --- 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"}} - <p style="margin:0;padding:0 0 9px 0;">点击链接重置密码,{{.ResetPwdCodeLives}} 分钟内有效</p> - <p style="margin:0;padding:0 0 9px 0;"> - <a href="{{.AppUrl}}reset/{{.Code}}">{{.AppUrl}}reset/{{.Code}}</a> - </p> - <p style="margin:0;padding:0 0 9px 0;">如果链接点击无反应,请复制到浏览器打开。</p> - {{end}} - {{if eq .Lang "en-US"}} - <p style="margin:0;padding:0 0 9px 0;">Please click following link to reset your password in {{.ResetPwdCodeLives}} hours</p> - <p style="margin:0;padding:0 0 9px 0;"> - <a href="{{.AppUrl}}reset/{{.Code}}">{{.AppUrl}}reset/{{.Code}}</a> - </p> - <p style="margin:0;padding:0 0 9px 0;">Copy and paste it to your browser if it's not working.</p> - {{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 0000000000..ff25406fd0 --- /dev/null +++ b/templates/user/forgot_passwd.tmpl @@ -0,0 +1,30 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +<div id="body" class="container"> + <form action="/user/forget_password" method="post" class="form-horizontal card" id="login-card"> + {{.CsrfTokenHtml}} + <h3>Reset Your Password</h3> + <div class="alert alert-danger form-error{{if .HasError}}{{else}} hidden{{end}}">{{.ErrorMsg}}</div> + {{if .IsResetSent}} + <p>A confirmation e-mail has been sent to <b>{{.Email}}</b>, please check your inbox within {{.Hours}} hours.</p> + <hr/> + <a href="http://{{Mail2Domain .Email}}" class="btn btn-lg btn-success">Sign in to your e-mail</a> + {{else if .IsResetRequest}} + <div class="form-group {{if .Err_Email}}has-error has-feedback{{end}}"> + <label class="col-md-3 control-label">Email: </label> + <div class="col-md-7"> + <input name="email" class="form-control" placeholder="Type your e-mail address" required="required"> + </div> + </div> + <hr/> + <div class="form-group"> + <div class="col-md-offset-4 col-md-6"> + <button type="submit" class="btn btn-lg btn-primary">Click here to send reset confirmation e-mail</button> + </div> + </div> + {{else if .IsResetDisable}} + <p>Sorry, mail service is not enabled.</p> + {{end}} + </form> +</div> +{{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 0000000000..9190c7c13c --- /dev/null +++ b/templates/user/reset_passwd.tmpl @@ -0,0 +1,26 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +<div id="body" class="container"> + <form action="/user/reset_password?code={{.Code}}" method="post" class="form-horizontal card" id="login-card"> + {{.CsrfTokenHtml}} + <h3>Reset Your Pasword</h3> + <div class="alert alert-danger form-error{{if .HasError}}{{else}} hidden{{end}}">{{.ErrorMsg}}</div> + {{if .IsResetForm}} + <div class="form-group"> + <label class="col-md-4 control-label">Password: </label> + <div class="col-md-6"> + <input name="passwd" type="password" class="form-control" placeholder="Type your password" required="required"> + </div> + </div> + <hr/> + <div class="form-group"> + <div class="col-md-offset-4 col-md-6"> + <button type="submit" class="btn btn-lg btn-primary">Click here to reset your password</button> + </div> + </div> + {{else}} + <p>Sorry, your confirmation code has been exipired or not valid.</p> + {{end}} + </form> +</div> +{{template "base/footer" .}} \ No newline at end of file diff --git a/templates/user/signin.tmpl b/templates/user/signin.tmpl index b6c39af1b8..43f47e4121 100644 --- a/templates/user/signin.tmpl +++ b/templates/user/signin.tmpl @@ -33,7 +33,7 @@ <div class="form-group"> <div class="col-md-offset-4 col-md-6"> <button type="submit" class="btn btn-lg btn-primary">Log In</button> - <a href="/forget-password/">Forgot your password?</a> + <a href="/user/forget_password/">Forgot your password?</a> </div> </div> diff --git a/web.go b/web.go index 0594d8e605..b5e4af3ee5 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)