fix: secret key is no longer hard coded

the secret key for signing JWT tokens is now read from server.secret.

if that does not exist, then a random UUID v4 is generated and used
instead. a log warning is also shown.
This commit is contained in:
Jordan Knott
2020-09-12 18:03:17 -05:00
parent 9fdb3008db
commit 52c60abcd7
7 changed files with 40 additions and 22 deletions

View File

@ -1,12 +1,15 @@
package commands
import (
"errors"
"fmt"
"strings"
"time"
"github.com/jordanknott/taskcafe/internal/auth"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
func newTokenCmd() *cobra.Command {
@ -15,13 +18,18 @@ func newTokenCmd() *cobra.Command {
Short: "Create a long lived JWT token for dev purposes",
Long: "Create a long lived JWT token for dev purposes",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
token, err := auth.NewAccessTokenCustomExpiration(args[0], time.Hour*24)
RunE: func(cmd *cobra.Command, args []string) error {
secret := viper.GetString("server.secret")
if strings.TrimSpace(secret) == "" {
return errors.New("server.secret must be set (TASKCAFE_SERVER_SECRET)")
}
token, err := auth.NewAccessTokenCustomExpiration(args[0], time.Hour*24, []byte(secret))
if err != nil {
log.WithError(err).Error("issue while creating access token")
return
return err
}
fmt.Println(token)
return nil
},
}
}

View File

@ -3,11 +3,13 @@ package commands
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/postgres"
"github.com/golang-migrate/migrate/v4/source/httpfs"
"github.com/google/uuid"
"github.com/spf13/cobra"
"github.com/spf13/viper"
@ -62,7 +64,12 @@ func newWebCmd() *cobra.Command {
}
log.WithFields(log.Fields{"url": viper.GetString("server.hostname")}).Info("starting server")
r, _ := route.NewRouter(db)
secret := viper.GetString("server.secret")
if strings.TrimSpace(secret) == "" {
log.Warn("server.secret is not set, generating a random secret")
secret = uuid.New().String()
}
r, _ := route.NewRouter(db, []byte(secret))
http.ListenAndServe(viper.GetString("server.hostname"), r)
return nil
},