-
Notifications
You must be signed in to change notification settings - Fork 0
/
login.go
53 lines (42 loc) · 1.1 KB
/
login.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
package handler
import (
// standard libraries
"errors"
// encryption library
"golang.org/x/crypto/bcrypt"
// custom handlers
"github.com/callistom/go-graphql-auth/authentication"
"github.com/callistom/go-graphql-auth/structs"
// db
"github.com/jinzhu/gorm"
)
// init vars
var (
db *gorm.DB
err error
)
// Login function find user
func (r *Resolver) Login(args *struct {
Input *structs.LoginInput
}) (string, error) {
db, err = gorm.Open("postgres", "postgres://localhost/graphql?sslmode=disable")
var users []structs.User
if err := db.Find(&users).Error; err != nil {
return "", errors.New("An error has occured when trying to fetch users")
}
for _, user := range users {
if user.Mail == args.Input.Mail {
// compare password with given password
err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(args.Input.Password))
if err == nil {
token, err := authentication.GenerateToken(user)
if err != nil {
return "", err
}
return token, err
}
return "", errors.New("Password is not correct")
}
}
return "", errors.New("User not found")
}