Untitled

mail@pastecode.io avatar
unknown
plain_text
5 months ago
2.0 kB
1
Indexable
package controllers

import (
	"fmt"
	"net/http"
	"unicode"
)

type Users struct {
	Templates struct {
		New Template
	}
}

type UserFormData struct {
	Email           string
	Password        string
	ConfirmPassword string
	Error           string
}

func verifyPassword(s string) (eightOrMore, number, upper, special bool) {
	letters := 0
	for _, c := range s {
		switch {
		case unicode.IsNumber(c):
			number = true
		case unicode.IsUpper(c):
			upper = true
			letters++
		case unicode.IsPunct(c) || unicode.IsSymbol(c):
			special = true
		case unicode.IsLetter(c) || c == ' ':
			letters++
		default:
			return false, false, false, false
		}
	}
	eightOrMore = letters >= 8
	return
}

func validatePasswordFields(password string) string {
	eightOrMore, hasNumber, hasUpper, hasSpecial := verifyPassword(password)

	if !eightOrMore {
		return "Password must be at least 8 letters long"
	}
	if !hasNumber {
		return "Password must contain at least one number"
	}
	if !hasUpper {
		return "Password must containt at least one uppercase letter"
	}
	if !hasSpecial {
		return "Password must contain at least one special character"
	}

	return ""

}

func (u Users) New(w http.ResponseWriter, r *http.Request) {
	data := UserFormData{}
	data.Email = r.FormValue("email")
	u.Templates.New.Execute(w, data)
}

func (u Users) Create(w http.ResponseWriter, r *http.Request) {
	email := r.FormValue("email")
	password := r.FormValue("password")
	confirmPassword := r.FormValue("confirmPassword")

	data := UserFormData{
		Email:           email,
		Password:        "",
		ConfirmPassword: "",
	}

	msg := validatePasswordFields(password)
	if msg != "" {
		data.Error = msg
		w.WriteHeader(http.StatusBadRequest)
		u.Templates.New.Execute(w, data)
		return
	}

	if password != confirmPassword {
		data.Error = "Passwords do not match"
		w.WriteHeader(http.StatusBadRequest)
		u.Templates.New.Execute(w, data)
		return
	}

	fmt.Fprintln(w, "User created successfully")
	fmt.Fprintf(w, "Email : %s", email)
	fmt.Fprintf(w, " Password : %s", password)

}
Leave a Comment