示例#1
0
func (r *UserRepo) Validate() error {
	r.user.Email = normalizeEmail(r.user.Email)

	errs := []string{}

	if r.user.Password == "" {
		errs = append(errs, PasswordBlank)
	}

	if r.user.Email == "" {
		errs = append(errs, EmailBlank)
	}

	if !regexp.MustCompile(emailFormat).MatchString(r.user.Email) {
		errs = append(errs, EmailInvalid)
	}

	var count int
	r.db.QueryRow(`SELECT COUNT(id) FROM users WHERE email = $1`, r.user.Email).Scan(&count)

	if count > 0 {
		errs = append(errs, EmailExists)
	}

	if len(errs) > 0 {
		return jsonapi.ErrInvalidParams(errs...)
	}

	return nil
}
示例#2
0
func (u *User) Authenticate(password string) error {
	err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	if err != nil {
		return jsonapi.ErrInvalidParams(EmailPasswordInvalid)
	}

	return nil
}
示例#3
0
	token.Claims["email"] = email
	tokenString, _ := token.SignedString(privateKey)
	return tokenString
}

func withToken(email string, res string) string {
	return fmt.Sprintf(res, createToken(email))
}

var createUserTestData = []struct {
	path    string
	body    string
	expCode int
	expBody string
}{
	{"/users", `{"data":[{"email":"","password":"******"}]}`, 422, err(jsonapi.ErrInvalidParams(auth.EmailBlank, auth.EmailInvalid))},
	{"/users", `{"data":[{"email":"*****@*****.**","password":""}]}`, 422, err(jsonapi.ErrInvalidParams(auth.PasswordBlank))},
	{"/users", `{"data":[{"email":"not_an_email","password":"******"}]}`, 422, err(jsonapi.ErrInvalidParams(auth.EmailInvalid))},
	{"/users", `{"data":[{"email":"*****@*****.**","password":"******"}]}`, 422, err(jsonapi.ErrInvalidParams(auth.EmailExists))},
	{"/users", `{"data":[{"email":"*****@*****.**","password":"******"}]}`, 422, err(jsonapi.ErrInvalidParams(auth.EmailExists))},
	{"/users", `{"data":[]}`, 422, err(jsonapi.ErrNoData)},
	{"/users", `{"other_key":[{"email":"*****@*****.**","password":"******"}]}`, 422, err(jsonapi.ErrNoData)},
	{"/users", `{}`, 422, err(jsonapi.ErrNoData)},
	{"/users", ``, 400, err(jsonapi.ErrBadRequest)},
	{"/users", `{"data":[{"email":"*****@*****.**","password":"******"}]}`, 201, withToken("*****@*****.**", `{"data":[{"id":2,"email":"*****@*****.**","token":"%s"}]}`+"\n")},
	{"/users", `{"data":[{"email":"third @bar.  com\t\n","password":"******"}]}`, 201, withToken("*****@*****.**", `{"data":[{"id":3,"email":"*****@*****.**","token":"%s"}]}`+"\n")},
}

func TestCreateUser(t *testing.T) {
	db := NewTestDB()
	defer db.Close()