How to use hasScope method of plugin Package

Best Gauge code snippet using plugin.hasScope

main.go

Source:main.go Github

copy

Full Screen

1package main2import (3 "bytes"4 "flag"5 "fmt"6 "github.com/golang/glog"7 "github.com/golang/protobuf/proto"8 "github.com/golang/protobuf/protoc-gen-go/descriptor"9 "github.com/golang/protobuf/protoc-gen-go/generator"10 plugin "github.com/golang/protobuf/protoc-gen-go/plugin"11 "github.com/tfeng/postgres-grpc-example/auth"12 "go/format"13 "io/ioutil"14 "os"15 "path/filepath"16 "strings"17 "text/template"18)19var authTemplate = template.Must(template.New("auth").Parse(`20package {{.Pkg}}21import (22 {{if not .IsSamePackage}}23 "github.com/tfeng/postgres-grpc-example/auth"24 {{end}}25 "golang.org/x/net/context"26 "google.golang.org/grpc/codes"27 "google.golang.org/grpc/status"28)29var (30 {{if not .IsSamePackage}}31 _ auth.AuthToken32 {{end}}33 _ context.Context34 _ codes.Code35 _ status.Status36)37{{range $svc := .Services}}38{{range $md := $svc.Methods}}39{{if (or ($md.AuthChecker.GetAuthenticated) ($md.AuthChecker.GetScope))}}40func (r *{{.Request}}) isAuthenticated(ctx context.Context) bool {41 _, ok := auth.GetAuthToken(ctx)42 return ok43}44{{end}}45{{if $md.AuthChecker.GetScope}}46func (r *{{.Request}}) HasScope(ctx context.Context) bool {47 token, _ := auth.GetAuthToken(ctx)48 return {{range $s := $md.AuthChecker.GetScope}}auth.HasScope(auth.Scope_{{$s}}, token) && {{end}}true49}50{{end}}51func (r *{{.Request}}) Authorize(ctx context.Context) error {52 {{if (or ($md.AuthChecker.GetAuthenticated) ($md.AuthChecker.GetScope))}}53 if !r.isAuthenticated(ctx) {54 return status.Error(codes.Unauthenticated, "Not authenticated")55 }56 {{end}}57 {{if $md.AuthChecker.GetScope}}58 if !r.HasScope(ctx) {59 return status.Error(codes.Unauthenticated, "Insufficient scope")60 }61 {{end}}62 return nil63}64{{end}}65{{end}}66`))67type Method struct {68 Method *descriptor.MethodDescriptorProto69 Request string70 AuthChecker *auth.AuthChecker71}72type Service struct {73 Service *descriptor.ServiceDescriptorProto74 Methods []Method75}76type TemplateData struct {77 Pkg string78 Services []Service79 IsSamePackage bool80}81type Params struct {82 IsAuthPackage bool83}84func parseParams(param string) Params {85 var p = Params{}86 parts := strings.Split(param, ",")87 for _, part := range parts {88 switch part {89 case "auth_package":90 p.IsAuthPackage = true91 }92 }93 return p94}95func createTemplateData(params Params, file *descriptor.FileDescriptorProto) TemplateData {96 var svcs []Service97 for _, svc := range file.GetService() {98 var mds []Method99 for _, md := range svc.GetMethod() {100 if ext, err := proto.GetExtension(md.GetOptions(), auth.E_Checker); err == nil {101 ac := ext.(*auth.AuthChecker)102 reqTypeParts := strings.Split(md.GetInputType(), ".")103 mds = append(mds, Method{104 md,105 reqTypeParts[len(reqTypeParts)-1],106 ac,107 })108 }109 }110 svcs = append(svcs, Service{111 svc,112 mds,113 })114 }115 return TemplateData{116 *file.Package,117 svcs,118 params.IsAuthPackage,119 }120}121func main() {122 flag.Parse()123 gen := generator.New()124 data, err := ioutil.ReadAll(os.Stdin)125 if err != nil {126 glog.Fatal("unable to read input", err)127 }128 if err := proto.Unmarshal(data, gen.Request); err != nil {129 glog.Fatal("unable to parse proto", err)130 }131 if len(gen.Request.FileToGenerate) == 0 {132 glog.Fatal("no files to generate")133 }134 var files []*plugin.CodeGeneratorResponse_File135 params := parseParams(gen.Request.GetParameter())136 for _, file := range gen.Request.GetProtoFile() {137 if len(file.GetService()) > 0 {138 code := bytes.NewBuffer(nil)139 data := createTemplateData(params, file)140 if err := authTemplate.Execute(code, data); err != nil {141 glog.Fatal("unable to generate method")142 }143 if formatted, err := format.Source(code.Bytes()); err != nil {144 glog.Fatal(err)145 } else {146 name := file.GetName()147 ext := filepath.Ext(name)148 base := strings.TrimSuffix(name, ext)149 output := fmt.Sprintf("%s.auth.pb.go", base)150 files = append(files, &plugin.CodeGeneratorResponse_File{151 Name: proto.String(output),152 Content: proto.String(string(formatted)),153 })154 }155 }156 }157 // Send back the results.158 data, err = proto.Marshal(&plugin.CodeGeneratorResponse{File: files})159 if err != nil {160 glog.Fatal("failed to marshal output proto", err)161 }162 _, err = os.Stdout.Write(data)163 if err != nil {164 glog.Fatal("failed to write output proto", err)165 }166}...

Full Screen

Full Screen

util_test.go

Source:util_test.go Github

copy

Full Screen

...4 "github.com/SUSE/cf-plugin-backup/util"5)6func TestCheckUserScope_HasScope(t *testing.T) {7 token := "eyJhbGciOiJSUzI1NiIsImtpZCI6ImxlZ2FjeS10b2tlbi1rZXkiLCJ0eXAiOiJKV1QifQ.eyJqdGkiOiI5MWJkZWQ2NTU1ZDI0OTlhYmQwZmFhOWI0ODFlYTA1YiIsInN1YiI6IjFhYWU5NjNhLTFmMTgtNDIwOC04ZDcyLWEzMjI4NjkxYzYzZSIsInNjb3BlIjpbInJvdXRpbmcucm91dGVyX2dyb3Vwcy5yZWFkIiwiY2xvdWRfY29udHJvbGxlci5yZWFkIiwicGFzc3dvcmQud3JpdGUiLCJjbG91ZF9jb250cm9sbGVyLndyaXRlIiwib3BlbmlkIiwiZG9wcGxlci5maXJlaG9zZSIsInNjaW0ud3JpdGUiLCJzY2ltLnJlYWQiLCJjbG91ZF9jb250cm9sbGVyLmFkbWluIiwidWFhLnVzZXIiXSwiY2xpZW50X2lkIjoiY2YiLCJjaWQiOiJjZiIsImF6cCI6ImNmIiwiZ3JhbnRfdHlwZSI6InBhc3N3b3JkIiwidXNlcl9pZCI6IjFhYWU5NjNhLTFmMTgtNDIwOC04ZDcyLWEzMjI4NjkxYzYzZSIsIm9yaWdpbiI6InVhYSIsInVzZXJfbmFtZSI6ImFkbWluIiwiZW1haWwiOiJhZG1pbiIsInJldl9zaWciOiIzODQ1Y2IxNCIsImlhdCI6MTQ4Mzk2NTQ1MSwiZXhwIjoxNDgzOTY2MDUxLCJpc3MiOiJodHRwczovL2hjZi51YWEuZXhhbXBsZS5jb20vb2F1dGgvdG9rZW4iLCJ6aWQiOiJoY2YiLCJhdWQiOlsic2NpbSIsImNsb3VkX2NvbnRyb2xsZXIiLCJwYXNzd29yZCIsImNmIiwidWFhIiwib3BlbmlkIiwiZG9wcGxlciIsInJvdXRpbmcucm91dGVyX2dyb3VwcyJdfQ.ZjX_Wr450SM6jigEBEQDs72_wJDQv2EPRYNG-ucPCFMDjvlwYZrUjaMeJkuVanwXFZhKR2oDflUZQeg78Ue49IPD9G7DiBSUbbgLsQkSRLmy3HJ8vipO8p8uZOmFdDsGbyJ8zFu0wkYTGTwQUfxxYq7j4egn3eZHcXc0rScaKbxlW-X2XLP04uUCc6O9EWxzWOzyE-q27lfGstkosEy1rWMOKs-6xpTimczYT0mnoqr3f6wjUtoYFHrrlPvQ6BPhE5Pm3lItw8BzRO3hUEMxGbgpfhdQ3dy0uBcRwR9Bc6WPpNkGjE8ENORYX82LvVb62IOTyRMphP60MCbvE7TQA98puN6aWmZZfJVmZ7VlBkl_1v8jjrUeWoyCv_0gilbQYsV1dfkll325_Lpp4eXHnsEXZUAgwMgxji4nhvjgk4YR9m9COdPGUzaSRQNm7NS04tHQY65YK8DwEi1SAljHWaghTHYkq5foShRQPLh2TS2QAjJRxH49eRla8DKVh4Cw_1FNy9lH_26xmRbPkf6L6GL_oG5r99emHAihcu8lE7cx7D129Z5JoGJ7RUNB3zA_89YwQPrnUSChoZ2KVU0qioZbH5f5YY4tjwCy-EG8i5DrNK94ti9gf-kVL5qoyMkC02r2EqHxXsQa2xuO_tGobJEqDJ0-3G00DPI2-MFb-_k"8 hasScope, err := util.CheckUserScope(token, "cloud_controller.admin")9 if err != nil {10 t.Fatal(err.Error())11 }12 if !hasScope {13 t.Fatal("scope not present")14 }15}16func TestCheckUserScope_NoScope(t *testing.T) {17 token := "eyJhbGciOiJSUzI1NiIsImtpZCI6ImxlZ2FjeS10b2tlbi1rZXkiLCJ0eXAiOiJKV1QifQ.eyJqdGkiOiIzMWJhMzM4NGQzOGU0NzZiODYyNjZmMmY5N2RmNmI2YyIsInN1YiI6ImQyN2UxZDU0LWQ2YzAtNGRhZi04N2NlLWQ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0S0ckPlUJhjCvZwdlHxgzvEuErrY1PuU63xiqQXEuJsU7etEtoN1uBOQVQ"18 hasScope, err := util.CheckUserScope(token, "inexistent_scope")19 if err != nil {20 t.Fatal(err.Error())21 }22 if hasScope {23 t.Fatal("scope should not be present")24 }25}...

Full Screen

Full Screen

restapi.go

Source:restapi.go Github

copy

Full Screen

1package dashboard2import (3 "errors"4 "net/http"5 "github.com/go-chi/chi"6 "github.com/heedy/heedy/api/golang/plugin"7 "github.com/heedy/heedy/api/golang/rest"8 "github.com/heedy/heedy/backend/database"9)10func validateRequest(w http.ResponseWriter, r *http.Request, scope string) (*plugin.ObjectInfo, bool) {11 oi, err := plugin.GetObjectInfo(r)12 if err != nil {13 rest.WriteJSONError(w, r, http.StatusInternalServerError, err)14 return nil, false15 }16 if !oi.Access.HasScope(scope) {17 rest.WriteJSONError(w, r, http.StatusForbidden, database.ErrAccessDenied("Insufficient permissions"))18 return nil, false19 }20 return oi, true21}22// ReadDashboard reads the entire dashboard23func ReadHandler(w http.ResponseWriter, r *http.Request) {24 oi, ok := validateRequest(w, r, "read")25 if !ok {26 return27 }28 c := rest.CTX(r)29 da, err := ReadDashboard(c.DB.AdminDB(), oi.AsObject(), oi.ID, oi.Access.HasScope("write"))30 rest.WriteGzipJSON(w, r, da, err)31}32func WriteHandler(w http.ResponseWriter, r *http.Request) {33 oi, ok := validateRequest(w, r, "write")34 if !ok {35 return36 }37 c := rest.CTX(r)38 var elements []DashboardElement39 err := rest.UnmarshalRequest(r, &elements)40 if err != nil {41 rest.WriteJSONError(w, r, http.StatusBadRequest, err)42 return43 }44 err = WriteDashboard(c.DB.AdminDB(), oi.AsObject(), oi.ID, elements)45 rest.WriteResult(w, r, err)46}47func ReadElementHandler(w http.ResponseWriter, r *http.Request) {48 oi, ok := validateRequest(w, r, "read")49 if !ok {50 return51 }52 c := rest.CTX(r)53 eid, err := rest.URLParam(r, "element_id", nil)54 if err != nil {55 rest.WriteJSONError(w, r, http.StatusBadRequest, err)56 return57 }58 de, err := ReadDashboardElement(c.DB.AdminDB(), oi.AsObject(), oi.ID, eid, oi.Access.HasScope("write"))59 rest.WriteGzipJSON(w, r, de, err)60}61func DeleteElementHandler(w http.ResponseWriter, r *http.Request) {62 oi, ok := validateRequest(w, r, "write")63 if !ok {64 return65 }66 c := rest.CTX(r)67 eid, err := rest.URLParam(r, "element_id", nil)68 if err != nil {69 rest.WriteJSONError(w, r, http.StatusBadRequest, err)70 return71 }72 err = DeleteDashboardElement(c.DB.AdminDB(), oi.ID, eid)73 rest.WriteResult(w, r, err)74}75func WriteElementHandler(w http.ResponseWriter, r *http.Request) {76 oi, ok := validateRequest(w, r, "write")77 if !ok {78 return79 }80 c := rest.CTX(r)81 eid, err := rest.URLParam(r, "element_id", nil)82 if err != nil {83 rest.WriteJSONError(w, r, http.StatusBadRequest, err)84 return85 }86 var element DashboardElement87 err = rest.UnmarshalRequest(r, &element)88 if err != nil {89 rest.WriteJSONError(w, r, http.StatusBadRequest, err)90 return91 }92 if element.ID != "" && element.ID != eid {93 rest.WriteJSONError(w, r, http.StatusBadRequest, errors.New("bad_request: element ID doesn't match URL"))94 return95 }96 element.ID = eid97 err = WriteDashboard(c.DB.AdminDB(), oi.AsObject(), oi.ID, []DashboardElement{element})98 rest.WriteResult(w, r, err)99}100// Handler is the global router for the timeseries API101var Handler = func() *chi.Mux {102 m := chi.NewMux()103 m.Get("/object/dashboard", ReadHandler)104 m.Post("/object/dashboard", WriteHandler)105 m.Get("/object/dashboard/{element_id}", ReadElementHandler)106 m.Patch("/object/dashboard/{element_id}", WriteElementHandler)107 m.Delete("/object/dashboard/{element_id}", DeleteElementHandler)108 m.NotFound(rest.NotFoundHandler)109 m.MethodNotAllowed(rest.NotFoundHandler)110 return m111}()...

Full Screen

Full Screen

hasScope

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 p, err := plugin.Open("plugin.so")4 if err != nil {5 fmt.Println(err)6 }7 symbol, err := p.Lookup("HasScope")8 if err != nil {9 fmt.Println(err)10 }11 hasScope, ok := symbol.(func(string) bool)12 if !ok {13 fmt.Println("unexpected type from module symbol")14 }15 fmt.Println(hasScope("read"))16 fmt.Println(hasScope("write"))17}18import (19func main() {20 p, err := plugin.Open("plugin.so")21 if err != nil {22 fmt.Println(err)23 }24 symbol, err := p.Lookup("HasScope")25 if err != nil {26 fmt.Println(err)27 }28 hasScope, ok := symbol.(func(string) bool)29 if !ok {30 fmt.Println("unexpected type from module symbol")31 }32 fmt.Println(hasScope("read"))33 fmt.Println(hasScope("write"))34}35import (36func main() {37 p, err := plugin.Open("plugin.so")38 if err != nil {39 fmt.Println(err)40 }41 symbol, err := p.Lookup("HasScope")42 if err != nil {43 fmt.Println(err)44 }45 hasScope, ok := symbol.(func(string) bool)46 if !ok {47 fmt.Println("unexpected type from module symbol")48 }49 fmt.Println(hasScope("read"))50 fmt.Println(hasScope("write"))51}52import (53func main() {54 p, err := plugin.Open("plugin.so")55 if err != nil {56 fmt.Println(err)57 }

Full Screen

Full Screen

hasScope

Using AI Code Generation

copy

Full Screen

1func main() {2 plugin := Plugin{}3 plugin.Init()4 plugin.hasScope("read")5}6func main() {7 plugin := Plugin{}8 plugin.Init()9 plugin.hasScope("read")10}11main.main()

Full Screen

Full Screen

hasScope

Using AI Code Generation

copy

Full Screen

1func main() {2 p := plugin.NewPlugin()3 p.HasScope("scope")4}5func main() {6 p := plugin.NewPlugin()7 p.HasScope("scope")8}9type Plugin struct {10}11func NewPlugin() *Plugin {12}13func (p *Plugin) HasScope(scope string) bool {14}15import "plugin"16func main() {17 p := plugin.NewPlugin()18 p.HasScope("scope")19}20import "plugin"21func main() {22 p := plugin.NewPlugin()23 p.HasScope("scope")24}

Full Screen

Full Screen

hasScope

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 p, err := plugin.Open("plugin.so")4 if err != nil {5 panic(err)6 }7 s, err := p.Lookup("Scopes")8 if err != nil {9 panic(err)10 }11 scopes := s.([]string)12 fmt.Println(scopes)13}14import (15func main() {16 p, err := plugin.Open("plugin.so")17 if err != nil {18 panic(err)19 }20 f, err := p.Lookup("HasScope")21 if err != nil {22 panic(err)23 }24 hasScope := f.(func(string) bool)25 fmt.Println(hasScope("read"))26 fmt.Println(hasScope("write"))27}

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