This repository has been archived by the owner on Feb 24, 2024. It is now read-only.
/
user.go
91 lines (81 loc) · 2.46 KB
/
user.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package models
import (
"encoding/json"
"fmt"
"time"
"github.com/markbates/going/validate"
"github.com/markbates/going/validate/validators"
"github.com/markbates/pop"
)
// User model stores information about a user account
type User struct {
ID int `json:"id" db:"id" schema:"-"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
FirstName string `json:"first_name" db:"first_name"`
LastName string `json:"last_name" db:"last_name"`
Email string `json:"email" db:"email"`
}
// String is not required by pop and may be deleted
func (u User) String() string {
b, _ := json.Marshal(u)
return string(b)
}
// FullName returns the first name and last name, separated by a space
func (u User) FullName() string {
return fmt.Sprintf("%s %s", u.FirstName, u.LastName)
}
// ValidateNew validates the User fields and checks whether a user has
// claimed that email address
func (u *User) ValidateNew(tx *pop.Connection) (*validate.Errors, error) {
verrs, err := u.validateCommon(tx)
verrs.Append(validate.Validate(
&validators.FuncValidator{
Fn: func() bool {
var b bool
if u.Email != "" {
b, err = tx.Where("email = ?", u.Email).Exists(u)
}
return !b
},
Field: "Email",
Message: "%s was already taken.",
},
))
return verrs, err
}
// ValidateUpdate validates the User fields and confirms that the email has
// not been claimed
func (u *User) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) {
verrs, err := u.validateCommon(tx)
verrs.Append(validate.Validate(
&validators.FuncValidator{
Fn: func() bool {
var b bool
if u.Email != "" {
// Differs from ValidateNew here - only check whether *other* users claimed email
b, err = tx.Where("email = ? and id != ?", u.Email, u.ID).Exists(u)
}
return !b
},
Field: "Email",
Message: "%s was already taken.",
},
))
return verrs, err
}
func (u *User) validateCommon(tx *pop.Connection) (*validate.Errors, error) {
verrs := validate.Validate(
&validators.StringIsPresent{Name: "First Name", Field: u.FirstName},
&validators.StringIsPresent{Name: "Last Name", Field: u.LastName},
&validators.StringIsPresent{Name: "Email", Field: u.Email},
)
return verrs, nil
}
// Users is not required by pop and may be deleted
type Users []User
// String is not required by pop and may be deleted
func (u Users) String() string {
b, _ := json.Marshal(u)
return string(b)
}