Best Testkube code snippet using oauth.CallbackHandler
login_test.go
Source:login_test.go
...106 assert.Equal(t, "oauth1: Context missing request token or secret", err.Error())107 }108 fmt.Fprintf(w, "failure handler called")109 }110 // CallbackHandler cannot get the request token from the ctx, assert that:111 // - failure handler is called112 // - error about missing request token is added to the ctx113 authRedirectHandler := AuthRedirectHandler(config, http.HandlerFunc(failure))114 w := httptest.NewRecorder()115 req, _ := http.NewRequest("GET", "/", nil)116 authRedirectHandler.ServeHTTP(w, req)117 assert.Equal(t, "failure handler called", w.Body.String())118}119func TestAuthRedirectHandler_AuthorizationURL(t *testing.T) {120 requestToken := "request_token"121 config := &oauth1.Config{122 Endpoint: oauth1.Endpoint{123 AuthorizeURL: "%gh&%ij", // always causes AuthorizationURL parse error124 },125 }126 failure := func(w http.ResponseWriter, req *http.Request) {127 ctx := req.Context()128 err := gologin.ErrorFromContext(ctx)129 if assert.NotNil(t, err) {130 assert.Contains(t, err.Error(), "invalid URL escape \"%gh\"")131 }132 fmt.Fprintf(w, "failure handler called")133 }134 // AuthRedirectHandler cannot construct the AuthorizationURL, assert that:135 // - failure handler is called136 // - error about authorization URL is added to the ctx137 authRedirectHandler := AuthRedirectHandler(config, http.HandlerFunc(failure))138 w := httptest.NewRecorder()139 req, _ := http.NewRequest("GET", "/", nil)140 ctx := WithRequestToken(context.Background(), requestToken, "")141 authRedirectHandler.ServeHTTP(w, req.WithContext(ctx))142 assert.Equal(t, "failure handler called", w.Body.String())143}144// CallbackHandler145func TestCallbackHandler(t *testing.T) {146 expectedToken := "acces_token"147 expectedSecret := "access_secret"148 requestSecret := "request_secret"149 data := url.Values{}150 data.Add("oauth_token", expectedToken)151 data.Add("oauth_token_secret", expectedSecret)152 server := NewAccessTokenServer(t, data)153 defer server.Close()154 config := &oauth1.Config{155 Endpoint: oauth1.Endpoint{156 AccessTokenURL: server.URL,157 },158 }159 success := func(w http.ResponseWriter, req *http.Request) {160 ctx := req.Context()161 accessToken, accessSecret, err := AccessTokenFromContext(ctx)162 assert.Equal(t, expectedToken, accessToken)163 assert.Equal(t, expectedSecret, accessSecret)164 assert.Nil(t, err)165 fmt.Fprintf(w, "success handler called")166 }167 failure := testutils.AssertFailureNotCalled(t)168 // CallbackHandler gets OAuth1 access token, assert that:169 // - success handler is called170 // - access token and secret added to the ctx of the success handler171 // - failure handler is not called172 callbackHandler := CallbackHandler(config, http.HandlerFunc(success), failure)173 w := httptest.NewRecorder()174 req, _ := http.NewRequest("GET", "/?oauth_token=any_token&oauth_verifier=any_verifier", nil)175 ctx := WithRequestToken(context.Background(), "", requestSecret)176 callbackHandler.ServeHTTP(w, req.WithContext(ctx))177 assert.Equal(t, "success handler called", w.Body.String())178}179func TestCallbackHandler_ParseAuthorizationCallbackError(t *testing.T) {180 config := &oauth1.Config{}181 success := testutils.AssertSuccessNotCalled(t)182 failure := func(w http.ResponseWriter, req *http.Request) {183 ctx := req.Context()184 err := gologin.ErrorFromContext(ctx)185 if assert.NotNil(t, err) {186 assert.Equal(t, "oauth1: Request missing oauth_token or oauth_verifier", err.Error())187 }188 fmt.Fprintf(w, "failure handler called")189 }190 // CallbackHandler called without oauth_token or oauth_verifier, assert that:191 // - failure handler is called192 // - error about missing oauth_token or oauth_verifier is added to the ctx193 callbackHandler := CallbackHandler(config, success, http.HandlerFunc(failure))194 w := httptest.NewRecorder()195 req, _ := http.NewRequest("GET", "/?oauth_verifier=", nil)196 callbackHandler.ServeHTTP(w, req)197 assert.Equal(t, "failure handler called", w.Body.String())198}199func TestCallbackHandler_MissingCtxRequestSecret(t *testing.T) {200 config := &oauth1.Config{}201 success := testutils.AssertSuccessNotCalled(t)202 failure := func(w http.ResponseWriter, req *http.Request) {203 ctx := req.Context()204 err := gologin.ErrorFromContext(ctx)205 if assert.NotNil(t, err) {206 assert.Equal(t, "oauth1: Context missing request token or secret", err.Error())207 }208 fmt.Fprintf(w, "failure handler called")209 }210 // CallbackHandler cannot get the request secret from the ctx, assert that:211 // - failure handler is called212 // - error about missing request secret is added to the ctx213 callbackHandler := CallbackHandler(config, success, http.HandlerFunc(failure))214 w := httptest.NewRecorder()215 req, _ := http.NewRequest("GET", "/?oauth_token=any_token&oauth_verifier=any_verifier", nil)216 callbackHandler.ServeHTTP(w, req)217 assert.Equal(t, "failure handler called", w.Body.String())218}219func TestCallbackHandler_AccessTokenError(t *testing.T) {220 requestSecret := "request_secret"221 _, server := testutils.NewErrorServer("OAuth1 Server Error", http.StatusInternalServerError)222 defer server.Close()223 config := &oauth1.Config{224 Endpoint: oauth1.Endpoint{225 AccessTokenURL: server.URL,226 },227 }228 success := testutils.AssertSuccessNotCalled(t)229 failure := func(w http.ResponseWriter, req *http.Request) {230 ctx := req.Context()231 err := gologin.ErrorFromContext(ctx)232 if assert.NotNil(t, err) {233 // first validation in OAuth1 impl failed234 assert.Equal(t, expectedOAuth1Error, err.Error())235 }236 fmt.Fprintf(w, "failure handler called")237 }238 // CallbackHandler cannot get the OAuth1 access token, assert that:239 // - failure handler is called240 // - error about StatusInternalServerError is added to the ctx241 callbackHandler := CallbackHandler(config, success, http.HandlerFunc(failure))242 w := httptest.NewRecorder()243 req, _ := http.NewRequest("GET", "/?oauth_token=any_token&oauth_verifier=any_verifier", nil)244 ctx := WithRequestToken(context.Background(), "", requestSecret)245 callbackHandler.ServeHTTP(w, req.WithContext(ctx))246 assert.Equal(t, "failure handler called", w.Body.String())247}...
oauth_test.go
Source:oauth_test.go
1package oauth2import (3 "github.com/serdmanczyk/freyr/fake"4 "github.com/serdmanczyk/freyr/models"5 "github.com/serdmanczyk/freyr/token"6 "net/http"7 "net/http/httptest"8 "net/url"9 "strings"10 "testing"11 "time"12)13const (14 testKey = "tokenkeytokenkeytokenkey"15 testEmail = "Ardvark@comeatme.bro"16)17func TestHandleThreeLegged(t *testing.T) {18 oauth := &fake.Oauth{Email: testEmail}19 tokensource := token.JWTTokenGen(testKey)20 authorizeRequest, err := http.NewRequest("GET", "/authorize", nil)21 if err != nil {22 t.Fatal(err)23 }24 authorizeResponse := httptest.NewRecorder()25 authorizeHandler := HandleAuthorize(oauth, tokensource)26 authorizeHandler.ServeHTTP(authorizeResponse, authorizeRequest)27 if authorizeResponse.Code != 302 {28 t.Fatalf("Response should be 302, got: %d", authorizeResponse.Code)29 }30 authorizeLocation, ok := authorizeResponse.HeaderMap["Location"]31 if !ok || len(authorizeLocation) != 1 {32 t.Fatalf("Location header not set and/or incorrect number of values")33 }34 u, err := url.Parse(authorizeLocation[0])35 if err != nil {36 t.Fatalf("Redirect header invalid: %s", err.Error())37 }38 state, ok := u.Query()["state"]39 if !ok || len(state) != 1 {40 t.Fatalf("State parameter not set in redirect url or set incorrect number of times")41 }42 claims, err := tokensource.ValidateToken(state[0])43 if err != nil {44 t.Fatalf("State header set in redirect url invalid: %s", err.Error())45 }46 if !checkOauthClaim(claims) {47 t.Fatalf("Passed claim in csrf token invalid: %v", claims)48 }49 callbackURL := "/oauth2callback?state=" + state[0] + "&code=jibbajabba"50 callbackRequest, err := http.NewRequest("GET", callbackURL, nil)51 if err != nil {52 t.Fatal(err)53 }54 callbackResponse := httptest.NewRecorder()55 userStore := fake.UserStore{testEmail: models.User{Email: testEmail}}56 callbackHandler := HandleOAuth2Callback(oauth, tokensource, userStore)57 callbackHandler.ServeHTTP(callbackResponse, callbackRequest)58 if callbackResponse.Code != 302 {59 t.Fatalf("Response should be 302, got: %d:%s", callbackResponse.Code, callbackResponse.Body.String())60 }61 callbackLocation, ok := callbackResponse.HeaderMap["Location"]62 if !ok || len(callbackLocation) != 1 {63 t.Fatalf("Location header not set and/or incorrect number of values")64 }65 if callbackLocation[0] != "/" {66 t.Fatalf("Callback should redirect to '/', got: %s", callbackLocation[0])67 }68 cookie, ok := callbackResponse.Header()["Set-Cookie"]69 if !ok || len(cookie) != 1 {70 t.Fatalf("Cookie not set in response, or set improper amount of times")71 }72 header := http.Header{}73 header.Add("Cookie", cookie[0])74 request := http.Request{Header: header}75 parsedCookie, err := request.Cookie(CookieName)76 if err != nil {77 t.Fatalf("Cookie not properly set in response: %s", parsedCookie)78 }79 claims, err = tokensource.ValidateToken(parsedCookie.Value)80 if err != nil {81 t.Fatalf("Cookie not properly set in response: %s", err.Error())82 }83 email, ok := claims["email"]84 if !ok {85 t.Fatalf("email not set in claim")86 }87 if email != testEmail {88 t.Fatalf("incorrect email in claim")89 }90}91// TODO: refactor following into table test??92func TestRejectToken(t *testing.T) {93 oauth := &fake.Oauth{Email: testEmail}94 tokensource := token.JWTTokenGen(testKey)95 callbackURL := "/oauth2callback?state=shutyomouth&code=jibbajabba"96 callbackRequest, err := http.NewRequest("GET", callbackURL, nil)97 if err != nil {98 t.Fatal(err)99 }100 callbackResponse := httptest.NewRecorder()101 userStore := fake.UserStore{testEmail: models.User{Email: testEmail}}102 callbackHandler := HandleOAuth2Callback(oauth, tokensource, userStore)103 callbackHandler.ServeHTTP(callbackResponse, callbackRequest)104 if callbackResponse.Code != http.StatusForbidden {105 t.Fatalf("Response should be %d, got: %d", http.StatusForbidden, callbackResponse.Code)106 }107}108func TestExpiredToken(t *testing.T) {109 oauth := &fake.Oauth{Email: testEmail}110 tokensource := token.JWTTokenGen(testKey)111 claims := map[string]interface{}{}112 expiredToken, err := tokensource.GenerateToken(time.Now().Add(time.Second*-1), claims)113 if err != nil {114 t.Fatal(err)115 }116 callbackURL := "/oauth2callback?state=" + expiredToken + "&code=jibbajabba"117 callbackRequest, err := http.NewRequest("GET", callbackURL, nil)118 if err != nil {119 t.Fatal(err)120 }121 callbackResponse := httptest.NewRecorder()122 userStore := fake.UserStore{testEmail: models.User{Email: testEmail}}123 callbackHandler := HandleOAuth2Callback(oauth, tokensource, userStore)124 callbackHandler.ServeHTTP(callbackResponse, callbackRequest)125 if callbackResponse.Code != http.StatusForbidden {126 t.Fatalf("Response should be %d, got: %d", http.StatusForbidden, callbackResponse.Code)127 }128 if !strings.Contains(callbackResponse.Body.String(), token.ErrorTokenExpired.Error()) {129 t.Fatalf("Error response incorrect, expected %s, got: %s", token.ErrorTokenExpired.Error(), callbackResponse.Body.String())130 }131}132func TestInvalidClaims(t *testing.T) {133 oauth := &fake.Oauth{Email: testEmail}134 tokensource := token.JWTTokenGen(testKey)135 claims := map[string]interface{}{136 "wacko": "blammo",137 }138 expiredToken, err := tokensource.GenerateToken(time.Now().Add(time.Second*5), claims)139 if err != nil {140 t.Fatal(err)141 }142 callbackURL := "/oauth2callback?state=" + expiredToken + "&code=jibbajabba"143 callbackRequest, err := http.NewRequest("GET", callbackURL, nil)144 if err != nil {145 t.Fatal(err)146 }147 callbackResponse := httptest.NewRecorder()148 userStore := fake.UserStore{testEmail: models.User{Email: testEmail}}149 callbackHandler := HandleOAuth2Callback(oauth, tokensource, userStore)150 callbackHandler.ServeHTTP(callbackResponse, callbackRequest)151 if callbackResponse.Code != http.StatusForbidden {152 t.Fatalf("Response should be %d, got: %d", http.StatusForbidden, callbackResponse.Code)153 }154 if !strings.Contains(callbackResponse.Body.String(), ErrorInvalidClaims.Error()) {155 t.Fatalf("Error response incorrect, expected %s, got: %s", ErrorInvalidClaims.Error(), callbackResponse.Body.String())156 }157}...
apiserver.go
Source:apiserver.go
...15)16// ApiServer éç¨äº http.ServeMux 模åè½½å
¥çæ¹æ¡17type ApiServer struct {18 *http.ServeMux19 callbacks map[string][]CallbackHandler20}21type CallbackHandler func(*ApiServer)22// NewApiServer å建 ApiServer å®ä½ï¼ç¨åç¨ http.ListenAndServe å¯å¨23func NewApiServer() *ApiServer {24 server := &ApiServer{25 ServeMux: http.NewServeMux(),26 }27 server.init()28 return server29}30type routeHandler func(*ApiServer) error31var db *models.Database32func (svr *ApiServer) init() {33 svr.callbacks = make(map[string][]CallbackHandler)34 svr.staticHandler()35 svr.Handle("/signout", sessions.MiddlewareFunc(func(w http.ResponseWriter, r *http.Request) {36 session := sessions.GetSession(r)37 logout(session)38 session.Save(r, w)39 http.Redirect(w, r, "/", http.StatusFound)40 }))41 tmpl.LoadTemplates()42 tmpl.AddBuiltinTemplate(buildNavTemplate())43 // db, _ = database.Open("sqlite3", "db/minibox.db")44 // db.LogMode(true)45 err := models.LoadConfig()46 if err != nil {47 log.Fatalf("load database config error: %s", err)48 }49 models.LogMode(true)50 db = models.GetDB()51 Registry(svr)52 EachInitializer(svr)53 models.AutoMigrations(db)54 storage = oauth_storage.NewStorage(db)55}56func (svr *ApiServer) staticHandler() {57 fs := http.FileServer(http.Dir("./static"))58 svr.Handle("/static/", http.StripPrefix("/static/", fs))59 svr.Handle("/website/", http.StripPrefix("/website/", http.FileServer(http.Dir("../website/build/minibox"))))60}61func (svr *ApiServer) beforeRouter(handle CallbackHandler) {62 var (63 callbacks []CallbackHandler64 ok bool65 )66 if callbacks, ok = svr.callbacks["beforeRouter"]; !ok {67 callbacks = make([]CallbackHandler, 0)68 }69 svr.callbacks["beforeRouter"] = append(callbacks, handle)70}71func (svr *ApiServer) afterRouter(handle CallbackHandler) {72 var (73 callbacks []CallbackHandler74 ok bool75 )76 if callbacks, ok = svr.callbacks["afterRouter"]; !ok {77 callbacks = make([]CallbackHandler, 0)78 }79 svr.callbacks["afterRouter"] = append(callbacks, handle)80}81func (svr *ApiServer) runCallback(name string) {82 var (83 callbacks []CallbackHandler84 ok bool85 )86 if callbacks, ok = svr.callbacks[name]; ok {87 for _, callback := range callbacks {88 callback(svr)89 }90 }91}92var storage osin.Storage93// Listen å¯å¨ ApiServer94func Listen(server *ApiServer) error {95 // server.init()96 ns := NewNamespace()97 ds := NewDatasets()...
CallbackHandler
Using AI Code Generation
1import (2func main() {3 r := mux.NewRouter()4 r.HandleFunc("/callback", CallbackHandler)5 http.Handle("/", r)6 http.ListenAndServe(":8080", nil)7}8func CallbackHandler(w http.ResponseWriter, r *http.Request) {9 code := r.URL.Query().Get("code")10 fmt.Printf("code: %s11}12import (13func main() {14 r := mux.NewRouter()15 r.HandleFunc("/callback", CallbackHandler)16 http.Handle("/", r)17 http.ListenAndServe(":8080", nil)18}19func CallbackHandler(w http.ResponseWriter, r *http.Request) {20 code := r.URL.Query().Get("code")21 fmt.Printf("code: %s22}23import (24func main() {25 r := mux.NewRouter()26 r.HandleFunc("/callback", CallbackHandler)27 http.Handle("/", r)28 http.ListenAndServe(":8080", nil)29}30func CallbackHandler(w http.ResponseWriter, r *http.Request) {31 code := r.URL.Query().Get("code")32 fmt.Printf("code: %s33}34import (35func main() {36 r := mux.NewRouter()37 r.HandleFunc("/callback", CallbackHandler)38 http.Handle("/", r)39 http.ListenAndServe(":8080", nil)40}41func CallbackHandler(w http.ResponseWriter, r *http.Request) {42 code := r.URL.Query().Get("code")43 fmt.Printf("code: %s44}45import (
CallbackHandler
Using AI Code Generation
1import (2func main() {3 var (4 flag.StringVar(&clientId, "client_id", "", "Client ID")5 flag.StringVar(&clientSecret, "client_secret", "", "Client Secret")6 flag.StringVar(&redirectUri, "redirect_uri", "", "Redirect URI")7 flag.StringVar(&scope, "scope", "", "Scope")8 flag.Parse()9 if clientId == "" || clientSecret == "" || redirectUri == "" || scope == "" {10 fmt.Println("Please provide all the required information")11 flag.PrintDefaults()12 os.Exit(1)13 }14 uuid, err := uuid.NewV4()15 if err != nil {16 fmt.Println("Error in creating uuid")17 os.Exit(1)18 }19 state = uuid.String()20 oauth := oauth.New(clientId, clientSecret, redirectUri, scope)21 authUrl = oauth.GetAuthorizationURL(state)22 fmt.Println("Authorization URL: ", authUrl)23 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {24 if r.Method == "GET" {25 if strings.Contains(r.URL.String(), "code") && strings.Contains(r.URL.String(), "state") {26 code, state := oauth.CallbackHandler(r.URL.String())27 client := &http.Client{}28 req, err := http.NewRequest("POST", oauth.GetAccessTokenURL(), nil)29 if err != nil {30 fmt.Println("Error in creating request object")31 os.Exit(
CallbackHandler
Using AI Code Generation
1import (2func main() {3 client := &http.Client{}4 req, err := http.NewRequest("GET", url, nil)5 if err != nil {6 fmt.Println("Error creating request:", err)7 }8 req.Header.Set("User-Agent", "Gopher")9 resp, err := client.Do(req)10 if err != nil {11 fmt.Println("Error making request:", err)12 }13 defer resp.Body.Close()14 for _, link := range linkheader.Parse(resp.Header.Get("Link")) {15 fmt.Println(link.URL, link.Rel)16 }17}18import (19func main() {20 client := &http.Client{}21 req, err := http.NewRequest("GET", url, nil)22 if err != nil {23 fmt.Println("Error creating request:", err)24 }25 req.Header.Set("User-Agent", "Gopher")26 resp, err := client.Do(req)27 if err != nil {28 fmt.Println("Error making request:", err)29 }30 defer resp.Body.Close()31 for _, link := range linkheader.Parse(resp.Header.Get("Link")) {32 fmt.Println(link.URL, link.Rel)33 }34}35import (
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!