2023-03-07 23:10:42 +01:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
2023-03-13 10:44:58 +01:00
|
|
|
"forge.cadoles.com/Cadoles/emissary/internal/auth/thirdparty"
|
2023-03-07 23:10:42 +01:00
|
|
|
"forge.cadoles.com/Cadoles/emissary/internal/command/common"
|
|
|
|
"forge.cadoles.com/Cadoles/emissary/internal/jwk"
|
|
|
|
"github.com/lithammer/shortuuid/v4"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/urfave/cli/v2"
|
|
|
|
)
|
|
|
|
|
|
|
|
func CreateTokenCommand() *cli.Command {
|
|
|
|
return &cli.Command{
|
|
|
|
Name: "create-token",
|
2023-03-13 10:44:58 +01:00
|
|
|
Usage: "Create a new authentication token",
|
2023-03-07 23:10:42 +01:00
|
|
|
Flags: []cli.Flag{
|
|
|
|
&cli.StringFlag{
|
|
|
|
Name: "role",
|
2023-03-13 10:44:58 +01:00
|
|
|
Usage: fmt.Sprintf("associate `ROLE` to the token (available: %v)", []thirdparty.Role{thirdparty.RoleReader, thirdparty.RoleWriter}),
|
|
|
|
Value: string(thirdparty.RoleReader),
|
2023-03-07 23:10:42 +01:00
|
|
|
},
|
|
|
|
&cli.StringFlag{
|
|
|
|
Name: "subject",
|
|
|
|
Usage: "associate `SUBJECT` to the token",
|
|
|
|
Value: fmt.Sprintf("user-%s", shortuuid.New()),
|
|
|
|
},
|
|
|
|
},
|
|
|
|
Action: func(ctx *cli.Context) error {
|
|
|
|
conf, err := common.LoadConfig(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "Could not load configuration")
|
|
|
|
}
|
|
|
|
|
|
|
|
subject := ctx.String("subject")
|
|
|
|
role := ctx.String("role")
|
|
|
|
|
2023-07-26 15:14:49 +02:00
|
|
|
localAuth := conf.Server.Auth.Local
|
|
|
|
if localAuth == nil {
|
|
|
|
return errors.New("local auth is disabled")
|
|
|
|
}
|
|
|
|
|
|
|
|
key, err := jwk.LoadOrGenerate(string(localAuth.PrivateKeyPath), jwk.DefaultKeySize)
|
2023-03-07 23:10:42 +01:00
|
|
|
if err != nil {
|
|
|
|
return errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
2023-07-26 15:14:49 +02:00
|
|
|
token, err := thirdparty.GenerateToken(ctx.Context, key, subject, thirdparty.Role(role))
|
2023-03-07 23:10:42 +01:00
|
|
|
if err != nil {
|
|
|
|
return errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Println(token)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|