/
main.go
70 lines (54 loc) · 1.44 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
package main
import (
"encoding/json"
"errors"
"log"
"github.com/xxdawn/micro/examples/booking/data"
"github.com/xxdawn/micro/examples/booking/srv/auth/proto"
"context"
"golang.org/x/net/trace"
"github.com/micro/go-micro/v2"
"github.com/micro/go-micro/v2/metadata"
)
type Auth struct {
customers map[string]*auth.Customer
}
// VerifyToken returns a customer from authentication token.
func (s *Auth) VerifyToken(ctx context.Context, req *auth.Request, rsp *auth.Result) error {
md, _ := metadata.FromContext(ctx)
traceID := md["traceID"]
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf("traceID %s", traceID)
}
customer := s.customers[req.AuthToken]
if customer == nil {
return errors.New("Invalid Token")
}
rsp.Customer = customer
return nil
}
// loadCustomers loads customers from a JSON file.
func loadCustomerData(path string) map[string]*auth.Customer {
file := data.MustAsset(path)
customers := []*auth.Customer{}
// unmarshal JSON
if err := json.Unmarshal(file, &customers); err != nil {
log.Fatalf("Failed to unmarshal json: %v", err)
}
// create customer lookup map
cache := make(map[string]*auth.Customer)
for _, c := range customers {
cache[c.AuthToken] = c
}
return cache
}
func main() {
service := micro.NewService(
micro.Name("go.micro.srv.auth"),
)
service.Init()
auth.RegisterAuthHandler(service.Server(), &Auth{
customers: loadCustomerData("data/customers.json"),
})
service.Run()
}