func (m *OauthMiddleware) ParamsMiddleware(h apollo.Handler) apollo.Handler { if len(m.ConfigParam) == 0 { m.ConfigParam = "config" } fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) { for _, p := range []string{"client_id", "scopes", "redirect_url", "state", "code"} { v := r.FormValue(p) if len(v) == 0 { http.Error(w, fmt.Sprintf("missing param %q", p), http.StatusBadRequest) return } } oauthConf := &OauthConfig{ Config: &oauth2.Config{ ClientID: r.FormValue("client_id"), RedirectURL: r.FormValue("redirect_url"), Scopes: strings.Split(r.FormValue("scopes"), " "), }, State: r.FormValue("state"), Code: r.FormValue("code"), } h.ServeHTTP(context.WithValue(ctx, m.ConfigParam, oauthConf), w, r) } return apollo.HandlerFunc(fn) }
func (m *OauthMiddleware) GoogleMiddleware(h apollo.Handler) apollo.Handler { fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) { oauthConf, ok := ctx.Value("config").(*OauthConfig) if !ok { http.Error(w, "unable to retrieve context", http.StatusInternalServerError) return } oauthConf.Config.ClientSecret = m.ClientSecret oauthConf.Config.Endpoint = m.Endpoint token, err := oauthConf.Exchange(oauth2.NoContext, oauthConf.Code) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } oauthClient := oauthConf.Client(oauth2.NoContext, token) resp, err := oauthClient.Get(user.Google) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } var google user.GoogleUser if err := json.NewDecoder(resp.Body).Decode(&google); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } user := &user.NormalizedUser{ Name: google.Name, Email: google.Email, } h.ServeHTTP(context.WithValue(ctx, "user", user), w, r) } return apollo.HandlerFunc(fn) }
func (m *OauthMiddleware) LinkedInMiddleware(h apollo.Handler) apollo.Handler { fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) { oauthConf, ok := ctx.Value("config").(*OauthConfig) if !ok { http.Error(w, "unable to retrieve context", http.StatusInternalServerError) return } oauthConf.Config.ClientSecret = m.ClientSecret oauthConf.Config.Endpoint = m.Endpoint token, err := oauthConf.Exchange(oauth2.NoContext, oauthConf.Code) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } oauthClient := oauthConf.Client(oauth2.NoContext, token) resp, err := oauthClient.Get(user.LinkedIn) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } var linkedin user.LinkedInUser if err := json.NewDecoder(resp.Body).Decode(&linkedin); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } user := &user.NormalizedUser{ Name: fmt.Sprintf("%s %s", linkedin.FirstName, linkedin.LastName), Email: linkedin.EmailAddress, } h.ServeHTTP(context.WithValue(ctx, "user", user), w, r) } return apollo.HandlerFunc(fn) }