How to use ErrorHandler method of oauth Package

Best Testkube code snippet using oauth.ErrorHandler

access_tokens_test.go

Source:access_tokens_test.go Github

copy

Full Screen

...17 routeSet := AccessTokens{18 Callbacks: make(map[string]chan OAuthCallback),19 Client: auth.FakeOauthConfig(),20 }21 errorHandler := FakeErrorHandler{}22 router := mux.NewRouter()23 router.HandleFunc("/authenticate", errorHandler.Handle(routeSet.Authenticate))24 router.ServeHTTP(recorder, req)25 response := recorder.Result()26 expectedRedirect := fmt.Sprintf(27 "https://example.org/auth?access_type=offline&client_id=%s&redirect_uri=%s&response_type=%s&scope=%s&state=%s",28 "the-client-id",29 url.QueryEscape("https://draupnir.org/redirect"),30 "code",31 "the-scope",32 "foo",33 )34 assert.Equal(t, http.StatusFound, response.StatusCode)35 assert.Equal(t, []string{expectedRedirect}, response.Header["Location"])36 assert.Equal(t, 0, len(recorder.Body.Bytes()))37 assert.Nil(t, errorHandler.Error)38}39func TestCallback(t *testing.T) {40 state := "foo"41 code := "some_code"42 _error := ""43 path := oauthCallbackPath(state, code, _error)44 req, recorder, logs := createRequest(t, "GET", path, nil)45 callback := make(chan OAuthCallback, 1)46 callbacks := make(map[string]chan OAuthCallback)47 callbacks[state] = callback48 oauthClient := auth.FakeOAuthClient{49 MockExchange: func(ctx context.Context, _code string) (*oauth2.Token, error) {50 assert.Equal(t, code, _code)51 return &oauth2.Token{RefreshToken: "the-access-token"}, nil52 },53 }54 errorHandler := FakeErrorHandler{}55 routeSet := AccessTokens{Callbacks: callbacks, Client: &oauthClient}56 router := mux.NewRouter()57 router.HandleFunc("/oauth_callback", errorHandler.Handle(routeSet.Callback))58 router.ServeHTTP(recorder, req)59 response := recorder.Result()60 responseBody := bytes.Buffer{}61 if _, err := responseBody.ReadFrom(response.Body); err != nil {62 t.Fatal(err)63 }64 assert.Equal(t, http.StatusOK, response.StatusCode)65 assert.Equal(t, []string{"text/html"}, response.Header["Content-Type"])66 assert.Contains(t, responseBody.String(), "Success!")67 assert.Empty(t, logs.String())68 assert.Nil(t, errorHandler.Error)69 select {70 case result := <-callback:71 assert.Equal(t, OAuthCallback{Token: oauth2.Token{RefreshToken: "the-access-token"}, Error: nil}, result)72 default:73 t.Fatal("Received nothing in channel")74 }75}76func TestCallbackWithResponseError(t *testing.T) {77 state := "foo"78 code := "some_code"79 _error := "some_error"80 path := oauthCallbackPath(state, code, _error)81 req, recorder, _ := createRequest(t, "GET", path, nil)82 callback := make(chan OAuthCallback, 1)83 callbacks := make(map[string]chan OAuthCallback)84 callbacks[state] = callback85 errorHandler := FakeErrorHandler{}86 routeSet := AccessTokens{Callbacks: callbacks}87 router := mux.NewRouter()88 router.HandleFunc("/oauth_callback", errorHandler.Handle(routeSet.Callback))89 router.ServeHTTP(recorder, req)90 response := recorder.Result()91 responseBody := bytes.Buffer{}92 if _, err := responseBody.ReadFrom(response.Body); err != nil {93 t.Fatal(err)94 }95 assert.Equal(t, http.StatusOK, response.StatusCode)96 assert.Empty(t, responseBody.String())97 assert.Equal(t, "some_error", errorHandler.Error.Error())98 select {99 case result := <-callback:100 err := result.Error101 assert.Equal(t, _error, err.Error())102 default:103 t.Fatal("Received nothing in channel")104 }105}106func TestCallbackWithEmptyResponseCode(t *testing.T) {107 state := "foo"108 code := ""109 _error := ""110 path := oauthCallbackPath(state, code, _error)111 req, recorder, logs := createRequest(t, "GET", path, nil)112 callback := make(chan OAuthCallback, 1)113 callbacks := make(map[string]chan OAuthCallback)114 callbacks[state] = callback115 errorHandler := FakeErrorHandler{}116 routeSet := AccessTokens{Callbacks: callbacks}117 router := mux.NewRouter()118 router.HandleFunc("/oauth_callback", errorHandler.Handle(routeSet.Callback))119 router.ServeHTTP(recorder, req)120 response := recorder.Result()121 responseBody := bytes.Buffer{}122 if _, err := responseBody.ReadFrom(response.Body); err != nil {123 t.Fatal(err)124 }125 assert.Equal(t, http.StatusOK, response.StatusCode)126 assert.Empty(t, responseBody.String())127 assert.Contains(t, logs.String(), "msg=\"empty oauth response code\"")128 assert.Equal(t, "OAuth callback response code is empty", errorHandler.Error.Error())129 select {130 case result := <-callback:131 err := result.Error132 assert.Equal(t, "OAuth callback response code is empty", err.Error())133 default:134 t.Fatal("Received nothing in channel")135 }136}137func TestCallbackWithFailedTokenExchange(t *testing.T) {138 state := "foo"139 code := "some_code"140 _error := ""141 path := oauthCallbackPath(state, code, _error)142 req, recorder, logs := createRequest(t, "GET", path, nil)143 callback := make(chan OAuthCallback, 1)144 callbacks := make(map[string]chan OAuthCallback)145 callbacks[state] = callback146 oauthClient := auth.FakeOAuthClient{147 MockExchange: func(ctx context.Context, _code string) (*oauth2.Token, error) {148 assert.Equal(t, code, _code)149 return &oauth2.Token{}, errors.New("token exchange failed")150 },151 }152 errorHandler := FakeErrorHandler{}153 routeSet := AccessTokens{Callbacks: callbacks, Client: &oauthClient}154 router := mux.NewRouter()155 router.HandleFunc("/oauth_callback", errorHandler.Handle(routeSet.Callback))156 router.ServeHTTP(recorder, req)157 response := recorder.Result()158 responseBody := bytes.Buffer{}159 if _, err := responseBody.ReadFrom(response.Body); err != nil {160 t.Fatal(err)161 }162 assert.Equal(t, http.StatusOK, response.StatusCode)163 assert.Empty(t, responseBody.String())164 assert.Empty(t, logs.String())165 assert.Equal(t, "token exchange error: token exchange failed", errorHandler.Error.Error())166 select {167 case result := <-callback:168 err := result.Error169 assert.Equal(t, "token exchange error: token exchange failed", err.Error())170 default:171 t.Fatal("Received nothing in channel")172 }173}174func TestCallbackWithTimedOutTokenExchange(t *testing.T) {175 state := "foo"176 code := "some_code"177 _error := ""178 path := oauthCallbackPath(state, code, _error)179 req, recorder, logs := createRequest(t, "GET", path, nil)180 // Set the request to time out immediately181 ctx, _ := context.WithTimeout(req.Context(), 0)182 req = req.WithContext(ctx)183 callback := make(chan OAuthCallback, 1)184 callbacks := make(map[string]chan OAuthCallback)185 callbacks[state] = callback186 oauthClient := auth.FakeOAuthClient{187 MockExchange: func(ctx context.Context, _code string) (*oauth2.Token, error) {188 assert.Equal(t, code, _code)189 select {190 case <-ctx.Done():191 return &oauth2.Token{}, errors.New("timeout")192 }193 },194 }195 errorHandler := FakeErrorHandler{}196 routeSet := AccessTokens{Callbacks: callbacks, Client: &oauthClient}197 router := mux.NewRouter()198 router.HandleFunc("/oauth_callback", errorHandler.Handle(routeSet.Callback))199 router.ServeHTTP(recorder, req)200 response := recorder.Result()201 responseBody := bytes.Buffer{}202 if _, err := responseBody.ReadFrom(response.Body); err != nil {203 t.Fatal(err)204 }205 assert.Equal(t, http.StatusOK, response.StatusCode)206 assert.Empty(t, responseBody.String())207 assert.Empty(t, logs.String())208 assert.Equal(t, errorHandler.Error.Error(), "token exchange error: timeout")209 select {...

Full Screen

Full Screen

oauth_handler.go

Source:oauth_handler.go Github

copy

Full Screen

...9type oauthHandlerImpl struct {10 Config11 storage OAuthTokenStorage12 handler http.Handler13 errorHandler ErrorHandler14}15// NewOAuthHandler instantiates a new Shopify embedded app handler, from the16// specified configuration.17//18// A typical usage of the handler is to serve the `index.html` page of a19// Shopify embedded app.20//21// Upon a successful request, the handler stores or refreshes authentication22// information on the client side, in the form of a cookie.23//24// The handler also stores the Shopify API key in a cookie named25// `shopify-api-key`.26//27// Javascript admin apps can use that cookie to actually configure their28// embedding in the Shopify admin portal.29func NewOAuthHandler(handler http.Handler, storage OAuthTokenStorage, config *Config, errorHandler ErrorHandler) http.Handler {30 if storage == nil {31 panic("An OAuth token storage is required.")32 }33 if config == nil {34 panic("A configuration is required.")35 }36 h := oauthHandlerImpl{37 Config: *config,38 storage: storage,39 handler: newHMACHandler(handler, config.APISecret),40 errorHandler: errorHandler,41 }42 return h43}44func (h oauthHandlerImpl) handleError(w http.ResponseWriter, req *http.Request, err error) {45 if h.errorHandler != nil {46 h.errorHandler.ServeHTTPError(w, req, err)47 return48 }49 w.Header().Set("Content-Type", "text/plain")50 w.WriteHeader(http.StatusInternalServerError)51 fmt.Fprintf(w, "Internal server error: you may contact the application adminstrator.\n")52}53const (54 shopifyAPIKeyCookieName = `shopify-api-key`55 shopifyShopCookieName = `shopify-shop`56)57func (h oauthHandlerImpl) ServeHTTP(w http.ResponseWriter, req *http.Request) {58 shop := shopify.Shop(req.URL.Query().Get("shop"))59 if shop == "" {60 w.WriteHeader(http.StatusBadRequest)61 fmt.Fprintf(w, "Missing `shop` parameter.")62 return63 }64 state := req.URL.Query().Get("state")65 // If we have a state, assume we are being called back after an install/update.66 if state != "" {67 h.handleInstallationCallback(w, req, shop, state)68 return69 }70 // Load any existing OAuth token for that shop.71 oauthToken, err := h.storage.GetOAuthToken(req.Context(), shop)72 if err != nil {73 h.handleError(w, req, fmt.Errorf("failed to load OAuth token for `%s`: %s", shop, err))74 return75 }76 // If we don't have a token yet for that shop, redirect for the OAuth page.77 if oauthToken == nil {78 h.redirectToInstall(w, req, shop)79 return80 }81 stok := &sessionToken{82 Shop: shop,83 OAuthToken: *oauthToken,84 }85 http.SetCookie(w, stok.AsCookie())86 http.SetCookie(w, &http.Cookie{87 Name: shopifyAPIKeyCookieName,88 Value: string(h.APIKey),89 Secure: true,90 })91 http.SetCookie(w, &http.Cookie{92 Name: shopifyShopCookieName,93 Value: string(shop),94 Secure: true,95 })96 req = req.WithContext(withSessionToken(req.Context(), stok))97 h.handler.ServeHTTP(w, req)98}99func (h oauthHandlerImpl) redirectToInstall(w http.ResponseWriter, req *http.Request, shop shopify.Shop) {100 state, err := generateRandomState()101 if err != nil {102 w.WriteHeader(http.StatusInternalServerError)103 fmt.Fprintf(w, "Unexpected error. Please contact the App's administrator.")104 return105 }106 oauthURL := &url.URL{107 Scheme: "https",108 Host: string(shop),109 Path: "/admin/oauth/authorize",110 }111 q := oauthURL.Query()112 q.Set("client_id", string(h.APIKey))113 q.Set("scope", h.Scope.String())114 q.Set("state", state)115 q.Set("redirect_uri", h.PublicURL.String())116 oauthURL.RawQuery = q.Encode()117 // Set a cookie to ensure the auth callback is really called by the right118 // entity.119 http.SetCookie(w, &http.Cookie{Name: "state", Value: state})120 // Redirect the browser to the OAuth autorization page.121 clientRedirect(w, req, oauthURL.String())122}123func (h oauthHandlerImpl) handleInstallationCallback(w http.ResponseWriter, req *http.Request, shop shopify.Shop, state string) {124 stateCookie, err := req.Cookie("state")125 if err != nil {126 w.WriteHeader(http.StatusBadRequest)127 fmt.Fprintf(w, "Missing `state` cookie.")128 return129 }130 if stateCookie.Value != state {131 w.WriteHeader(http.StatusForbidden)132 fmt.Fprintf(w, "A different `state` value was expected.")133 return134 }135 code := req.URL.Query().Get("code")136 if code == "" {137 w.WriteHeader(http.StatusBadRequest)138 fmt.Fprintf(w, "Missing `code` parameter.")139 return140 }141 req = req.WithContext(shopify.WithShop(req.Context(), shop))142 oauthToken, err := shopify.DefaultAdminClient.GetOAuthToken(req.Context(), h.APIKey, h.APISecret, code)143 if err != nil {144 h.handleError(w, req, fmt.Errorf("get OAuth token from Shopify for `%s`: %s", shop, err))145 return146 }147 if err = h.storage.UpdateOAuthToken(req.Context(), shop, *oauthToken); err != nil {148 h.handleError(w, req, fmt.Errorf("updating OAuth token for `%s`: %s", shop, err))149 return150 }151 // Remove the state cookie.152 http.SetCookie(w, &http.Cookie{153 Name: "state",154 MaxAge: -1,155 })156 // Redirect the browser to the main page.157 //158 // Make sure parameters are correct or we will redirect to an error page.159 query := url.Values{}160 query.Set("shop", string(shop))161 injectHMAC(query, h.APISecret)162 redirectURL := &url.URL{163 Scheme: h.PublicURL.Scheme,164 Host: h.PublicURL.Host,165 Path: h.PublicURL.Path,166 RawQuery: query.Encode(),167 }168 clientRedirect(w, req, redirectURL.String())169}170// NewOAuthMiddleware instantiates a new Shopify embedded app middleware, from171// the specified configuration.172//173// A typical usage of the handler is to serve the `index.html` page of a174// Shopify embedded app.175//176// Upon a successful request, the handler stores or refreshes authentication177// information on the client side, in the form of a cookie.178func NewOAuthMiddleware(storage OAuthTokenStorage, config *Config, errorHandler ErrorHandler) func(http.Handler) http.Handler {179 return func(handler http.Handler) http.Handler {180 return NewOAuthHandler(handler, storage, config, errorHandler)181 }182}183func clientRedirect(w http.ResponseWriter, req *http.Request, url string) {184 html := fmt.Sprintf(`185<html>186 <head>187 <script>188 if (window.self === window.top) {189 window.location.href = '%s';190 } else {191 window.top.location.href = '%s';192 }...

Full Screen

Full Screen

proxy_handler.go

Source:proxy_handler.go Github

copy

Full Screen

...7type proxyHandlerImpl struct {8 Config9 storage OAuthTokenStorage10 handler http.Handler11 errorHandler ErrorHandler12}13// NewProxyHandler instantiates a new Shopify proxy handler, from the specified14// configuration.15//16// A typical usage of the handler is to serve pages, scripts or APIs through a17// Shopify App proxy, usually from the storefront.18func NewProxyHandler(handler http.Handler, storage OAuthTokenStorage, config *Config, errorHandler ErrorHandler) http.Handler {19 if storage == nil {20 panic("An OAuth token storage is required.")21 }22 if config == nil {23 panic("A configuration is required.")24 }25 h := proxyHandlerImpl{26 Config: *config,27 storage: storage,28 handler: handler,29 errorHandler: errorHandler,30 }31 return newSignatureHandler(h, h.APISecret)32}33func (h proxyHandlerImpl) handleError(w http.ResponseWriter, req *http.Request, err error) {34 if h.errorHandler != nil {35 h.errorHandler.ServeHTTPError(w, req, err)36 return37 }38 w.Header().Set("Content-Type", "text/plain")39 w.WriteHeader(http.StatusInternalServerError)40 fmt.Fprintf(w, "Internal server error: you may contact the application adminstrator.\n")41}42func (h proxyHandlerImpl) ServeHTTP(w http.ResponseWriter, req *http.Request) {43 shop := shopify.Shop(req.URL.Query().Get("shop"))44 if shop == "" {45 w.WriteHeader(http.StatusBadRequest)46 fmt.Fprintf(w, "Missing `shop` parameter.")47 return48 }49 // Load any existing OAuth token for that shop.50 oauthToken, err := h.storage.GetOAuthToken(req.Context(), shop)51 if err != nil {52 h.handleError(w, req, fmt.Errorf("failed to load OAuth token for `%s`: %s", shop, err))53 return54 }55 // If we don't have a token yet for that shop, redirect for the OAuth page.56 if oauthToken == nil {57 h.handleError(w, req, fmt.Errorf("no OAuth token for `%s`", shop))58 return59 }60 stok := &sessionToken{61 Shop: shop,62 OAuthToken: *oauthToken,63 }64 req = req.WithContext(withSessionToken(req.Context(), stok))65 h.handler.ServeHTTP(w, req)66}67// NewProxyMiddleware instantiates a new proxy middleware.68func NewProxyMiddleware(storage OAuthTokenStorage, config *Config, errorHandler ErrorHandler) func(http.Handler) http.Handler {69 return func(handler http.Handler) http.Handler {70 return NewProxyHandler(handler, storage, config, errorHandler)71 }72}...

Full Screen

Full Screen

ErrorHandler

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.HandleFunc("/", oauth.ErrorHandler)4 http.ListenAndServe(":8080", nil)5}6import (7func main() {8 http.HandleFunc("/", oauth.ErrorHandler)9 http.ListenAndServe(":8080", nil)10}11import (12func main() {13 http.HandleFunc("/", oauth.ErrorHandler)14 http.ListenAndServe(":8080", nil)15}16import (17func main() {18 http.HandleFunc("/", oauth.ErrorHandler)19 http.ListenAndServe(":8080", nil)20}21import (22func main() {23 http.HandleFunc("/", oauth.ErrorHandler)24 http.ListenAndServe(":8080", nil)25}26import (27func main() {28 http.HandleFunc("/", oauth.ErrorHandler)29 http.ListenAndServe(":8080", nil)30}31import (32func main() {33 http.HandleFunc("/", oauth.ErrorHandler)34 http.ListenAndServe(":8080", nil)35}36import (37func main() {38 http.HandleFunc("/", oauth.ErrorHandler)39 http.ListenAndServe(":8080", nil)40}41import (42func main() {43 http.HandleFunc("/", oauth.ErrorHandler)44 http.ListenAndServe(":8080", nil)45}

Full Screen

Full Screen

ErrorHandler

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {4 fmt.Fprint(w, "Hello, world!")5 })6 http.ListenAndServe(":8080", nil)7}8import (9func main() {10 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {11 fmt.Fprint(w, "Hello, world!")12 })13 http.ListenAndServe(":8080", nil)14}15import (16func main() {17 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {18 fmt.Fprint(w, "Hello, world!")19 })20 http.ListenAndServe(":8080", nil)21}22import (23func main() {24 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {25 fmt.Fprint(w, "Hello, world!")26 })27 http.ListenAndServe(":8080", nil)28}

Full Screen

Full Screen

ErrorHandler

Using AI Code Generation

copy

Full Screen

1import (2const (3var googleOauthConfig = &oauth2.Config{4}5func main() {6 http.HandleFunc("/", handleMain)7 http.HandleFunc("/login", handleGoogleLogin)8 http.HandleFunc("/oauth2callback", handleGoogleCallback)9 fmt.Println("Listening on localhost:8080")10 http.ListenAndServe(":8080", nil)11}12func handleMain(w http.ResponseWriter, r *http.Request) {13 fmt.Fprint(w, mainPage)14}15func handleGoogleLogin(w http.ResponseWriter, r *http.Request) {16 url := googleOauthConfig.AuthCodeURL("")17 http.Redirect(w, r, url, http.StatusTemporaryRedirect)18}19func handleGoogleCallback(w http.ResponseWriter, r *http.Request) {20 if r.FormValue("state") != googleOauthConfig.RedirectURL {21 fmt.Fprintf(w, "State is not valid")22 }23 tok, err := googleOauthConfig.Exchange(oauth2.NoContext, r.FormValue("code"))24 if err != nil {25 fmt.Fprintf(w, "Error while exchanging code for token: %v26 }27 client := googleOauthConfig.Client(oauth2.NoContext, tok)28 if err != nil {29 fmt.Fprintf(w, "Error while getting user info: %v30 }31 defer resp.Body.Close()32 fmt.Fprintf(w, "Response:33}

Full Screen

Full Screen

ErrorHandler

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := oauth2.NewClient()4 errorHandler := client.NewErrorHandler()5 client.SetErrorHandler(errorHandler)6 client.ErrorHandler()7}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful