You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
953 B
48 lines
953 B
package auth
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"regexp"
|
|
"strings"
|
|
|
|
passwordvalidator "github.com/wagslane/go-password-validator"
|
|
)
|
|
|
|
const (
|
|
minPasswordEntropy = 60
|
|
)
|
|
|
|
type RequestForm struct {
|
|
Username string
|
|
Password string
|
|
}
|
|
|
|
func (h *RequestForm) validate() error {
|
|
if h.Username == "" {
|
|
return errors.New("username is required")
|
|
}
|
|
if h.Password == "" {
|
|
return errors.New("password is required")
|
|
}
|
|
if !regexp.MustCompile(`^[a-zA-Z0-9-_]{3,24}$`).MatchString(h.Username) {
|
|
return errors.New("username is not valid")
|
|
}
|
|
return passwordvalidator.Validate(h.Password, minPasswordEntropy)
|
|
}
|
|
|
|
func (h *RequestForm) Parse(r *http.Request) error {
|
|
err := r.ParseForm()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
h.Username = strings.TrimSpace(r.FormValue("username"))
|
|
h.Password = strings.TrimSpace(r.FormValue("password"))
|
|
// truncate extremely long passwords
|
|
if len(h.Password) > 128 {
|
|
h.Password = h.Password[:128]
|
|
}
|
|
|
|
return h.validate()
|
|
}
|