Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.9 kB
1
Indexable
Never
package controllers

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

type Users struct {
	Templates struct {
		New Template
	}
}

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) error {
	eightOrMore, hasNumber, hasUpper, hasSpecial := verifyPassword(password)

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

	return nil

}

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

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

	err := validatePasswordFields(password)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	err = validatePasswordFields(confirmPassword)
	if err != nil {
		http.Error(w, fmt.Sprintf("Confirm Password error: %s", err.Error()), http.StatusBadRequest)
		return
	}

	fmt.Fprintln(w, "Password:", password)

	if password != confirmPassword {
		http.Error(w, "Passwords do not match", http.StatusBadRequest)
		return
	}

}

Leave a Comment