github.com/goravel/framework@v1.13.9/auth/console/jwt_secret_command.go (about) 1 package console 2 3 import ( 4 "errors" 5 "os" 6 "strings" 7 8 "github.com/gookit/color" 9 10 "github.com/goravel/framework/contracts/config" 11 "github.com/goravel/framework/contracts/console" 12 "github.com/goravel/framework/contracts/console/command" 13 "github.com/goravel/framework/support" 14 "github.com/goravel/framework/support/str" 15 ) 16 17 type JwtSecretCommand struct { 18 config config.Config 19 } 20 21 func NewJwtSecretCommand(config config.Config) *JwtSecretCommand { 22 return &JwtSecretCommand{config: config} 23 } 24 25 // Signature The name and signature of the console command. 26 func (receiver *JwtSecretCommand) Signature() string { 27 return "jwt:secret" 28 } 29 30 // Description The console command description. 31 func (receiver *JwtSecretCommand) Description() string { 32 return "Set the JWTAuth secret key used to sign the tokens" 33 } 34 35 // Extend The console command extend. 36 func (receiver *JwtSecretCommand) Extend() command.Extend { 37 return command.Extend{ 38 Category: "jwt", 39 } 40 } 41 42 // Handle Execute the console command. 43 func (receiver *JwtSecretCommand) Handle(ctx console.Context) error { 44 key := receiver.generateRandomKey() 45 46 if err := receiver.setSecretInEnvironmentFile(key); err != nil { 47 color.Redln(err.Error()) 48 49 return nil 50 } 51 52 color.Greenln("Jwt Secret set successfully") 53 54 return nil 55 } 56 57 // generateRandomKey Generate a random key for the application. 58 func (receiver *JwtSecretCommand) generateRandomKey() string { 59 return str.Random(32) 60 } 61 62 // setSecretInEnvironmentFile Set the application key in the environment file. 63 func (receiver *JwtSecretCommand) setSecretInEnvironmentFile(key string) error { 64 currentKey := receiver.config.GetString("jwt.secret") 65 66 if currentKey != "" { 67 return errors.New("Exist jwt secret") 68 } 69 70 err := receiver.writeNewEnvironmentFileWith(key) 71 72 if err != nil { 73 return err 74 } 75 76 return nil 77 } 78 79 // writeNewEnvironmentFileWith Write a new environment file with the given key. 80 func (receiver *JwtSecretCommand) writeNewEnvironmentFileWith(key string) error { 81 content, err := os.ReadFile(support.EnvPath) 82 if err != nil { 83 return err 84 } 85 86 newContent := strings.Replace(string(content), "JWT_SECRET="+receiver.config.GetString("jwt.secret"), "JWT_SECRET="+key, 1) 87 88 err = os.WriteFile(support.EnvPath, []byte(newContent), 0644) 89 if err != nil { 90 return err 91 } 92 93 return nil 94 }