Skip to content

Commit

Permalink
Merge pull request #8 from pusher/handle-invalid-token-resp
Browse files Browse the repository at this point in the history
Handle invalid token response from google
  • Loading branch information
robertoles authored Sep 23, 2024
2 parents d7b27a1 + 09769c4 commit 7acae5f
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
22 changes: 20 additions & 2 deletions fcm.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,28 @@ func (c *fcmClient) GetInstanceInfo(token string) (*InstanceInformationResponse,
defer response.Body.Close()

switch response.StatusCode {
case 400:
errorResponseBytes, err := io.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("unable to read response from google: %w", err)
}

errorBody := ErrorResponse{}
err = json.Unmarshal(errorResponseBytes, &errorBody)
if err != nil {
return nil, fmt.Errorf("unable to read response from google: %w", err)
}

if errorBody.Error == "InvalidToken" {
return nil, ErrInvalidToken
}

return nil, ErrInvalidRequest

case 401, 403:
return nil, fmt.Errorf("invalid FCM Service Account File")
return nil, ErrInalidFCMServiceAccountFile
case 404:
return nil, fmt.Errorf("device not found")
return nil, ErrDeviceNotFound
}

if response.StatusCode > 299 {
Expand Down
2 changes: 1 addition & 1 deletion gcm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ type stubHttpClient struct {
Requests []string
}

func (c *stubHttpClient) send(apiKey string, message HttpMessage) (*HttpResponse, error) {
func (c *stubHttpClient) send(ctx context.Context, apiKey string, message HttpMessage) (*HttpResponse, error) {
response := &HttpResponse{}
err := json.Unmarshal([]byte(multicastReply[c.InvocationNum]), &response)
c.InvocationNum++
Expand Down
15 changes: 15 additions & 0 deletions requests.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
package googlemessaging

import (
"errors"
)

var (
ErrInvalidToken = errors.New("invalid token")
ErrDeviceNotFound = errors.New("device not found")
ErrInvalidRequest = errors.New("invalid request")
ErrInalidFCMServiceAccountFile = errors.New("invalid fcm service account file")
)

type FcmMessageBody struct {
Message *FcmHttpMessage `json:"message"`
}
Expand Down Expand Up @@ -52,3 +63,7 @@ type FcmSendHttpResponse struct {
type InstanceInformationResponse struct {
AuthorizedEntity string `json:"authorizedEntity"`
}

type ErrorResponse struct {
Error string `json:"error"`
}

0 comments on commit 7acae5f

Please sign in to comment.