-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathhandler.go
107 lines (84 loc) · 2.24 KB
/
handler.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
99
100
101
102
103
104
105
106
107
package main
import (
"errors"
"fmt"
"log"
pb "github.com/EwanValentine/shippy-user-service/proto/auth"
"golang.org/x/crypto/bcrypt"
"golang.org/x/net/context"
)
const topic = "user.created"
type service struct {
repo Repository
tokenService Authable
}
func (srv *service) Get(ctx context.Context, req *pb.User, res *pb.Response) error {
user, err := srv.repo.Get(req.Id)
if err != nil {
return err
}
res.User = user
return nil
}
func (srv *service) GetAll(ctx context.Context, req *pb.Request, res *pb.Response) error {
users, err := srv.repo.GetAll()
if err != nil {
return err
}
res.Users = users
return nil
}
func (srv *service) Auth(ctx context.Context, req *pb.User, res *pb.Token) error {
log.Println("Logging in with:", req.Email, req.Password)
user, err := srv.repo.GetByEmail(req.Email)
log.Println(user, err)
if err != nil {
return err
}
// Compares our given password against the hashed password
// stored in the database
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
return err
}
token, err := srv.tokenService.Encode(user)
if err != nil {
return err
}
res.Token = token
return nil
}
func (srv *service) Create(ctx context.Context, req *pb.User, res *pb.Response) error {
log.Println("Creating user: ", req)
// Generates a hashed version of our password
hashedPass, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
if err != nil {
return errors.New(fmt.Sprintf("error hashing password: %v", err))
}
req.Password = string(hashedPass)
if err := srv.repo.Create(req); err != nil {
return errors.New(fmt.Sprintf("error creating user: %v", err))
}
token, err := srv.tokenService.Encode(req)
if err != nil {
return err
}
res.User = req
res.Token = &pb.Token{Token: token}
/*
if err := srv.Publisher.Publish(ctx, req); err != nil {
return errors.New(fmt.Sprintf("error publishing event: %v", err))
}*/
return nil
}
func (srv *service) ValidateToken(ctx context.Context, req *pb.Token, res *pb.Token) error {
// Decode token
claims, err := srv.tokenService.Decode(req.Token)
if err != nil {
return err
}
if claims.User.Id == "" {
return errors.New("invalid user")
}
res.Valid = true
return nil
}