pye/internal/app/verify.go

59 lines
1.3 KiB
Go
Raw Permalink Normal View History

2024-10-13 21:03:44 +03:00
package app
2024-10-13 16:16:19 +03:00
import (
"fmt"
"log/slog"
"os"
2024-10-13 21:03:44 +03:00
"git.a71.su/Andrew71/pye/internal/auth"
2024-10-13 16:16:19 +03:00
"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 21:26:03 +03:00
Run: verify,
2024-10-13 16:16:19 +03:00
}
2024-10-13 21:26:03 +03:00
func verify(cmd *cobra.Command, args []string) {
2024-10-13 16:16:19 +03:00
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 21:26:03 +03:00
t, err = auth.VerifyLocalToken(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 21:26:03 +03:00
t, err = auth.VerifyToken(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
}