github.com/ActiveState/cli@v0.0.0-20240508170324-6801f60cd051/pkg/platform/model/auth/auth.go (about) 1 package model 2 3 import ( 4 "github.com/ActiveState/cli/internal/errs" 5 "github.com/ActiveState/cli/internal/locale" 6 "github.com/ActiveState/cli/internal/logging" 7 "github.com/ActiveState/cli/pkg/platform/api" 8 "github.com/ActiveState/cli/pkg/platform/api/mono" 9 "github.com/ActiveState/cli/pkg/platform/api/mono/mono_client/oauth" 10 mms "github.com/ActiveState/cli/pkg/platform/api/mono/mono_models" 11 "github.com/go-openapi/strfmt" 12 ) 13 14 // RequestDeviceAuthorization posts a request to authorize this device on the Platform and 15 // returns the device code needed for authorization. 16 // The user is subsequently required to visit the device code's URI and click the "Authorize" 17 // button. 18 func RequestDeviceAuthorization() (*mms.DeviceCode, error) { 19 postParams := oauth.NewAuthDevicePostParams() 20 response, err := mono.Get().Oauth.AuthDevicePost(postParams) 21 if err != nil { 22 return nil, errs.Wrap(err, "Could not request device authentication") 23 } 24 25 return response.Payload, nil 26 } 27 28 func CheckDeviceAuthorization(deviceCode strfmt.UUID) (jwt *mms.JWT, apiKey *mms.NewToken, err error) { 29 getParams := oauth.NewAuthDeviceGetParams() 30 getParams.SetDeviceCode(deviceCode) 31 32 response, err := mono.Get().Oauth.AuthDeviceGet(getParams) 33 if err != nil { 34 // Identify input or benign errors 35 if errs.Matches(err, &oauth.AuthDeviceGetBadRequest{}) { 36 errorToken := err.(*oauth.AuthDeviceGetBadRequest).Payload.Error 37 switch *errorToken { 38 case oauth.AuthDeviceGetBadRequestBodyErrorAuthorizationPending, oauth.AuthDeviceGetBadRequestBodyErrorSlowDown: 39 logging.Debug("Authorization still pending") 40 return nil, nil, nil 41 case oauth.AuthDeviceGetBadRequestBodyErrorExpiredToken: 42 return nil, nil, locale.WrapExternalError(err, "auth_device_timeout") 43 } 44 } 45 46 return nil, nil, errs.Wrap(err, api.ErrorMessageFromPayload(err)) 47 } 48 49 return response.Payload.AccessToken, response.Payload.RefreshToken, nil 50 }