Last active
April 17, 2023 02:34
-
-
Save reedom/3a33c75742bca2209cf07252edfdd655 to your computer and use it in GitHub Desktop.
Go Echo middleware that extract user info from Google Auth Token found in Authorization: Bearer header field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package echomw | |
| import ( | |
| "encoding/json" | |
| "io/ioutil" | |
| "net/http" | |
| "github.com/labstack/echo/v4" | |
| "github.com/labstack/echo/v4/middleware" | |
| "github.com/reedom/…/pkg/log" | |
| "github.com/reedom/…/pkg/service" | |
| "github.com/reedom/…/pkg/webservice" | |
| "go.uber.org/zap" | |
| ) | |
| type OpenIdProfile struct { | |
| ID string `json:"id"` | |
| EMail string `json:"email"` | |
| VerifiedEMail bool `json:"verified_email"` | |
| Name string `json:"name"` | |
| GivenName string `json:"given_name"` | |
| FamilyName string `json:"family_name"` | |
| Picture string `json:"picture"` | |
| Locale string `json:"locale"` | |
| HD string `json:"hd"` | |
| } | |
| func GoogleAuthMiddleware(skipper middleware.Skipper) echo.MiddlewareFunc { | |
| config := middleware.KeyAuthConfig{ | |
| Skipper: skipper, | |
| Validator: googleAuthValidator, | |
| } | |
| return middleware.KeyAuthWithConfig(config) | |
| } | |
| func googleAuthValidator(key string, e echo.Context) (bool, error) { | |
| log.Logger.Info("googleAuthValidator start") | |
| req, _ := http.NewRequest("GET", "https://www.googleapis.com/oauth2/v1/userinfo?alt=json", nil) | |
| req.Header.Add("Authorization", "Bearer "+key) | |
| req.Header.Add("Content-Type", "application/json") | |
| client := &http.Client{} | |
| resp, err := client.Do(req) | |
| if err != nil { | |
| log.Logger.Info("googleapis returns error", zap.Error(err)) | |
| return false, err | |
| } | |
| //noinspection GoUnhandledErrorResult | |
| defer resp.Body.Close() | |
| if 400 <= resp.StatusCode { | |
| log.Logger.Info("googleAuth fail", zap.String("status", resp.Status)) | |
| return false, nil | |
| } | |
| body, err := ioutil.ReadAll(resp.Body) | |
| log.Logger.Info("profile", zap.String("body", string(body))) | |
| var profile OpenIdProfile | |
| if err = json.Unmarshal(body, &profile); err != nil { | |
| log.Logger.Info("json.Unmarshal fail", zap.Error(err)) | |
| return false, err | |
| } | |
| user := service.AuthUser{ | |
| Email: profile.EMail, | |
| Name: profile.Name, | |
| UserID: profile.ID, | |
| } | |
| e.Set(webservice.AuthUserKey, user) | |
| return true, nil | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment