From dffd67a9fe1fa5a2a9c318f31a9059123338eef5 Mon Sep 17 00:00:00 2001 From: Las Zenow Date: Mon, 9 Apr 2018 20:52:40 +0000 Subject: [PATCH] Improve usability of the user registration --- lib/database/users.go | 13 +++++++++++-- lib/user.go | 4 +++- templates/header.html | 2 +- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/lib/database/users.go b/lib/database/users.go index 2c9db34..d71f71b 100644 --- a/lib/database/users.go +++ b/lib/database/users.go @@ -8,10 +8,13 @@ import ( "bytes" "crypto/rand" "errors" + "regexp" "golang.org/x/crypto/scrypt" ) +var alphaNumeric = regexp.MustCompile(`^[a-zA-Z0-9_\-\.]+$`).MatchString + type User struct { ID int `sql:"type:serial"` Username string `sql:"type:varchar(255),unique"` @@ -23,7 +26,7 @@ type User struct { func (db *pgDB) AddUser(name string, pass string) error { if !validUserName(name) { - return errors.New("Invalid user name") + return errors.New("Invalid user name. Username needs to have at least 3 characters and can only be letters, numbers, '-', '_' and '.'.") } num, err := db.sql.Model(&User{}).Where("lower(username) = lower(?)", name).Count() if err != nil { @@ -118,8 +121,14 @@ func (db *pgDB) getUser(name string) (User, error) { } func validUserName(name string) bool { + if len(name) < 3 { + return false + } + if !alphaNumeric(name) { + return false + } switch name { - case "", "admin", "webmaster", "postmaster", "info", "root", "news": + case "", "admin", "webmaster", "postmaster", "info", "root", "news", "trantor", "librarian", "library", "imperial": return false default: return true diff --git a/lib/user.go b/lib/user.go index c37e7ef..abbd895 100644 --- a/lib/user.go +++ b/lib/user.go @@ -39,13 +39,15 @@ func createUserHandler(h handler) { confirmPass := h.r.FormValue("confirmPass") if pass != confirmPass { h.sess.Notify("Registration error!", "Passwords don't match", "error") + } else if pass == "" { + h.sess.Notify("Registration error!", "The password can't be empty", "error") } else { user := h.r.FormValue("user") err := h.db.AddUser(user, pass) if err == nil { h.sess.Notify("Account created!", "Welcome "+user+". Now you can login", "success") } else { - h.sess.Notify("Registration error!", "There was some database problem, if it keeps happening please inform me", "error") + h.sess.Notify("Registration error!", err.Error(), "error") } } h.sess.Save(h.w, h.r) diff --git a/templates/header.html b/templates/header.html index 68aff07..e5204b3 100644 --- a/templates/header.html +++ b/templates/header.html @@ -82,7 +82,7 @@ {{else}} -
  • +
  • Login/SignUp
  • {{end}}