Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use refresh_token instead of grant_token #82

Merged
merged 5 commits into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 5 additions & 24 deletions cmd/other/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -451,10 +451,7 @@ func executeUserLogin(currentEnv string) {
}

accessToken, refreshToken, newAccessToken, err := getValidTokens(currentEnv)
if err == nil && refreshToken != "" && !isTokenExpired(refreshToken) {
// Use existing valid refresh token
accessToken = newAccessToken
} else {
if err != nil || refreshToken == "" || isTokenExpired(refreshToken) {
// Get new tokens with password
password := promptPassword()
accessToken, refreshToken, err = issueToken(baseUrl, tempUserID, password, domainID)
Expand Down Expand Up @@ -1598,7 +1595,7 @@ func validateAndDecodeToken(token string) (map[string]interface{}, error) {
}

// Check required fields
requiredFields := []string{"exp", "rol", "did"}
requiredFields := []string{"exp", "did"}
for _, field := range requiredFields {
if _, ok := claims[field]; !ok {
return nil, fmt.Errorf("invalid token format: missing required field '%s'", field)
Expand Down Expand Up @@ -1668,34 +1665,18 @@ func getValidTokens(currentEnv string) (accessToken, refreshToken, newAccessToke

envCacheDir := filepath.Join(homeDir, ".cfctl", "cache", currentEnv)

// Try to read and validate grant token first
if newAccessToken, err = readTokenFromFile(envCacheDir, "grant_token"); err == nil {
claims, err := validateAndDecodeToken(newAccessToken)
if refreshToken, err = readTokenFromFile(envCacheDir, "refresh_token"); err == nil {
claims, err := validateAndDecodeToken(refreshToken)
if err == nil {
// Check if token has expired
if exp, ok := claims["exp"].(float64); ok {
if time.Now().Unix() < int64(exp) {
accessToken, _ = readTokenFromFile(envCacheDir, "access_token")
refreshToken, _ = readTokenFromFile(envCacheDir, "refresh_token")
newAccessToken, _ = readTokenFromFile(envCacheDir, "grant_token")
return accessToken, refreshToken, newAccessToken, nil
}
}
}
}

// If grant token is invalid or expired, check refresh token
if accessToken, err = readTokenFromFile(envCacheDir, "access_token"); err == nil {
if refreshToken, err = readTokenFromFile(envCacheDir, "refresh_token"); err == nil {
claims, err := validateAndDecodeToken(refreshToken)
if err == nil {
if exp, ok := claims["exp"].(float64); ok {
if time.Now().Unix() < int64(exp) {
return accessToken, refreshToken, "", nil
}
}
}
}
}

return "", "", "", fmt.Errorf("no valid tokens found")
}
19 changes: 9 additions & 10 deletions cmd/other/setting.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@ var settingInitURLCmd = &cobra.Command{
Short: "Initialize configuration with a URL",
Long: `Specify a URL to initialize the environment configuration.`,
Args: cobra.NoArgs,
Example: ` cfctl setting init url -u https://spaceone.spaceone.megazone.io --app
Example: ` cfctl setting init url -u https://example.com --app
or
cfctl setting init url -u https://spaceone.spaceone.megazone.io --user`,
cfctl setting init url -u https://example.com --user`,
Run: func(cmd *cobra.Command, args []string) {
urlStr, _ := cmd.Flags().GetString("url")
appFlag, _ := cmd.Flags().GetBool("app")
Expand Down Expand Up @@ -182,7 +182,7 @@ var settingInitLocalCmd = &cobra.Command{
if appFlag {
updateLocalSetting(envName, "app", mainSettingPath)
} else {
updateLocalSetting(envName, "user", filepath.Join(settingDir, "cache", "setting.toml"))
updateLocalSetting(envName, "user", mainSettingPath)
}

// Update the current environment in the main setting
Expand Down Expand Up @@ -226,7 +226,12 @@ func updateLocalSetting(envName, settingType, settingPath string) {

// Set environment configuration
v.Set(fmt.Sprintf("environments.%s.endpoint", envName), "grpc://localhost:50051")
v.Set(fmt.Sprintf("environments.%s.token", envName), "")
if settingType == "app" {
v.Set(fmt.Sprintf("environments.%s.token", envName), "")
v.Set(fmt.Sprintf("environments.%s.proxy", envName), true)
} else if settingType == "user" {
v.Set(fmt.Sprintf("environments.%s.proxy", envName), false)
}

// Write configuration
if err := v.WriteConfig(); err != nil {
Expand Down Expand Up @@ -404,12 +409,6 @@ var showCmd = &cobra.Command{
return
}

// Load user configuration
if err := loadSetting(userV, userSettingPath); err != nil {
pterm.Error.Println(err)
return
}

currentEnv := getCurrentEnvironment(appV)
if currentEnv == "" {
pterm.Sprintf("No environment set in %s\n", appSettingPath)
Expand Down
17 changes: 12 additions & 5 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,18 @@ func init() {
pterm.DisableColor()
}

// Skip configuration check for settings init commands
if len(os.Args) >= 3 && os.Args[1] == "settings" && os.Args[2] == "init" {
// Skip configuration check for initialization
} else {
// Try to add dynamic service commands
// Determine if the current command is 'setting environment -l'
skipDynamicCommands := false
if len(os.Args) >= 3 && os.Args[1] == "setting" && os.Args[2] == "environment" {
for _, arg := range os.Args[3:] {
if arg == "-l" || arg == "--list" {
skipDynamicCommands = true
break
}
}
}

if !skipDynamicCommands {
if err := addDynamicServiceCommands(); err != nil {
showInitializationGuide(err)
}
Expand Down
Loading