-
Notifications
You must be signed in to change notification settings - Fork 0
/
discovery_authorize.go
69 lines (59 loc) · 1.95 KB
/
discovery_authorize.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
// Copyright © 2017 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
package cmd
import (
"fmt"
"time"
"github.com/TheThingsNetwork/go-account-lib/claims"
"github.com/TheThingsNetwork/ttn/utils/security"
jwt "github.com/dgrijalva/jwt-go"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var discoveryAuthorizeCmd = &cobra.Command{
Hidden: true,
Use: "authorize [router/broker/handler] [id]",
Short: "Generate a token that components should use to announce themselves",
Long: `ttn discovery authorize generates a token that components should use to announce themselves`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 2 {
cmd.UsageFunc()(cmd)
return
}
privKey, err := security.LoadKeypair(viper.GetString("key-dir"))
if err != nil {
ctx.WithError(err).Fatal("Could not load security keys")
}
ttl, err := cmd.Flags().GetInt("valid")
if err != nil {
ctx.WithError(err).Fatal("Could not read TTL")
}
issuer, err := cmd.Flags().GetString("issuer")
if err != nil {
ctx.WithError(err).Fatal("Could not read issuer ID")
}
var claims claims.ComponentClaims
claims.Subject = args[1]
claims.Type = args[0]
claims.Issuer = issuer
claims.IssuedAt = time.Now().Unix()
claims.NotBefore = time.Now().Unix()
if ttl > 0 {
claims.ExpiresAt = time.Now().Add(time.Duration(ttl) * time.Hour * 24).Unix()
}
tokenBuilder := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
token, err := tokenBuilder.SignedString(privKey)
if err != nil {
ctx.WithError(err).Fatal("Could not sign JWT")
}
ctx.WithField("ID", args[0]).Info("Generated token")
fmt.Println()
fmt.Println(token)
fmt.Println()
},
}
func init() {
discoveryCmd.AddCommand(discoveryAuthorizeCmd)
discoveryAuthorizeCmd.Flags().Int("valid", 0, "The number of days the token is valid")
discoveryAuthorizeCmd.Flags().String("issuer", "local", "The issuer ID to use")
}