-
Notifications
You must be signed in to change notification settings - Fork 0
/
provider.go
84 lines (67 loc) · 1.99 KB
/
provider.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
package mysqlusers
import (
"database/sql"
"errors"
"fmt"
"net/http"
"strings"
_ "github.com/go-sql-driver/mysql"
"github.com/gotuna/gotuna"
"golang.org/x/crypto/bcrypt"
)
// DBUser is a sample gotuna.User implementation used with mysql
type DBUser struct {
ID string
Email string
Name string
Phone string
PasswordHash string
}
// GetID should return auto-incremented, unique "id" field from mysql database for this user
func (u DBUser) GetID() string {
return u.ID
}
// NewRepository returns a new mysql implementation of gotuna.UserRepository
func NewRepository(db *sql.DB) gotuna.UserRepository {
return mysqlUserRepository{db}
}
type mysqlUserRepository struct {
db *sql.DB
}
func (u mysqlUserRepository) Authenticate(w http.ResponseWriter, r *http.Request) (gotuna.User, error) {
email := strings.ToLower(strings.TrimSpace(r.FormValue("email")))
Password := r.FormValue("password")
if email == "" {
return DBUser{}, errors.New("this field is required")
}
if Password == "" {
return DBUser{}, errors.New("this field is required")
}
found, err := u.getUserByField("email", email)
if err != nil {
return DBUser{}, fmt.Errorf("cannot find user with this email: %v", err)
}
if err := bcrypt.CompareHashAndPassword([]byte(found.PasswordHash), []byte(Password)); err != nil {
return DBUser{}, fmt.Errorf("passwords don't match %v", err)
}
return found, nil
}
func (u mysqlUserRepository) GetUserByID(id string) (gotuna.User, error) {
return u.getUserByField("id", id)
}
func (u mysqlUserRepository) getUserByField(field, value string) (DBUser, error) {
user := DBUser{}
err := u.db.QueryRow(fmt.Sprintf(`
SELECT id, email, name, phone, password_hash
FROM users
WHERE %s = ?
`, field), value).
Scan(&user.ID, &user.Email, &user.Name, &user.Phone, &user.PasswordHash)
if err == sql.ErrNoRows {
return DBUser{}, errors.New("user not found")
}
if err != nil {
return DBUser{}, fmt.Errorf("user cannot be checked: %v", err)
}
return user, nil
}