ch11.3
This commit is contained in:
@@ -2,7 +2,12 @@ package models
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
@@ -18,6 +23,24 @@ type UserModel struct {
|
||||
}
|
||||
|
||||
func (m *UserModel) Insert(name, email, password string) error {
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 12)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
stmt := `INSERT INTO users (name, email, hashed_password, created)
|
||||
VALUES(?, ?, ?, UTC_TIMESTAMP())`
|
||||
|
||||
_, err = m.DB.Exec(stmt, name, email, string(hashedPassword))
|
||||
if err != nil {
|
||||
var mySQLError *mysql.MySQLError
|
||||
if errors.As(err, &mySQLError) {
|
||||
if mySQLError.Number == 1062 && strings.Contains(mySQLError.Message, "users_uc_email") {
|
||||
return ErrDuplicateEmail
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package validator
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
@@ -44,3 +45,13 @@ func PermittedInt(value int, permittedValues ...int) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var EmailRX = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
|
||||
|
||||
func MinChars(value string, n int) bool {
|
||||
return utf8.RuneCountInString(value) >= n
|
||||
}
|
||||
|
||||
func Matches(value string, rx *regexp.Regexp) bool {
|
||||
return rx.MatchString(value)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user