Skip to content
Permalink
Browse files

06-User-Login add register

  • Loading branch information...
bonfy committed Sep 12, 2018
1 parent 4ce33f3 commit 2940d8a8ada7e9ea2d214495f7dc6958c4e45c16
Showing with 186 additions and 10 deletions.
  1. +35 −10 controller/home.go
  2. +85 −0 controller/utils.go
  3. +7 −0 model/user.go
  4. +2 −0 templates/content/login.html
  5. +20 −0 templates/content/register.html
  6. +37 −0 vm/register.go
@@ -1,6 +1,7 @@
package controller

import (
"log"
"net/http"

"github.com/bonfy/go-mega-code/vm"
@@ -9,9 +10,10 @@ import (
type home struct{}

func (h home) registerRoutes() {
http.HandleFunc("/", middleAuth(indexHandler))
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/logout", middleAuth(logoutHandler))
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/register", registerHandler)
http.HandleFunc("/", middleAuth(indexHandler))
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
@@ -35,21 +37,44 @@ func loginHandler(w http.ResponseWriter, r *http.Request) {
username := r.Form.Get("username")
password := r.Form.Get("password")

if len(username) < 3 {
v.AddError("username must longer than 3")
}
errs := checkLogin(username, password)
v.AddError(errs...)

if len(password) < 6 {
v.AddError("password must longer than 6")
if len(v.Errs) > 0 {
templates[tpName].Execute(w, &v)
} else {
setSessionUser(w, r, username)
http.Redirect(w, r, "/", http.StatusSeeOther)
}
}
}

if !vm.CheckLogin(username, password) {
v.AddError("username password not correct, please input again")
}
func registerHandler(w http.ResponseWriter, r *http.Request) {
tpName := "register.html"
vop := vm.RegisterViewModelOp{}
v := vop.GetVM()

if r.Method == http.MethodGet {
templates[tpName].Execute(w, &v)
}
if r.Method == http.MethodPost {
r.ParseForm()
username := r.Form.Get("username")
email := r.Form.Get("email")
pwd1 := r.Form.Get("pwd1")
pwd2 := r.Form.Get("pwd2")

errs := checkRegister(username, email, pwd1, pwd2)
v.AddError(errs...)

if len(v.Errs) > 0 {
templates[tpName].Execute(w, &v)
} else {
if err := addUser(username, pwd1, email); err != nil {
log.Println("add User error:", err)
w.Write([]byte("Error insert database"))
return
}
setSessionUser(w, r, username)
http.Redirect(w, r, "/", http.StatusSeeOther)
}
@@ -7,6 +7,9 @@ import (
"io/ioutil"
"net/http"
"os"
"regexp"

"github.com/bonfy/go-mega-code/vm"
)

// PopulateTemplates func
@@ -91,3 +94,85 @@ func clearSession(w http.ResponseWriter, r *http.Request) error {

return nil
}

// Login Check
func checkLen(fieldName, fieldValue string, minLen, maxLen int) string {
lenField := len(fieldValue)
if lenField < minLen {
return fmt.Sprintf("%s field is too short, less than %d", fieldName, minLen)
}
if lenField > maxLen {
return fmt.Sprintf("%s field is too long, more than %d", fieldName, maxLen)
}
return ""
}

func checkUsername(username string) string {
return checkLen("Username", username, 3, 20)
}

func checkPassword(password string) string {
return checkLen("Password", password, 6, 50)
}

func checkEmail(email string) string {
if m, _ := regexp.MatchString(`^([\w\.\_]{2,10})@(\w{1,}).([a-z]{2,4})$`, email); !m {
return fmt.Sprintf("Email field not a valid email")
}
return ""
}

func checkUserPassword(username, password string) string {
if !vm.CheckLogin(username, password) {
return fmt.Sprintf("Username and password is not correct.")
}
return ""
}

func checkUserExist(username string) string {
if !vm.CheckUserExist(username) {
return fmt.Sprintf("Username already exist, please choose another username")
}
return ""
}

// checkLogin()
func checkLogin(username, password string) []string {
var errs []string
if errCheck := checkUsername(username); len(errCheck) > 0 {
errs = append(errs, errCheck)
}
if errCheck := checkPassword(password); len(errCheck) > 0 {
errs = append(errs, errCheck)
}
if errCheck := checkUserPassword(username, password); len(errCheck) > 0 {
errs = append(errs, errCheck)
}
return errs
}

// checkRegister()
func checkRegister(username, email, pwd1, pwd2 string) []string {
var errs []string
if pwd1 != pwd2 {
errs = append(errs, "2 password does not match")
}
if errCheck := checkUsername(username); len(errCheck) > 0 {
errs = append(errs, errCheck)
}
if errCheck := checkPassword(pwd1); len(errCheck) > 0 {
errs = append(errs, errCheck)
}
if errCheck := checkEmail(email); len(errCheck) > 0 {
errs = append(errs, errCheck)
}
if errCheck := checkUserExist(username); len(errCheck) > 0 {
errs = append(errs, errCheck)
}
return errs
}

// addUser()
func addUser(username, password, email string) error {
return vm.AddUser(username, password, email)
}
@@ -28,3 +28,10 @@ func GetUserByUsername(username string) (*User, error) {
}
return &user, nil
}

// AddUser func
func AddUser(username, password, email string) error {
user := User{Username: username, Email: email}
user.SetPassword(password)
return db.Create(&user).Error
}
@@ -6,6 +6,8 @@ <h1>Login</h1>
<p><input type="submit" name="submit" value="Login"></p>
</form>

<p>New User? <a href="/register">Click to Register!</a></p>

{{if .Errs}}
<ul>
{{range .Errs}}
@@ -0,0 +1,20 @@
{{define "content"}}
<h1>Register</h1>
<form action="/register" method="post" name="register">
<p><input type="text" name="username" value="" placeholder="Username"></p>
<p><input type="text" name="email" value="" placeholder="Email"></p>
<p><input type="password" name="pwd1" value="" placeholder="Password"></p>
<p><input type="password" name="pwd2" value="" placeholder="Password"></p>
<p><input type="submit" name="submit" value="Register"></p>
</form>

<p>Have account? <a href="/login">Click to Login!</a></p>

{{if .Errs}}
<ul>
{{range .Errs}}
<li>{{.}}</li>
{{end}}
</ul>
{{end}}
{{end}}
@@ -0,0 +1,37 @@
package vm

import (
"log"

"github.com/bonfy/go-mega-code/model"
)

// RegisterViewModel struct
type RegisterViewModel struct {
LoginViewModel
}

// RegisterViewModelOp struct
type RegisterViewModelOp struct{}

// GetVM func
func (RegisterViewModelOp) GetVM() RegisterViewModel {
v := RegisterViewModel{}
v.SetTitle("Register")
return v
}

// CheckUserExist func
func CheckUserExist(username string) bool {
_, err := model.GetUserByUsername(username)
if err != nil {
log.Println("Can not find username: ", username)
return true
}
return false
}

// AddUser func
func AddUser(username, password, email string) error {
return model.AddUser(username, password, email)
}

0 comments on commit 2940d8a

Please sign in to comment.
You can’t perform that action at this time.