当前位置: 首页>>代码示例>>Golang>>正文


Golang nosurf.New函数代码示例

本文整理汇总了Golang中github.com/justinas/nosurf.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: main

func main() {
	server := web.NewServer()
	server.Get("/", myHandler)
	server.Post("/", myHandler)

	http.ListenAndServe(":8000", nosurf.New(server))
}
开发者ID:marswang,项目名称:nosurf,代码行数:7,代码来源:web.go

示例2: main

func main() {
	goji.Get("/", IndexHandler) // Doesn't need CSRF protection (no POST/PUT/DELETE actions).

	signup := web.New()
	goji.Handle("/signup/*", signup)
	// But our signup forms do, so we add nosurf to their middleware stack (only).
	signup.Use(nosurf.NewPure)
	signup.Get("/signup/new", ShowSignupForm)
	signup.Post("/signup/submit", SubmitSignupForm)

	admin := web.New()
	// A more advanced example: we enforce secure cookies (HTTPS only),
	// set a domain and keep the expiry time low.
	a := nosurf.New(admin)
	a.SetBaseCookie(http.Cookie{
		Name:     "csrf_token",
		Domain:   "localhost",
		Path:     "/admin",
		MaxAge:   3600 * 4,
		HttpOnly: true,
		Secure:   true,
	})

	// Our /admin/* routes now have CSRF protection.
	goji.Handle("/admin/*", a)

	goji.Serve()
}
开发者ID:marswang,项目名称:nosurf,代码行数:28,代码来源:goji.go

示例3: nosurfing

func nosurfing(h http.Handler) http.Handler {
	surfing := nosurf.New(h)
	surfing.SetFailureHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Println("Failed to validate XSRF Token:", nosurf.Reason(r))
		w.WriteHeader(http.StatusBadRequest)
	}))
	return surfing
}
开发者ID:josephmisiti,项目名称:authboss-sample,代码行数:8,代码来源:middleware.go

示例4: WithCsrfHandler

// WithCsrfHandler is a middleware wrapper providing CSRF validation
func WithCsrfHandler(h http.Handler) http.Handler {
	csrfHandler := nosurf.New(h)
	csrfHandler.SetFailureHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		rsn := nosurf.Reason(req).Error()
		log.DebugR(req, "failed csrf validation", log.Data{"reason": rsn})
		HTML(w, http.StatusBadRequest, "error", map[string]interface{}{"error": rsn})
	}))
	return csrfHandler
}
开发者ID:ian-kent,项目名称:service.go,代码行数:10,代码来源:render.go

示例5: CreateAdminRouter

// CreateAdminRouter creates the routes for handling requests to the web interface.
// This function returns an http.Handler to be used in http.ListenAndServe().
func CreateAdminRouter() http.Handler {
	router := mux.NewRouter()
	// Base Front-end routes
	router.HandleFunc("/", Use(Base, mid.RequireLogin))
	router.HandleFunc("/login", Login)
	router.HandleFunc("/logout", Use(Logout, mid.RequireLogin))
	router.HandleFunc("/campaigns", Use(Campaigns, mid.RequireLogin))
	router.HandleFunc("/campaigns/{id:[0-9]+}", Use(CampaignID, mid.RequireLogin))
	router.HandleFunc("/templates", Use(Templates, mid.RequireLogin))
	router.HandleFunc("/users", Use(Users, mid.RequireLogin))
	router.HandleFunc("/landing_pages", Use(LandingPages, mid.RequireLogin))
	router.HandleFunc("/sending_profiles", Use(SendingProfiles, mid.RequireLogin))
	router.HandleFunc("/register", Use(Register, mid.RequireLogin))
	router.HandleFunc("/settings", Use(Settings, mid.RequireLogin))
	// Create the API routes
	api := router.PathPrefix("/api").Subrouter()
	api = api.StrictSlash(true)
	api.HandleFunc("/", Use(API, mid.RequireLogin))
	api.HandleFunc("/reset", Use(API_Reset, mid.RequireLogin))
	api.HandleFunc("/campaigns/", Use(API_Campaigns, mid.RequireAPIKey))
	api.HandleFunc("/campaigns/{id:[0-9]+}", Use(API_Campaigns_Id, mid.RequireAPIKey))
	api.HandleFunc("/campaigns/{id:[0-9]+}/results", Use(API_Campaigns_Id_Results, mid.RequireAPIKey))
	api.HandleFunc("/campaigns/{id:[0-9]+}/complete", Use(API_Campaigns_Id_Complete, mid.RequireAPIKey))
	api.HandleFunc("/groups/", Use(API_Groups, mid.RequireAPIKey))
	api.HandleFunc("/groups/{id:[0-9]+}", Use(API_Groups_Id, mid.RequireAPIKey))
	api.HandleFunc("/templates/", Use(API_Templates, mid.RequireAPIKey))
	api.HandleFunc("/templates/{id:[0-9]+}", Use(API_Templates_Id, mid.RequireAPIKey))
	api.HandleFunc("/pages/", Use(API_Pages, mid.RequireAPIKey))
	api.HandleFunc("/pages/{id:[0-9]+}", Use(API_Pages_Id, mid.RequireAPIKey))
	api.HandleFunc("/smtp/", Use(API_SMTP, mid.RequireAPIKey))
	api.HandleFunc("/smtp/{id:[0-9]+}", Use(API_SMTP_Id, mid.RequireAPIKey))
	api.HandleFunc("/util/send_test_email", Use(API_Send_Test_Email, mid.RequireAPIKey))
	api.HandleFunc("/import/group", API_Import_Group)
	api.HandleFunc("/import/email", API_Import_Email)
	api.HandleFunc("/import/site", API_Import_Site)

	// Setup static file serving
	router.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/")))

	// Setup CSRF Protection
	csrfHandler := nosurf.New(router)
	// Exempt API routes and Static files
	csrfHandler.ExemptGlob("/api/campaigns")
	csrfHandler.ExemptGlob("/api/campaigns/*")
	csrfHandler.ExemptGlob("/api/groups")
	csrfHandler.ExemptGlob("/api/groups/*")
	csrfHandler.ExemptGlob("/api/templates")
	csrfHandler.ExemptGlob("/api/templates/*")
	csrfHandler.ExemptGlob("/api/pages")
	csrfHandler.ExemptGlob("/api/pages/*")
	csrfHandler.ExemptGlob("/api/smtp")
	csrfHandler.ExemptGlob("/api/smtp/*")
	csrfHandler.ExemptGlob("/api/import/*")
	csrfHandler.ExemptGlob("/api/util/*")
	csrfHandler.ExemptGlob("/static/*")
	return Use(csrfHandler.ServeHTTP, mid.GetContext)
}
开发者ID:TheBigBear,项目名称:gophish,代码行数:59,代码来源:route.go

示例6: New

func New(handler http.Handler) http.Handler {
	n := nosurf.New(handler)
	n.SetFailureHandler(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		b := base.New(rw, r, false)
		b.SetTitle("text11")
		b.RenderContentPart(vioTmpl, nil)
		b.Render()
	}))

	return n
}
开发者ID:andrewtremblay,项目名称:GoAuth,代码行数:11,代码来源:controller.go

示例7: Start

func Start(DB *Connection, config *Config) {
	// Create a new cookie store
	store := sessions.NewCookieStore([]byte(config.SecretKey))

	m := martini.Classic()

	// It will be available to all handlers as *sessions.CookieStore
	m.Map(store)

	// It will be available to all handlers as *connection *Connection
	m.Map(DB)

	// It will be available to all handlers as *Config
	m.Map(config)

	// public folder will serve the static content
	m.Use(martini.Static("public"))

	// Tag-related routes
	m.Get("/tag/:tag/:page", AuthRequired, GetTagHandler)

	// Bookmark-related routes
	m.Get("/bookmarks/:page", AuthRequired, GetBookmarksHandler)
	m.Post("/bookmark/new", AuthRequired, NewBookmarkHandler)
	m.Post("/bookmark/update/:bookmark", AuthRequired, EditBookmarkHandler)
	m.Delete("/bookmark/delete/:bookmark", AuthRequired, DeleteBookmarkHandler)

	// Search
	m.Post("/search/:page", AuthRequired, SearchHandler)

	// User-related routes
	m.Post("/login", LoginPostHandler)
	m.Get("/logout", AuthRequired, LogoutHandler)
	m.Post("/signup", SignUpHandler)
	m.Post("/new_token", AuthRequired, RequestNewToken)

	// Test
	m.Get("/test", TestHandler)

	// Home
	m.Get("/", func(cs *sessions.CookieStore, req *http.Request, w http.ResponseWriter, connection *Connection) {
		if GetUserID(cs, req, connection) == "" {
			LoginHandler(req, w)
		}
	}, IndexHandler)

	csrfHandler := nosurf.New(m)
	csrfHandler.SetFailureHandler(http.HandlerFunc(CsrfFailHandler))

	http.ListenAndServe(config.Port, csrfHandler)
}
开发者ID:gauthierc,项目名称:magnet,代码行数:51,代码来源:handler.go

示例8: runWeb

// runWeb is an starts the GIN application
func runWeb(ctx *cli.Context) {
	r := gin.Default()
	r.HTMLRender = pongo2gin.Default() // Use Pongo2 for templates

	setupMiddleware(r)
	setupRoutes(r)

	// Initialise nosurf for csrf token support.
	csrfHandler := nosurf.New(r)
	csrfHandler.SetFailureHandler(http.HandlerFunc(csrfFailed))
	csrfHandler.ExemptRegexp("/api/(.*)") // ignore API urls for the time being

	// Start the Gin application with nosurf (for csrf protection).
	// This is an alternative way to start up the Gin application.
	http.ListenAndServe(":"+config.Config.Port, csrfHandler)
}
开发者ID:robvdl,项目名称:gcms,代码行数:17,代码来源:web.go

示例9: main

func main() {
	/*
	   myHandler := http.HandlerFunc(myFunc)
	   fmt.Println("Listening on http://127.0.0.1:8000/")
	   http.ListenAndServe(":8000", nosurf.New(myHandler))
	*/

	myHandler := http.HandlerFunc(myFunc)
	http.HandleFunc("/", nosurf.New(myHandler))
	fmt.Println("Listening on http://127.0.0.1:8000/")
	http.ListenAndServe(":8000", nil)

	/*
			http.HandleFunc("/", nosurf.New(myFunc))
		    fmt.Println("Listening on http://127.0.0.1:8000/")

		    http.ListenAndServe(":8000", nil)
	*/

}
开发者ID:isikfsc,项目名称:otp,代码行数:20,代码来源:csrf.go

示例10: CsrfMiddleware

// CsrfMiddleware adds CSRF support via nosurf.
func CsrfMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	var token string
	var passed bool

	// nosurf disposes of the token as soon as it calls the http.Handler you provide...
	// in order to use it as negroni middleware, pull out token and dispose of it ourselves
	csrfHandler := nosurf.New(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
		token = nosurf.Token(r)
		passed = true
	}))
	csrfHandler.ExemptRegexp("/v1(.*)")
	csrfHandler.ServeHTTP(w, r)

	// csrf passed
	if passed {
		context.Set(r, "csrf_token", token)
		next(w, r)
		context.Delete(r, "csrf_token")
	}
}
开发者ID:oceandiver,项目名称:firstgo,代码行数:21,代码来源:middleware.go

示例11: main

func main() {
	http.HandleFunc("/", Index)

	// when you route urls with .Handle[Func]() they end up on DefaultServeMux
	csrfHandler := nosurf.New(http.DefaultServeMux)

	// exempting by an exact path...
	// won't exempt /faq/question-1
	csrfHandler.ExemptPath("/faq")

	// exempting by a glob
	// will exempt /post, /post1, /post2, etc.
	// won't exempt /post1/comments, as * stops at a /
	csrfHandler.ExemptGlob("/post*")

	// exempting by a regexp
	// will exempt /static, /static/, /static/favicon.ico, /static/css/style.css, etc.
	csrfHandler.ExemptRegexp("/static(.*)")

	// setting the failureHandler. Will call this in case the CSRF check fails.
	csrfHandler.SetFailureHandler(http.HandlerFunc(failHand))

	http.ListenAndServe(":8000", csrfHandler)
}
开发者ID:marswang,项目名称:nosurf,代码行数:24,代码来源:advanced.go

示例12: Nosurf

// Nosurf is a wrapper for justinas' csrf protection middleware
func Nosurf() func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return nosurf.New(next)
	}
}
开发者ID:mvpmvh,项目名称:interpose,代码行数:6,代码来源:nosurf.go

示例13: main

func main() {
	var port string

	hostname, err := os.Hostname()
	if err != nil {
		fmt.Println("Error getting hostname:", err)
	}

	if hostname == "pythia" {
		port = ":80"
	} else {
		port = ":8080"
	}

	fieldsToIndex := make(map[string][]string)
	fieldsToIndex["answers"] = []string{"tags"}
	fieldsToIndex["users"] = []string{"login"}

	db, err := ivy.OpenDB("data", fieldsToIndex)
	if err != nil {
		fmt.Println("Database initialization failed:", err)
	}

	defer db.Close()

	store := sessions.NewCookieStore([]byte("pythia-is-awesome"))

	gv := global_vars.GlobalVars{MyDB: db, SessionStore: store}

	fs := http.FileServer(http.Dir("static"))
	http.Handle("/static/", http.StripPrefix("/static/", fs))

	r := mux.NewRouter()
	r.HandleFunc("/", makeHandler(answers_handler.Index, &gv)).Methods("GET")

	r.HandleFunc("/answers", makeHandler(answers_handler.Index, &gv)).Methods("GET")
	r.HandleFunc("/answers/search", makeHandler(answers_handler.Index, &gv)).Methods("POST")
	r.HandleFunc("/answers/{id:[0-9]+}", makeHandler(answers_handler.View, &gv)).Methods("GET")
	r.HandleFunc("/answers/new", makeHandler(answers_handler.New, &gv)).Methods("GET")
	r.HandleFunc("/answers/create", makeHandler(answers_handler.Create, &gv)).Methods("POST")
	r.HandleFunc("/answers/{id:[0-9]+}/edit", makeHandler(answers_handler.Edit, &gv)).Methods("GET")
	r.HandleFunc("/answers/update", makeHandler(answers_handler.Update, &gv)).Methods("POST")
	r.HandleFunc("/answers/{id:[0-9]+}/delete", makeHandler(answers_handler.Delete, &gv)).Methods("GET")
	r.HandleFunc("/answers/destroy", makeHandler(answers_handler.Destroy, &gv)).Methods("POST")

	r.HandleFunc("/users", makeHandler(users_handler.Index, &gv)).Methods("GET")
	r.HandleFunc("/users/{id:[0-9]+}", makeHandler(users_handler.View, &gv)).Methods("GET")
	r.HandleFunc("/users/new", makeHandler(users_handler.New, &gv)).Methods("GET")
	r.HandleFunc("/users/create", makeHandler(users_handler.Create, &gv)).Methods("POST")
	r.HandleFunc("/users/{id:[0-9]+}/edit", makeHandler(users_handler.Edit, &gv)).Methods("GET")
	r.HandleFunc("/users/update", makeHandler(users_handler.Update, &gv)).Methods("POST")
	r.HandleFunc("/users/{id:[0-9]+}/delete", makeHandler(users_handler.Delete, &gv)).Methods("GET")
	r.HandleFunc("/users/destroy", makeHandler(users_handler.Destroy, &gv)).Methods("POST")

	r.HandleFunc("/logins/new", makeHandler(logins_handler.New, &gv)).Methods("GET")
	r.HandleFunc("/logins/create", makeHandler(logins_handler.Create, &gv)).Methods("POST")
	r.HandleFunc("/logout", makeHandler(logins_handler.Logout, &gv)).Methods("GET")

	http.Handle("/", r)

	csrfHandler := nosurf.New(http.DefaultServeMux)

	csrfHandler.SetFailureHandler(http.HandlerFunc(failHand))

	http.ListenAndServe(port, csrfHandler)
}
开发者ID:anukat2015,项目名称:pythia,代码行数:66,代码来源:pythia.go

示例14: main

func main() {

	//SSH goroutine

	go func() {
		config := ssh.ServerConfig{
			PublicKeyCallback: keyAuth,
		}
		config.AddHostKey(hostPrivateKeySigner)

		port := strconv.Itoa(hostSSHPort)

		socket, err := net.Listen("tcp", ":"+port)
		if err != nil {
			panic(err)
		}

		for {
			conn, err := socket.Accept()
			if err != nil {
				panic(err)
			}

			// From a standard TCP connection to an encrypted SSH connection
			sshConn, chans, reqs, err := ssh.NewServerConn(conn, &config)
			if err != nil {
				log.Println("Error accepting ssh connection: ", err)
				continue
			}

			log.Println("Connection from", sshConn.RemoteAddr())

			// Print incoming out-of-band Requests
			go handleRequests(reqs)
			// Accept all channels
			go handleChannels(chans)
		}
	}()

	//

	// Garbage collecting goroutine
	// For testing, a stop-the-world gc using mutexes shall be 'nuff
	go func() {

		for {
			authRequestMap.Lock()

			for k, v := range authRequestMap.timestamps {

				killtime := time.Now().Add(-5 * time.Minute)

				if v.Before(killtime) {
					log.Debugf("Garbage collected key %s, %v old", k, time.Now().Sub(v))
					delete(authRequestMap.timestamps, k)
					delete(authRequestMap.matches, k)
				}

			}

			authRequestMap.Unlock()
			time.Sleep(2 * time.Minute)
		}

	}()

	templateStart, err = template.New("index.html").ParseFiles("index.html")
	if err != nil {
		panic(err)
	}

	templateAuth, err = template.New("auth.html").ParseFiles("auth.html")
	if err != nil {
		panic(err)
	}

	http.HandleFunc("/auth", authRequestHandler)
	http.HandleFunc("/", startHandler)

	weblogOptions := &weblogs.Options{

		Writer: nil,
		Logger: customLogger{},
	}

	csrfHandler := nosurf.New(http.DefaultServeMux)

	csrfHandler.SetBaseCookie(http.Cookie{HttpOnly: true, Secure: sslEnabled})

	handler := context.ClearHandler(weblogs.HandlerWithOptions(csrfHandler, weblogOptions))

	if sslEnabled {
		go http.ListenAndServe(":"+strconv.Itoa(hostHTTPPort), handler)
		http.ListenAndServeTLS(":"+strconv.Itoa(hostTLSPort), sslCertPath, sslKeyPath, handler)
	} else {
		http.ListenAndServe(":"+strconv.Itoa(hostHTTPPort), handler)
	}
}
开发者ID:FlamesRunner,项目名称:webauth-ssh-go,代码行数:98,代码来源:main.go

示例15: main

func main() {
	myHandler := http.HandlerFunc(myFunc)
	fmt.Println("Listening on http://127.0.0.1:8000/")
	http.ListenAndServe(":8000", nosurf.New(myHandler))
}
开发者ID:marswang,项目名称:nosurf,代码行数:5,代码来源:simple.go


注:本文中的github.com/justinas/nosurf.New函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。