This repository has been archived by the owner on Aug 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
98 lines (80 loc) · 2.09 KB
/
main.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
93
94
95
96
97
98
package main
import (
"errors"
"fmt"
"os"
"golang.org/x/crypto/bcrypt"
// Using postgres sql driver
_ "github.com/lib/pq"
"github.com/jinzhu/gorm"
)
var (
// DB returns a gorm.DB interface, it is used to access to database
DB *gorm.DB
)
type User struct {
gorm.Model
Name string `sql:"not null"`
Password string `sql:"-"`
EncryptedPassword string `sql:"not null" json:"-"`
}
// BeforeSave is a hook function provided by gorm package. It is used to:
// - update user password
func (user *User) BeforeSave(scope *gorm.Scope) (err error) {
if user.Password != "" {
if err = user.setEncryptedPassword(scope); err != nil {
return
}
}
return
}
func (user *User) setEncryptedPassword(scope *gorm.Scope) error {
pw, err := bcrypt.GenerateFromPassword([]byte(user.Password), 0)
if err != nil {
return err
}
scope.SetColumn("EncryptedPassword", string(pw))
user.Password = ""
return nil
}
// ErrInvalidEmailOrPassword returns an error. It's using in
// models.UserAuthenticate function when authenticate failure.
var ErrInvalidEmailOrPassword = errors.New("invalid username or password")
// UserAuthenticate receives a name and a password. Then find the user
// with name in database and validate the password. And returns a user
// instance and an error.
func UserAuthenticate(name string, password string) (User, error) {
var user User
if err := DB.Where("name = ?", name).First(&user).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return user, ErrInvalidEmailOrPassword
}
return user, err
}
if err := bcrypt.CompareHashAndPassword([]byte(user.EncryptedPassword), []byte(password)); err != nil {
return user, ErrInvalidEmailOrPassword
}
return user, nil
}
func init() {
initDB()
migrate()
}
func initDB() {
var err error
var db *gorm.DB
dbParams := os.Getenv("DB_PARAMS")
if dbParams == "" {
panic(errors.New("DB_PARAMS environment variable not set"))
}
db, err = gorm.Open("postgres", fmt.Sprintf(dbParams))
if err == nil {
DB = db
} else {
panic(err)
}
}
func migrate() {
DB.DropTableIfExists(&User{})
DB.AutoMigrate(&User{})
}