-
Notifications
You must be signed in to change notification settings - Fork 0
/
email.go
91 lines (69 loc) · 1.46 KB
/
email.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 (
"database/sql"
"errors"
"github.com/asaskevich/govalidator"
"github.com/eirka/eirka-libs/db"
e "github.com/eirka/eirka-libs/errors"
)
// EmailModel contains new email
type EmailModel struct {
Uid uint
Name string
Email string
CurrentEmail string
}
// check struct validity
func (e *EmailModel) IsValid() bool {
if e.Uid == 0 {
return false
}
if e.Name == "" {
return false
}
if e.Email == "" {
return false
}
return true
}
// Validate will check the provided email
func (r *EmailModel) Validate() (err error) {
// Validate email
if !govalidator.IsEmail(r.Email) {
return e.ErrInvalidEmail
}
// Get Database handle
dbase, err := db.GetDb()
if err != nil {
return
}
// get current email
err = dbase.QueryRow("SELECT user_name,user_email FROM users WHERE user_id = ?", r.Uid).Scan(&r.Name, &r.CurrentEmail)
if err == sql.ErrNoRows {
return e.ErrUserNotExist
} else if err != nil {
return e.ErrInternalError
}
// we dont care if the email is already the same
if r.Email == r.CurrentEmail {
return e.ErrEmailSame
}
return
}
// update email
func (r *EmailModel) Update() (err error) {
// check model validity
if !r.IsValid() {
return errors.New("EmailModel is not valid")
}
// Get Database handle
dbase, err := db.GetDb()
if err != nil {
return
}
_, err = dbase.Exec("UPDATE users SET user_email = ? WHERE user_id = ?", r.Email, r.Uid)
if err != nil {
return
}
return
}