-
Notifications
You must be signed in to change notification settings - Fork 0
/
email.go
92 lines (69 loc) · 1.51 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
92
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
}
// IsValid will check struct validity
func (m *EmailModel) IsValid() bool {
if m.UID == 0 || m.UID == 1 {
return false
}
if m.Name == "" {
return false
}
if m.Email == "" {
return false
}
return true
}
// Validate will check the provided email
func (m *EmailModel) Validate() (err error) {
// Validate email
if !govalidator.IsEmail(m.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 = ?", m.UID).Scan(&m.Name, &m.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 m.Email == m.CurrentEmail {
return e.ErrEmailSame
}
return
}
// Update will update the email model
func (m *EmailModel) Update() (err error) {
// check model validity
if !m.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 = ?", m.Email, m.UID)
if err != nil {
return
}
return
}