Browse Source

Add binding form for register user

pull/31/head
Unknown 11 years ago
parent
commit
c6f2c23b05
  1. 3
      bee.json
  2. 1
      conf/app.ini
  3. 2
      gogs.go
  4. 3
      models/models.go
  5. 15
      models/user.go
  6. 111
      modules/auth/form.go
  7. 20
      modules/base/base.go
  8. 50
      routers/user/user.go
  9. 10
      templates/user/signup.tmpl
  10. 15
      utils/auth/auth.go
  11. 7
      web.go

3
bee.json

@ -11,7 +11,8 @@
"controllers": "routers", "controllers": "routers",
"models": "", "models": "",
"others": [ "others": [
"utils" "utils", "modules",
"$GOPATH/src/github.com/gogits/binding"
] ]
}, },
"cmd_args": [ "cmd_args": [

1
conf/app.ini

@ -3,6 +3,7 @@ RUN_USER = lunny
[repository] [repository]
ROOT = /Users/lunny/git/gogs-repositories ROOT = /Users/lunny/git/gogs-repositories
ROOT_jiahuachen = /Users/jiahuachen/git/gogs-repositories
[server] [server]
HTTP_ADDR = HTTP_ADDR =

2
gogs.go

@ -19,7 +19,7 @@ import (
// Test that go1.1 tag above is included in builds. main.go refers to this definition. // Test that go1.1 tag above is included in builds. main.go refers to this definition.
const go11tag = true const go11tag = true
const APP_VER = "0.0.0.0303" const APP_VER = "0.0.0.0305"
func init() { func init() {
runtime.GOMAXPROCS(runtime.NumCPU()) runtime.GOMAXPROCS(runtime.NumCPU())

3
models/models.go

@ -83,6 +83,9 @@ func setEngine() {
//log.Trace("Initialized database -> %s", dbName) //log.Trace("Initialized database -> %s", dbName)
RepoRootPath = utils.Cfg.MustValue("repository", "ROOT") RepoRootPath = utils.Cfg.MustValue("repository", "ROOT")
if uname.Username == "jiahuachen" {
RepoRootPath = utils.Cfg.MustValue("repository", "ROOT_jiahuachen")
}
} }
func init() { func init() {

15
models/user.go

@ -15,7 +15,6 @@ import (
"github.com/dchest/scrypt" "github.com/dchest/scrypt"
"github.com/gogits/gogs/utils" "github.com/gogits/gogs/utils"
"github.com/gogits/gogs/utils/log"
) )
// User types. // User types.
@ -100,17 +99,15 @@ func RegisterUser(user *User) (err error) {
user.LowerName = strings.ToLower(user.Name) user.LowerName = strings.ToLower(user.Name)
user.Avatar = utils.EncodeMd5(user.Email) user.Avatar = utils.EncodeMd5(user.Email)
user.EncodePasswd() user.EncodePasswd()
_, err = orm.Insert(user) if _, err = orm.Insert(user); err != nil {
if err != nil {
return err return err
} }
err = os.MkdirAll(UserPath(user.Name), os.ModePerm) if err = os.MkdirAll(UserPath(user.Name), os.ModePerm); err != nil {
if err != nil {
_, err2 := orm.Id(user.Id).Delete(&User{}) if _, err := orm.Id(user.Id).Delete(&User{}); err != nil {
if err2 != nil { return errors.New(fmt.Sprintf(
log.Error("create userpath %s failed and delete table record faild", "both create userpath %s and delete table record faild", user.Name))
user.Name)
} }
return err return err
} }

111
modules/auth/form.go

@ -0,0 +1,111 @@
// 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 auth
import (
"net/http"
"reflect"
"github.com/codegangsta/martini"
"github.com/gogits/binding"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/utils/log"
)
type RegisterForm struct {
UserName string `form:"username" binding:"Required;AlphaDash;MinSize(5);MaxSize(30)"`
Email string `form:"email" binding:"Required;Email;MaxSize(50)"`
Password string `form:"passwd" binding:"Required;MinSize(6);MaxSize(30)"`
}
func (r *RegisterForm) Validate(errors *binding.Errors, req *http.Request, context martini.Context) {
if req.Method == "GET" || errors.Count() == 0 {
return
}
data := context.Get(reflect.TypeOf(base.TmplData{})).Interface().(base.TmplData)
data["HasError"] = true
AssignForm(r, data)
if len(errors.Overall) > 0 {
for _, err := range errors.Overall {
log.Error("RegisterForm.Validate: %v", err)
}
return
}
if err, ok := errors.Fields["UserName"]; ok {
data["Err_Username"] = true
switch err {
case binding.RequireError:
data["ErrorMsg"] = "Username cannot be empty"
case binding.AlphaDashError:
data["ErrorMsg"] = "Username must be valid alpha or numeric or dash(-_) characters"
case binding.MinSizeError:
data["ErrorMsg"] = "Username at least has 5 characters"
case binding.MaxSizeError:
data["ErrorMsg"] = "Username at most has 30 characters"
default:
data["ErrorMsg"] = "Unknown error: " + err
}
return
}
if err, ok := errors.Fields["Email"]; ok {
data["Err_Email"] = true
switch err {
case binding.RequireError:
data["ErrorMsg"] = "E-mail address cannot be empty"
case binding.EmailError:
data["ErrorMsg"] = "E-mail address is not valid"
case binding.MaxSizeError:
data["ErrorMsg"] = "E-mail address at most has 50 characters"
default:
data["ErrorMsg"] = "Unknown error: " + err
}
return
}
if err, ok := errors.Fields["Password"]; ok {
data["Err_Passwd"] = true
switch err {
case binding.RequireError:
data["ErrorMsg"] = "Password cannot be empty"
case binding.MinSizeError:
data["ErrorMsg"] = "Password at least has 6 characters"
case binding.MaxSizeError:
data["ErrorMsg"] = "Password at most has 30 characters"
default:
data["ErrorMsg"] = "Unknown error: " + err
}
return
}
}
// AssignForm assign form values back to the template data.
func AssignForm(form interface{}, data base.TmplData) {
typ := reflect.TypeOf(form)
val := reflect.ValueOf(form)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
val = val.Elem()
}
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
fieldName := field.Tag.Get("form")
// Allow ignored fields in the struct
if fieldName == "-" {
continue
}
data[fieldName] = val.Field(i).Interface()
}
}

20
modules/base/base.go

@ -0,0 +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 base
import (
"github.com/codegangsta/martini"
)
type (
// Type TmplData represents data in the templates.
TmplData map[string]interface{}
)
func InitContext() martini.Handler {
return func(context martini.Context) {
context.Map(TmplData{})
}
}

50
routers/user/user.go

@ -8,13 +8,13 @@ import (
"fmt" "fmt"
"net/http" "net/http"
//"github.com/martini-contrib/binding"
"github.com/martini-contrib/render" "github.com/martini-contrib/render"
"github.com/martini-contrib/sessions" "github.com/martini-contrib/sessions"
"github.com/gogits/validation"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/utils/auth" "github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/utils/log" "github.com/gogits/gogs/utils/log"
) )
@ -50,42 +50,42 @@ func SignIn(req *http.Request, r render.Render, session sessions.Session) {
}) })
} }
func SignUp(req *http.Request, r render.Render) { func SignUp(form auth.RegisterForm, data base.TmplData, req *http.Request, r render.Render) {
data := map[string]interface{}{"Title": "Sign Up"} data["Title"] = "Sign Up"
if req.Method == "GET" { if req.Method == "GET" {
r.HTML(200, "user/signup", data) r.HTML(200, "user/signup", data)
return return
} }
// Front-end should do double check of password. if hasErr, ok := data["HasError"]; ok && hasErr.(bool) {
u := &models.User{ r.HTML(200, "user/signup", data)
Name: req.FormValue("username"), return
Email: req.FormValue("email"),
Passwd: req.FormValue("passwd"),
} }
valid := validation.Validation{} //Front-end should do double check of password.
ok, err := valid.Valid(u) u := &models.User{
if err != nil { Name: form.UserName,
log.Error("user.SignUp -> valid user: %v", err) Email: form.Email,
return Passwd: form.Password,
} }
if !ok {
if err := models.RegisterUser(u); err != nil {
if err.Error() == models.ErrUserAlreadyExist.Error() {
data["HasError"] = true data["HasError"] = true
data["ErrorMsg"] = auth.GenerateErrorMsg(valid.Errors[0]) data["Err_Username"] = true
data["ErrorMsg"] = "Username has been already taken"
auth.AssignForm(form, data)
r.HTML(200, "user/signup", data) r.HTML(200, "user/signup", data)
return return
} }
// err = models.RegisterUser(u) log.Error("user.SignUp: %v", err)
// if err != nil { r.HTML(500, "status/500", nil)
// r.HTML(200, "base/error", map[string]interface{}{ return
// "Error": fmt.Sprintf("%v", err), }
// })
// return
// }
// r.Redirect("/") r.Redirect("/user/login")
} }
func Delete(req *http.Request, r render.Render) { func Delete(req *http.Request, r render.Render) {

10
templates/user/signup.tmpl

@ -6,20 +6,20 @@
{{if .HasError}} {{if .HasError}}
<div class="alert alert-danger">{{.ErrorMsg}}</div> <div class="alert alert-danger">{{.ErrorMsg}}</div>
{{end}} {{end}}
<div class="form-group"> <div class="form-group {{if .Err_Username}}has-error has-feedback{{end}}">
<label class="col-md-4 control-label">Username: </label> <label class="col-md-4 control-label">Username: </label>
<div class="col-md-6"> <div class="col-md-6">
<input name="username" class="form-control" placeholder="Type your username"> <input name="username" class="form-control" placeholder="Type your username" value="{{.username}}">
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group {{if .Err_Email}}has-error has-feedback{{end}}">
<label class="col-md-4 control-label">Email: </label> <label class="col-md-4 control-label">Email: </label>
<div class="col-md-6"> <div class="col-md-6">
<input name="email" class="form-control" placeholder="Type your e-mail address"> <input name="email" class="form-control" placeholder="Type your e-mail address" value="{{.email}}">
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group {{if .Err_Passwd}}has-error has-feedback{{end}}">
<label class="col-md-4 control-label">Password: </label> <label class="col-md-4 control-label">Password: </label>
<div class="col-md-6"> <div class="col-md-6">
<input name="passwd" type="password" class="form-control" placeholder="Type your password"> <input name="passwd" type="password" class="form-control" placeholder="Type your password">

15
utils/auth/auth.go

@ -1,15 +0,0 @@
// 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 auth
import (
"fmt"
"github.com/gogits/validation"
)
func GenerateErrorMsg(e *validation.ValidationError) string {
return fmt.Sprintf("%v", e.LimitValue)
}

7
web.go

@ -14,6 +14,10 @@ import (
"github.com/martini-contrib/render" "github.com/martini-contrib/render"
"github.com/martini-contrib/sessions" "github.com/martini-contrib/sessions"
"github.com/gogits/binding"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/routers" "github.com/gogits/gogs/routers"
"github.com/gogits/gogs/routers/repo" "github.com/gogits/gogs/routers/repo"
"github.com/gogits/gogs/routers/user" "github.com/gogits/gogs/routers/user"
@ -46,6 +50,7 @@ func runWeb(*cli.Context) {
// Middleware. // Middleware.
m.Use(render.Renderer(render.Options{Funcs: []template.FuncMap{AppHelpers}})) m.Use(render.Renderer(render.Options{Funcs: []template.FuncMap{AppHelpers}}))
m.Use(base.InitContext())
// TODO: should use other store because cookie store is not secure. // TODO: should use other store because cookie store is not secure.
store := sessions.NewCookieStore([]byte("secret123")) store := sessions.NewCookieStore([]byte("secret123"))
@ -55,7 +60,7 @@ func runWeb(*cli.Context) {
m.Get("/", routers.Dashboard) m.Get("/", routers.Dashboard)
m.Any("/user/login", user.SignIn) m.Any("/user/login", user.SignIn)
m.Any("/user/sign_up", user.SignUp) m.Any("/user/sign_up", binding.BindIgnErr(auth.RegisterForm{}), user.SignUp)
m.Get("/user/profile", user.Profile) // should be /username m.Get("/user/profile", user.Profile) // should be /username
m.Any("/user/delete", user.Delete) m.Any("/user/delete", user.Delete)

Loading…
Cancel
Save