Best Testkube code snippet using oauth.GetValidator
oauth.go
Source:oauth.go
...73 Client *http.Client74 Token *oauth2.Token75}76func (p Provider) getOAuthConfig(providerType ProviderType) (*oauth2.Config, error) {77 validator, err := p.GetValidator(providerType)78 if err != nil {79 return nil, err80 }81 redirectURL := fmt.Sprintf("http://%s:%d%s", localIP, localPort, callbackPath)82 return &oauth2.Config{83 ClientID: p.clientID,84 ClientSecret: p.clientSecret,85 Endpoint: validator.GetEndpoint(),86 RedirectURL: redirectURL,87 Scopes: p.scopes,88 }, nil89}90// AddValidator adds validator91func (p Provider) AddValidator(providerType ProviderType, validator Validator) {92 p.validators[providerType] = validator93}94// GetValidator returns validator95func (p Provider) GetValidator(providerType ProviderType) (Validator, error) {96 validator, ok := p.validators[providerType]97 if !ok {98 return nil, fmt.Errorf("unknown oauth provider %s", providerType)99 }100 return validator, nil101}102// ValidateToken validates token103func (p Provider) ValidateToken(providerType ProviderType, token *oauth2.Token) (*oauth2.Token, error) {104 config, err := p.getOAuthConfig(providerType)105 if err != nil {106 return nil, err107 }108 tokenSource := config.TokenSource(context.Background(), token)109 return tokenSource.Token()110}111// ValidateAccessToken validates access token112func (p Provider) ValidateAccessToken(providerType ProviderType, accessToken string) error {113 validator, err := p.GetValidator(providerType)114 if err != nil {115 return err116 }117 return validator.Validate(accessToken)118}119// AuthenticateUser starts the login process120func (p Provider) AuthenticateUser(providerType ProviderType) (client *AuthorizedClient, err error) {121 oauthStateString := rand.String(randomLength)122 ctx := context.WithValue(context.WithValue(context.Background(), oauth2.HTTPClient, p.client),123 oauthStateStringContextKey, oauthStateString)124 config, err := p.getOAuthConfig(providerType)125 if err != nil {126 return nil, err127 }...
handlers.go
Source:handlers.go
1package handlers2import (3 "context"4 "crypto/rand"5 "encoding/base64"6 "encoding/json"7 "io/ioutil"8 "log"9 "net/http"10 "os"11 "time"12 "github.com/gin-gonic/contrib/sessions"13 "github.com/gin-gonic/gin"14 pb "github.com/nodebreaker0-0/gin-oauth-test/config"15 "github.com/nodebreaker0-0/gin-oauth-test/structs"16 "golang.org/x/oauth2"17 "golang.org/x/oauth2/google"18 "google.golang.org/grpc"19)20var cred Credentials21var conf *oauth2.Config22// Credentials which stores google ids.23type Credentials struct {24 Cid string `json:"cid"`25 Csecret string `json:"csecret"`26 RedirectURL string `json:"url"`27}28// RandToken generates a random @l length token.29func RandToken(l int) (string, error) {30 b := make([]byte, l)31 if _, err := rand.Read(b); err != nil {32 return "", err33 }34 return base64.StdEncoding.EncodeToString(b), nil35}36func getLoginURL(state string) string {37 return conf.AuthCodeURL(state)38}39func init() {40 file, err := ioutil.ReadFile("./creds.json")41 if err != nil {42 log.Printf("File error: %v\n", err)43 os.Exit(1)44 }45 if err := json.Unmarshal(file, &cred); err != nil {46 log.Println("unable to marshal data")47 return48 }49 conf = &oauth2.Config{50 ClientID: cred.Cid,51 ClientSecret: cred.Csecret,52 RedirectURL: cred.RedirectURL,53 Scopes: []string{54 "https://www.googleapis.com/auth/userinfo.email", // You have to select your own scope from here -> https://developers.google.com/identity/protocols/googlescopes#google_sign-in55 },56 Endpoint: google.Endpoint,57 }58}59// AuthHandler handles authentication of a user and initiates a session.60func AuthHandler(c *gin.Context) {61 // Handle the exchange code to initiate a transport.62 session := sessions.Default(c)63 retrievedState := session.Get("state")64 queryState := c.Request.URL.Query().Get("state")65 if retrievedState != queryState {66 log.Printf("Invalid session state: retrieved: %s; Param: %s", retrievedState, queryState)67 c.HTML(http.StatusUnauthorized, "error.tmpl", gin.H{"message": "Invalid session state."})68 return69 }70 code := c.Request.URL.Query().Get("code")71 tok, err := conf.Exchange(oauth2.NoContext, code)72 if err != nil {73 log.Println(err)74 c.HTML(http.StatusBadRequest, "error.tmpl", gin.H{"message": "Login failed. Please try again."})75 return76 }77 client := conf.Client(oauth2.NoContext, tok)78 userinfo, err := client.Get("https://www.googleapis.com/oauth2/v3/userinfo")79 if err != nil {80 log.Println(err)81 c.AbortWithStatus(http.StatusBadRequest)82 return83 }84 defer userinfo.Body.Close()85 data, _ := ioutil.ReadAll(userinfo.Body)86 u := structs.User{}87 if err = json.Unmarshal(data, &u); err != nil {88 log.Println(err)89 c.HTML(http.StatusBadRequest, "error.tmpl", gin.H{"message": "Error marshalling response. Please try agian."})90 return91 }92 session.Set("user-id", u.Email)93 err = session.Save()94 if err != nil {95 log.Println(err)96 c.HTML(http.StatusBadRequest, "error.tmpl", gin.H{"message": "Error while saving session. Please try again."})97 return98 }99 c.HTML(http.StatusOK, "validator.tmpl", gin.H{"link": "/"})100}101// LoginHandler handles the login procedure.102func LoginHandler(c *gin.Context) {103 state, err := RandToken(32)104 if err != nil {105 c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"message": "Error while generating random data."})106 return107 }108 session := sessions.Default(c)109 session.Set("state", state)110 err = session.Save()111 if err != nil {112 c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"message": "Error while saving session."})113 return114 }115 link := getLoginURL(state)116 c.HTML(http.StatusOK, "auth.tmpl", gin.H{"link": link})117}118//You need to change it to be a little more communication efficient.119func GetnodeStatusHandler(c *gin.Context) {120 conn, err := grpc.Dial("localhost:8088", grpc.WithInsecure(), grpc.WithBlock())121 if err != nil {122 log.Fatalf("did not connect: %v", err)123 }124 defer conn.Close()125 connect := pb.NewMonitoringClient(conn)126 nodeuri := c.Query("nodeuri")127 ctx, cancel := context.WithTimeout(context.Background(), time.Second)128 defer cancel()129 r, err := connect.GetnodeStatus(ctx, &pb.StatusRequest{NodeURI: nodeuri})130 if err != nil {131 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})132 } else {133 c.JSON(http.StatusOK, gin.H{"status": r.Status})134 }135 log.Printf("Config: %v", r)136}137func GetvalidatorSignInfo(c *gin.Context) {138 conn, err := grpc.Dial("localhost:8088", grpc.WithInsecure(), grpc.WithBlock())139 if err != nil {140 log.Fatalf("did not connect: %v", err)141 }142 defer conn.Close()143 connect := pb.NewMonitoringClient(conn)144 nodeuri := c.Query("nodeuri")145 validator := c.Query("validatoraddress")146 ctx, cancel := context.WithTimeout(context.Background(), time.Second)147 defer cancel()148 q, err := connect.GetvalidatorSignInfo(ctx, &pb.SignInfoRequest{NodeURI: nodeuri, ValidatorAddress: validator}) //CADDDE4BF216A677736DF9487C3C0D0228CE3256149 if err != nil {150 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})151 } else {152 c.JSON(http.StatusOK, gin.H{"status": q.Status})153 }154 log.Printf("Config: %v", q)155}...
main.go
Source:main.go
1package main2import (3 "log"4 "github.com/gin-gonic/contrib/sessions"5 "github.com/gin-gonic/contrib/static"6 "github.com/gin-gonic/gin"7 "github.com/nodebreaker0-0/gin-oauth-test/handlers"8 "github.com/nodebreaker0-0/gin-oauth-test/middleware"9)10func main() {11 router := gin.Default()12 token, err := handlers.RandToken(64)13 if err != nil {14 log.Fatal("unable to generate random token: ", err)15 }16 store := sessions.NewCookieStore([]byte(token))17 store.Options(sessions.Options{18 Path: "/",19 MaxAge: 600,20 HttpOnly: true,21 Secure: true,22 })23 router.Use(gin.Logger())24 router.Use(gin.Recovery())25 router.Use(sessions.Sessions("adminsession", store))26 router.Static("/css", "./static/css")27 router.Static("/img", "./static/img")28 router.LoadHTMLGlob("templates/*")29 //router.GET("/", handlers.IndexHandler)30 router.GET("/login", handlers.LoginHandler)31 router.GET("/auth", handlers.AuthHandler)32 router.Use(middleware.AuthorizeRequest())33 {34 router.Use(static.Serve("/", static.LocalFile("./all-in-one-admin/build", true)))35 router.GET("/GetnodeStatus", handlers.GetnodeStatusHandler)36 router.GET("/GetvalidatorSignInfo", handlers.GetvalidatorSignInfo)37 }38 if err := router.RunTLS(":443", "./server.crt", "./server.key"); err != nil {39 log.Fatal(err)40 }41}...
GetValidator
Using AI Code Generation
1import (2func main() {3 beego.Info("Starting server...")4 beego.AddFuncMap("i18n", i18n.Tr)5 beego.LoadAppConfig("ini", "conf/app.conf")6 orm.RegisterDataBase("default", "mysql", beego.AppConfig.String("mysqluser")+":"+beego.AppConfig.String("mysqlpass")+"@/"+beego.AppConfig.String("mysqldb")+"?charset=utf8", 30)7 orm.RegisterModel(new(models.User))8 validation.SetDefaultMessage(map[string]string{
GetValidator
Using AI Code Generation
1import (2func main() {3 router := mux.NewRouter()4 router.HandleFunc("/oauth2/authorize", GetValidator)5 http.ListenAndServe(":8000", router)6}7func GetValidator(w http.ResponseWriter, r *http.Request) {8 fmt.Fprintf(w, "Hello")9}10import (11func main() {12 router := mux.NewRouter()13 router.HandleFunc("/oauth2/authorize", GetValidator)14 http.ListenAndServe(":8000", router)15}16func GetValidator(w http.ResponseWriter, r *http.Request) {17 fmt.Fprintf(w, "Hello")18}19import (20func main() {21 router := mux.NewRouter()22 router.HandleFunc("/oauth2/authorize", GetValidator)23 http.ListenAndServe(":8000", router)24}25func GetValidator(w http.ResponseWriter, r *http.Request) {26 fmt.Fprintf(w, "Hello")27}28import (29func main() {30 router := mux.NewRouter()31 router.HandleFunc("/oauth2/authorize", GetValidator)32 http.ListenAndServe(":8000", router)33}34func GetValidator(w http.ResponseWriter, r *http.Request) {35 fmt.Fprintf(w, "Hello")36}37import (38func main() {39 router := mux.NewRouter()40 router.HandleFunc("/oauth2/authorize", GetValidator)41 http.ListenAndServe(":8000", router)42}43func GetValidator(w http.ResponseWriter, r *http.Request) {44 fmt.Fprintf(w, "Hello")45}46import (47func main() {
GetValidator
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World!")4 oauth.GetValidator()5}6import (7func GetValidator() {8 fmt.Println("GetValidator")9}10Your name to display (optional):11Your name to display (optional):12Your name to display (optional):
GetValidator
Using AI Code Generation
1import (2func main() {3 oauth := oauth.OAuth{}4 oauth.GetValidator()5 fmt.Println(oauth)6}7import (8func main() {9 oauth := oauth.OAuth{}10 oauth.GetValidator()11 fmt.Println(oauth)12}13type OAuth struct {14}15func (oauth OAuth) GetValidator() {16}
GetValidator
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 oauthObj.GetValidator()5}6import (7func main() {8 fmt.Println("Hello, playground")9 oauthObj := oauth.OAuth{}10 oauthObj.GetValidator()11}12import (13func main() {14 fmt.Println("Hello, playground")15 oauthObj := oauth.OAuth{}16 oauthObj.GetValidator()17}18import (19func main() {20 fmt.Println("Hello, playground")21 oauthObj := oauth.OAuth{}22 oauthObj.GetValidator()23}24import (25func main() {26 fmt.Println("Hello, playground")27 oauthObj := oauth.OAuth{}28 oauthObj.GetValidator()29}30import (31func main() {32 fmt.Println("Hello, playground")33 oauthObj := oauth.OAuth{}34 oauthObj.GetValidator()35}36import (37func main() {38 fmt.Println("Hello, playground")39 oauthObj := oauth.OAuth{}40 oauthObj.GetValidator()41}42import (43func main() {44 fmt.Println("Hello, playground")45 oauthObj := oauth.OAuth{}46 oauthObj.GetValidator()47}48import (49func main() {50 fmt.Println("Hello, playground")51 oauthObj := oauth.OAuth{}52 oauthObj.GetValidator()53}
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!!