96 lines
2.0 KiB
Go
96 lines
2.0 KiB
Go
package api
|
|
|
|
import (
|
|
"log"
|
|
|
|
"lishwist/db"
|
|
"lishwist/templates"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
type RegisterProps struct {
|
|
GeneralError string `json:",omitempty"`
|
|
Username templates.InputProps
|
|
Password templates.InputProps
|
|
ConfirmPassword templates.InputProps
|
|
}
|
|
|
|
func (p *RegisterProps) Validate() (valid bool) {
|
|
if p.Password.Value != p.ConfirmPassword.Value {
|
|
p.ConfirmPassword.Error = "Passwords didn't match"
|
|
valid = false
|
|
}
|
|
|
|
if !p.Username.Validate() {
|
|
valid = false
|
|
}
|
|
|
|
if !p.Password.Validate() {
|
|
valid = false
|
|
}
|
|
|
|
if !p.ConfirmPassword.Validate() {
|
|
valid = false
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
func NewRegisterProps(usernameVal, passwordVal, confirmPassVal string) *RegisterProps {
|
|
return &RegisterProps{
|
|
GeneralError: "",
|
|
Username: templates.InputProps{
|
|
Name: "username",
|
|
Required: true,
|
|
MinLength: 4,
|
|
Value: usernameVal,
|
|
},
|
|
Password: templates.InputProps{
|
|
Type: "password",
|
|
Name: "newPassword",
|
|
Required: true,
|
|
MinLength: 5,
|
|
Value: passwordVal,
|
|
},
|
|
ConfirmPassword: templates.InputProps{
|
|
Type: "password",
|
|
Name: "confirmPassword",
|
|
Required: true,
|
|
Value: confirmPassVal,
|
|
},
|
|
}
|
|
}
|
|
|
|
func Register(username, newPassword, confirmPassword string) *RegisterProps {
|
|
props := NewRegisterProps(username, newPassword, confirmPassword)
|
|
|
|
valid := props.Validate()
|
|
props.Password.Value = ""
|
|
props.ConfirmPassword.Value = ""
|
|
if !valid {
|
|
return props
|
|
}
|
|
|
|
existingUser, _ := db.GetUserByName(username)
|
|
if existingUser != nil {
|
|
props.Username.Error = "Username is taken"
|
|
return props
|
|
}
|
|
|
|
hashedPasswordBytes, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.MinCost)
|
|
if err != nil {
|
|
props.GeneralError = "Something went wrong. Error code: Aang"
|
|
return props
|
|
}
|
|
|
|
_, err = db.CreateUser(username, hashedPasswordBytes)
|
|
if err != nil {
|
|
log.Println("Registration error:", err)
|
|
props.GeneralError = "Something went wrong. Error code: Ozai"
|
|
return props
|
|
}
|
|
|
|
return nil
|
|
}
|