github.com/lukasheimann/cloudfoundrycli@v7.1.0+incompatible/actor/v7action/auth.go (about) 1 package v7action 2 3 import ( 4 "encoding/base64" 5 "encoding/json" 6 "fmt" 7 "strings" 8 9 "code.cloudfoundry.org/cli/actor/actionerror" 10 "code.cloudfoundry.org/cli/api/uaa/constant" 11 "code.cloudfoundry.org/cli/cf/configuration/coreconfig" 12 ) 13 14 func (actor Actor) Authenticate(credentials map[string]string, origin string, grantType constant.GrantType) error { 15 if grantType == constant.GrantTypePassword && actor.Config.UAAGrantType() == string(constant.GrantTypeClientCredentials) { 16 return actionerror.PasswordGrantTypeLogoutRequiredError{} 17 } 18 19 actor.Config.UnsetOrganizationAndSpaceInformation() 20 accessToken, refreshToken, err := actor.UAAClient.Authenticate(credentials, origin, grantType) 21 if err != nil { 22 actor.Config.SetTokenInformation("", "", "") 23 return err 24 } 25 26 accessToken = fmt.Sprintf("bearer %s", accessToken) 27 actor.Config.SetTokenInformation(accessToken, refreshToken, "") 28 29 if grantType == constant.GrantTypePassword { 30 actor.Config.SetUAAGrantType("") 31 } else { 32 actor.Config.SetUAAGrantType(string(grantType)) 33 } 34 35 if grantType == constant.GrantTypeClientCredentials { 36 actor.Config.SetUAAClientCredentials(credentials["client_id"], "") 37 } 38 39 return nil 40 } 41 42 func (actor Actor) GetLoginPrompts() map[string]coreconfig.AuthPrompt { 43 rawPrompts := actor.UAAClient.LoginPrompts() 44 prompts := make(map[string]coreconfig.AuthPrompt) 45 for key, val := range rawPrompts { 46 prompts[key] = coreconfig.AuthPrompt{ 47 Type: knownAuthPromptTypes[val[0]], 48 DisplayName: val[1], 49 } 50 } 51 return prompts 52 } 53 54 // TODO: error check this in future stories 55 func (actor Actor) RevokeAccessAndRefreshTokens() error { 56 accessToken := actor.Config.AccessToken() 57 if actor.isTokenRevocable(accessToken) { 58 refreshToken := actor.Config.RefreshToken() 59 _ = actor.UAAClient.Revoke(refreshToken) 60 _ = actor.UAAClient.Revoke(accessToken) 61 } 62 return nil 63 } 64 65 func (actor Actor) isTokenRevocable(token string) bool { 66 segments := strings.Split(token, ".") 67 68 if len(segments) < 2 { 69 return false 70 } 71 72 jsonPayload, err := base64.RawURLEncoding.DecodeString(segments[1]) 73 74 if err != nil { 75 return false 76 } 77 78 payload := make(map[string]interface{}) 79 json.Unmarshal(jsonPayload, &payload) 80 revocable, ok := payload["revocable"].(bool) 81 82 if !ok { 83 return false 84 } 85 86 return revocable 87 } 88 89 var knownAuthPromptTypes = map[string]coreconfig.AuthPromptType{ 90 "text": coreconfig.AuthPromptTypeText, 91 "password": coreconfig.AuthPromptTypePassword, 92 }