-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt_secret_command.go
94 lines (71 loc) · 2.24 KB
/
jwt_secret_command.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
package console
import (
"errors"
"os"
"strings"
"github.com/gookit/color"
"github.com/wesleysnt/framework/contracts/config"
"github.com/wesleysnt/framework/contracts/console"
"github.com/wesleysnt/framework/contracts/console/command"
"github.com/wesleysnt/framework/support"
"github.com/wesleysnt/framework/support/str"
)
type JwtSecretCommand struct {
config config.Config
}
func NewJwtSecretCommand(config config.Config) *JwtSecretCommand {
return &JwtSecretCommand{config: config}
}
// Signature The name and signature of the console command.
func (receiver *JwtSecretCommand) Signature() string {
return "jwt:secret"
}
// Description The console command description.
func (receiver *JwtSecretCommand) Description() string {
return "Set the JWTAuth secret key used to sign the tokens"
}
// Extend The console command extend.
func (receiver *JwtSecretCommand) Extend() command.Extend {
return command.Extend{
Category: "jwt",
}
}
// Handle Execute the console command.
func (receiver *JwtSecretCommand) Handle(ctx console.Context) error {
key := receiver.generateRandomKey()
if err := receiver.setSecretInEnvironmentFile(key); err != nil {
color.Redln(err.Error())
return nil
}
color.Greenln("Jwt Secret set successfully")
return nil
}
// generateRandomKey Generate a random key for the application.
func (receiver *JwtSecretCommand) generateRandomKey() string {
return str.Random(32)
}
// setSecretInEnvironmentFile Set the application key in the environment file.
func (receiver *JwtSecretCommand) setSecretInEnvironmentFile(key string) error {
currentKey := receiver.config.GetString("jwt.secret")
if currentKey != "" {
return errors.New("Exist jwt secret")
}
err := receiver.writeNewEnvironmentFileWith(key)
if err != nil {
return err
}
return nil
}
// writeNewEnvironmentFileWith Write a new environment file with the given key.
func (receiver *JwtSecretCommand) writeNewEnvironmentFileWith(key string) error {
content, err := os.ReadFile(support.EnvPath)
if err != nil {
return err
}
newContent := strings.Replace(string(content), "JWT_SECRET="+receiver.config.GetString("jwt.secret"), "JWT_SECRET="+key, 1)
err = os.WriteFile(support.EnvPath, []byte(newContent), 0644)
if err != nil {
return err
}
return nil
}