2024-10-13 16:16:19 +03:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log/slog"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"git.a71.su/Andrew71/pye/auth"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
verifyToken string
|
|
|
|
verifyFile string
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
verifyCmd.Flags().StringVarP(&verifyToken, "token", "t", "", "token to verify")
|
|
|
|
verifyCmd.MarkFlagRequired("token")
|
2024-10-13 16:38:13 +03:00
|
|
|
verifyCmd.Flags().StringVarP(&verifyFile, "file", "f", "", "PEM file to use")
|
2024-10-13 16:16:19 +03:00
|
|
|
rootCmd.AddCommand(verifyCmd)
|
|
|
|
}
|
|
|
|
|
|
|
|
var verifyCmd = &cobra.Command{
|
|
|
|
Use: "verify",
|
|
|
|
Short: "Verify a JWT token",
|
2024-10-13 16:38:13 +03:00
|
|
|
Long: `Pass a JWT token (and optionally a path to a PEM-formatted file with the public key)
|
|
|
|
to verify whether it is valid.`,
|
2024-10-13 16:16:19 +03:00
|
|
|
Run: verifyFunc,
|
|
|
|
}
|
|
|
|
|
2024-10-13 16:38:13 +03:00
|
|
|
// TODO: Needs a better name?
|
2024-10-13 16:16:19 +03:00
|
|
|
func verifyFunc(cmd *cobra.Command, args []string) {
|
|
|
|
if verifyToken == "" {
|
|
|
|
fmt.Println("Empty token supplied!")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var t *jwt.Token
|
|
|
|
var err error
|
|
|
|
if verifyFile == "" {
|
|
|
|
fmt.Println("No PEM file supplied, assuming local")
|
2024-10-13 17:18:53 +03:00
|
|
|
t, err = auth.VerifyLocal(verifyToken)
|
2024-10-13 16:16:19 +03:00
|
|
|
} else {
|
|
|
|
key, err_k := os.ReadFile(verifyFile)
|
|
|
|
if err_k != nil {
|
|
|
|
slog.Error("error reading file", "error", err, "file", verifyFile)
|
|
|
|
return
|
|
|
|
}
|
2024-10-13 17:18:53 +03:00
|
|
|
t, err = auth.Verify(verifyToken, key)
|
2024-10-13 16:16:19 +03:00
|
|
|
}
|
2024-10-13 16:38:13 +03:00
|
|
|
slog.Debug("result", "token", t, "error", err, "ok", err == nil)
|
|
|
|
if err == nil {
|
|
|
|
fmt.Println("Token valid!")
|
|
|
|
} else {
|
|
|
|
fmt.Println("Token invalid!", err)
|
|
|
|
}
|
2024-10-13 16:16:19 +03:00
|
|
|
}
|