apps-durpcli/cmd/auth/generateToken.go

75 lines
1.7 KiB
Go
Raw Normal View History

2023-05-27 11:43:24 -05:00
package auth
import (
2024-06-23 09:49:14 -05:00
"context"
2023-05-27 11:43:24 -05:00
"fmt"
"net/http"
2024-06-23 09:49:14 -05:00
"github.com/cli/oauth/device"
2023-05-27 11:43:24 -05:00
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
type accessTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
IDToken string `json:"id_token"`
}
var (
clientID string
grantType string
url string
username string
password string
2023-07-17 07:33:29 -05:00
scope string
2023-05-27 11:43:24 -05:00
)
var generateTokenCmd = &cobra.Command{
Use: "generateToken",
Short: "Prints disk usage of the current directory",
Long: ``,
Run: func(cmd *cobra.Command, args []string) {
if clientID == "" {
clientID = viper.GetViper().GetString("auth.clientID")
}
2024-06-23 09:49:14 -05:00
generateToken(clientID)
2023-05-27 11:43:24 -05:00
},
}
func init() {
generateTokenCmd.Flags().StringVarP(&clientID, "clientID", "c", "", "The ClientID")
2023-07-17 07:33:29 -05:00
generateTokenCmd.Flags().
StringVarP(&grantType, "grantType", "g", "client_credentials", "The Grant Type")
2023-05-27 11:43:24 -05:00
generateTokenCmd.Flags().StringVarP(&url, "url", "", "", "Token URL")
AuthCmd.AddCommand(generateTokenCmd)
}
2023-07-17 07:33:29 -05:00
func generateToken(
clientID string,
) {
2024-06-23 09:49:14 -05:00
scopes := []string{"openid", "email", "profile"}
httpClient := http.DefaultClient
2023-05-27 11:43:24 -05:00
2024-06-23 09:49:14 -05:00
code, err := device.RequestCode(httpClient, "https://authentik.durp.info/application/o/device/", clientID, scopes)
2023-05-27 11:43:24 -05:00
if err != nil {
2024-06-23 09:49:14 -05:00
panic(err)
2023-05-27 11:43:24 -05:00
}
2024-06-23 09:49:14 -05:00
fmt.Printf("Copy code: %s\n", code.UserCode)
fmt.Printf("then open: %s\n", code.VerificationURIComplete)
2023-05-27 11:43:24 -05:00
2024-06-23 09:49:14 -05:00
accessToken, err := device.Wait(context.TODO(), httpClient, "https://authentik.durp.info/application/o/token/", device.WaitOptions{
ClientID: clientID,
DeviceCode: code,
GrantType: "urn:ietf:params:oauth:grant-type:device_code",
})
2023-05-27 11:43:24 -05:00
if err != nil {
2024-06-23 09:49:14 -05:00
panic(err)
2023-05-27 11:43:24 -05:00
}
2024-06-23 09:49:14 -05:00
fmt.Printf("Access token: %s\n", accessToken.Token)
2023-05-27 11:43:24 -05:00
}