-
Notifications
You must be signed in to change notification settings - Fork 0
/
views.go
66 lines (58 loc) · 1.65 KB
/
views.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
package backend
import (
"errors"
"time"
"github.com/aukbit/pluto"
"github.com/aukbit/pluto/auth/jwt"
pba "github.com/aukbit/pluto/auth/proto"
"github.com/aukbit/pluto/client"
pbu "github.com/aukbit/pluto/examples/user/proto"
"golang.org/x/net/context"
)
var (
errCredentials = errors.New("Invalid credentials")
errClientUserNotAvailable = errors.New("Client user not available")
)
// AuthViews struct
type AuthViews struct{}
// Authenticate implements authentication
func (av *AuthViews) Authenticate(ctx context.Context, cre *pba.Credentials) (*pba.Token, error) {
// get client user from pluto service from context
c, ok := pluto.FromContext(ctx).Client("user")
if !ok {
return &pba.Token{}, errClientUserNotAvailable
}
// dial
conn, err := c.Dial(client.Timeout(5 * time.Second))
if err != nil {
return &pba.Token{}, err
}
defer conn.Close()
// make a call to user backend service for credentials verification
nCred := &pbu.Credentials{Email: cre.Email, Password: cre.Password}
v, err := c.Stub(conn).(pbu.UserServiceClient).VerifyUser(ctx, nCred)
if err != nil {
return &pba.Token{}, err
}
if !v.IsValid {
return &pba.Token{}, errCredentials
}
cs := &jwt.ClaimSet{
Identifier: cre.Email,
Audience: "bearer",
Expiration: 3650,
}
token, err := jwt.NewToken(ctx, cs)
if err != nil {
return &pba.Token{}, err
}
return &pba.Token{Jwt: token}, nil
}
// Verify implements authentication
func (av *AuthViews) Verify(ctx context.Context, t *pba.Token) (*pba.Verification, error) {
err := jwt.Verify(ctx, t.Jwt)
if err != nil {
return &pba.Verification{IsValid: false}, err
}
return &pba.Verification{IsValid: true}, nil
}