forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
54 lines (44 loc) · 1.05 KB
/
auth.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
package sponsor
import (
"context"
"fmt"
"time"
"github.com/evcc-io/evcc/api/proto/pb"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/cloud"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
var (
Subject, Token string
ExpiresAt time.Time
)
func IsAuthorized() bool {
return len(Subject) > 0
}
// check and set sponsorship token
func ConfigureSponsorship(token string) error {
host := util.Getenv("GRPC_URI", cloud.Host)
conn, err := cloud.Connection(host)
if err != nil {
return err
}
client := pb.NewAuthClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
res, err := client.IsAuthorized(ctx, &pb.AuthRequest{Token: token})
if err == nil && res.Authorized {
Subject = res.Subject
ExpiresAt = res.ExpiresAt.AsTime()
Token = token
}
if err != nil {
if s, ok := status.FromError(err); ok && s.Code() != codes.Unknown {
Subject = "sponsorship unavailable"
err = nil
} else {
err = fmt.Errorf("sponsortoken: %w", err)
}
}
return err
}