func Test_LoginRedirectAfterLoginRequired(t *testing.T) { recorder := httptest.NewRecorder() n := negroni.New() n.Use(sessions.Sessions("my_session", cookiestore.New([]byte("secret123")))) n.Use(Google(&Config{ ClientID: "client_id", ClientSecret: "client_secret", RedirectURL: "refresh_url", Scopes: []string{"x", "y"}, })) n.Use(LoginRequired()) mux := http.NewServeMux() mux.HandleFunc("/login-required", func(w http.ResponseWriter, req *http.Request) { t.Log("hi there") fmt.Fprintf(w, "OK") }) n.UseHandler(mux) r, _ := http.NewRequest("GET", "/login-required?key=value", nil) n.ServeHTTP(recorder, r) location := recorder.HeaderMap["Location"][0] if recorder.Code != 302 { t.Errorf("Not being redirected to the auth page.") } if location != "/login?next=%2Flogin-required%3Fkey%3Dvalue" { t.Errorf("Not being redirected to the right page, %v found", location) } }
func Test_LoginRequired(t *testing.T) { recorder := httptest.NewRecorder() n := negroni.Classic() n.Use(sessions.Sessions("my_session", cookiestore.New([]byte("secret123")))) n.Use(Google(&Config{ ClientID: "foo", ClientSecret: "foo", RedirectURL: "foo", })) n.Use(LoginRequired()) mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "OK") }) n.UseHandler(mux) r, _ := http.NewRequest("GET", "/", nil) n.ServeHTTP(recorder, r) if recorder.Code != 302 { t.Errorf("Not being redirected to the auth page although user is not logged in. %d\n", recorder.Code) } }
func main() { fmt.Println("Starting sample auth...") n := negroni.Classic() n.Use(sessions.Sessions("mysession", cookiestore.New([]byte("secret12")))) n.Use(KeyCloak(&oauth2.Config{ ClientID: "grafana", ClientSecret: "10b54f7c-a8ed-4a61-abd7-eb993d12367b", RedirectURL: "http://127.0.0.1:8090/oauth2callback", Scopes: []string{"name", "email"}})) router := mux.NewRouter() router.HandleFunc("/", Home) router.HandleFunc("/version", Version) router.HandleFunc("/hello", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "World !") }) n.Use(oauth2.LoginRequired()) n.UseHandler(router) n.Run(":8090") }
// Serve set the route handlers and serve func Serve() { // Setup middleware middle := negroni.Classic() store := cookiestore.New([]byte("keyboard cat")) middle.Use(sessions.Sessions("hugoku", store)) router := httprouter.New() router.GET("/", routes.Index) router.GET("/auth/login", routes.GithubLogin) router.GET("/auth/logout", routes.GithubLogout) router.GET("/auth/callback", routes.GithubLoginCallback) router.GET("/project/:id", routes.GetProject) router.POST("/project", routes.PostProject) router.DELETE("/project/:id", routes.DeleteProject) router.GET("/about", routes.About) router.GET("/faq", routes.FAQ) // Apply middleware to the router middle.UseHandler(router) log.Println("Started running on http://127.0.0.1:8080") // TODO: Get the port from flag, config file or environment var log.Fatal(http.ListenAndServe(":8080", middle)) }
func Test_LogoutOnAccessTokenExpiration(t *testing.T) { recorder := httptest.NewRecorder() s := cookiestore.New([]byte("secret123")) n := negroni.Classic() n.Use(sessions.Sessions("my_session", s)) n.Use(Google(&Config{ ClientID: "foo", ClientSecret: "foo", RedirectURL: "foo", })) mux := http.NewServeMux() mux.HandleFunc("/addtoken", func(w http.ResponseWriter, req *http.Request) { SetToken(req, "dummy token") fmt.Fprintf(w, "OK") }) mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { tok := GetToken(req) if tok != nil { t.Errorf("User not logged out although access token is expired. %v\n", tok) } }) n.UseHandler(mux) addtoken, _ := http.NewRequest("GET", "/addtoken", nil) index, _ := http.NewRequest("GET", "/", nil) n.ServeHTTP(recorder, addtoken) n.ServeHTTP(recorder, index) }
func Test_SessionsDeleteValue(t *testing.T) { n := negroni.Classic() store := cookiestore.New([]byte("secret123")) n.Use(sessions.Sessions("my_session", store)) mux := http.NewServeMux() mux.HandleFunc("/testsession", func(w http.ResponseWriter, req *http.Request) { session := sessions.GetSession(req) session.Set("hello", "world") session.Delete("hello") fmt.Fprintf(w, "OK") }) mux.HandleFunc("/show", func(w http.ResponseWriter, req *http.Request) { session := sessions.GetSession(req) if session.Get("hello") == "world" { t.Error("Session value deleting failed") } fmt.Fprintf(w, "OK") }) n.UseHandler(mux) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/testsession", nil) n.ServeHTTP(res, req) res2 := httptest.NewRecorder() req2, _ := http.NewRequest("GET", "/show", nil) req2.Header.Set("Cookie", res.Header().Get("Set-Cookie")) n.ServeHTTP(res2, req2) }
func main() { // 라우터 생성 router := httprouter.New() // 핸들러 정의 router.GET("/", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // 렌더러를 사용하여 템플릿 렌더링 renderer.HTML(w, http.StatusOK, "index", map[string]interface{}{"host": r.Host}) }) router.GET("/rooms", retrieveRooms) router.GET("/rooms/:id", retrieveRoom) router.POST("/rooms", createRoom) router.DELETE("/rooms/:id", deleteRoom) router.GET("/rooms/:id/messages", retrieveMessages) // router.POST("/rooms/:id/messages", createMessage) router.GET("/info", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { u := GetCurrentUser(r) info := map[string]interface{}{"currrent_user": u, "clients": clients} renderer.JSON(w, http.StatusOK, info) }) router.GET("/login", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // login 페이지 렌더링 renderer.HTML(w, http.StatusOK, "login", nil) }) router.GET("/logout", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // 세션에서 사용자 정보 제거 후 로그인 페이지로 이동 sessions.GetSession(r).Delete(currentUserKey) http.Redirect(w, r, "/login", http.StatusFound) }) router.GET("/auth/:action/:provider", loginHandler) router.GET("/ws/:room_id", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { socket, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Fatal("ServeHTTP:", err) return } newClient(socket, ps.ByName("room_id"), GetCurrentUser(r)) }) // negroni 미들웨어 생성 n := negroni.Classic() store := cookiestore.New([]byte(sessionSecret)) n.Use(sessions.Sessions(sessionKey, store)) n.Use(LoginRequired("/login", "/auth")) // negroni에 router를 핸들러로 등록 n.UseHandler(router) // 웹서버 실행 n.Run(":3000") }
func main() { // Load the configuration. err := envconfig.Process("elwinar", &configuration) if err != nil { log.Fatalln("unable to read the configuration from env:", err) } // Open the database connection. database, err = sqlx.Connect("sqlite3", configuration.Database) if err != nil { log.Fatalln("unable to open the database:", err) } // Initialize the router. router := httprouter.New() // Add the front-office handlers. router.GET("/", Index) router.GET("/read", List) router.GET("/article/:slug", View) router.GET("/fortune", Fortune) router.GET("/sitemap.xml", Sitemap) // Add the back-office handlers. router.GET("/login", Login) router.POST("/login", Authenticate) router.GET("/logout", Logout) router.GET("/write", Write) router.POST("/write", Create) router.GET("/article/:slug/edit", Edit) router.POST("/article/:slug/edit", Update) router.GET("/article/:slug/delete", Delete) router.GET("/article/:slug/publish", Publish) router.GET("/article/:slug/unpublish", Unpublish) // Initialize the server middleware stack. stack := negroni.New() stack.Use(gzip.Gzip(gzip.DefaultCompression)) stack.Use(negroni.NewRecovery()) stack.Use(negroni.NewStatic(http.Dir(configuration.Public))) stack.Use(sessions.Sessions("elwinar", cookiestore.New([]byte(configuration.Secret)))) stack.UseHandler(router) // Initialize the HTTP server. server := &graceful.Server{ Timeout: 1 * time.Second, Server: &http.Server{ Addr: fmt.Sprintf(":%d", configuration.Port), Handler: stack, }, } // Run the server. err = server.ListenAndServe() if err != nil { log.Fatalln("unable to run the server:", err) } }
func main() { //Loads environment variables from a .env file godotenv.Load("environment") var ( clientID = getEnv("OAUTH2_CLIENT_ID", "client_id") clientSecret = getEnv("OAUTH2_CLIENT_SECRET", "client_secret") redirectURL = getEnv("OAUTH2_REDIRECT_URL", "redirect_url") ) secureMux := http.NewServeMux() // Routes that require a logged in user // can be protected by using a separate route handler // If the user is not authenticated, they will be // redirected to the login path. secureMux.HandleFunc("/restrict", func(w http.ResponseWriter, req *http.Request) { token := oauth2.GetToken(req) fmt.Fprintf(w, "OK: %s", token.Access()) }) secure := negroni.New() secure.Use(oauth2.LoginRequired()) secure.UseHandler(secureMux) n := negroni.New() n.Use(sessions.Sessions("my_session", cookiestore.New([]byte("secret123")))) n.Use(oauth2.Google(&oauth2.Config{ ClientID: clientID, ClientSecret: clientSecret, RedirectURL: redirectURL, Scopes: []string{"https://www.googleapis.com/auth/drive"}, })) router := http.NewServeMux() //routes added to mux do not require authentication router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { token := oauth2.GetToken(req) if token == nil || !token.Valid() { fmt.Fprintf(w, "not logged in, or the access token is expired") return } fmt.Fprintf(w, "logged in") return }) //There is probably a nicer way to handle this than repeat the restricted routes again //of course, you could use something like gorilla/mux and define prefix / regex etc. router.Handle("/restrict", secure) n.UseHandler(router) n.Run(":3000") }
func main() { ren := render.New(render.Options{ Layout: "shared/layout", IsDevelopment: true, }) //sessions store := cookiestore.New([]byte("secret")) //db // db, err := sqlx.Connect("postgres", os.Getenv("CONNECTIONSTRING")) db, err := sqlx.Connect("postgres", "user=travisjones dbname=cm_app sslmode=disable") if err != nil { log.Println("Error initializing database...") log.Fatalln(err) } c := ctx{db, ren} n := negroni.New() nauth := negroni.New() //routers router := mux.NewRouter() authRouter := mux.NewRouter() //AUTHORIZED ROUTES authRouter.HandleFunc("/", c.Home) router.Handle("/", nauth).Methods("GET") //OPEN ROUTES router.HandleFunc("/account/login", c.Login).Methods("GET") router.HandleFunc("/account/login", c.LoginPost).Methods("POST") router.HandleFunc("/account/signup", c.Signup).Methods("GET") router.HandleFunc("/account/signup", c.SignupPost).Methods("POST") router.HandleFunc("/account/logout", c.Logout).Methods("GET") //Middleware nauth.Use(negroni.HandlerFunc(RequireAuth)) nauth.UseHandler(authRouter) //Sessions n.Use(sessions.Sessions("authex", store)) n.Use(negroni.NewStatic(http.Dir("public"))) n.UseHandler(router) n.Run( fmt.Sprint(":", os.Getenv("PORT")), ) }
func runWeb() { mux := http.NewServeMux() mux.HandleFunc("/config", HandleConfig) mux.HandleFunc("/", HandleLogin) n := negroni.Classic() store := cookiestore.New([]byte("ss")) n.Use(sessions.Sessions("shadow", store)) //n.Use(gzip.Gzip(gzip.DefaultCompression)) n.UseHandler(mux) n.Run(":3000") }
func main() { store := cookiestore.New([]byte("secretkey789")) router := LoadRoutes() n := negroni.Classic() static := negroni.NewStatic(http.Dir("static")) static.Prefix = "/static" n.Use(static) n.Use(negroni.HandlerFunc(MgoMiddleware)) n.Use(sessions.Sessions("global_session_store", store)) n.UseHandler(router) n.Run(":3000") }
func main() { rt := httprouter.New() rt.GET("/", AuthHandler) rt.GET("/tmpl", DlmHandler) rt.POST("/upload", upload.UploadHandler) n := negroni.Classic() store := cookiestore.New([]byte("session_secret")) n.Use(sessions.Sessions("my_session", store)) n.UseHandler(rt) n.Run(":10000") }
func main() { defer db.Close() mux := http.NewServeMux() n := negroni.Classic() store := cookiestore.New([]byte("ohhhsooosecret")) n.Use(sessions.Sessions("global_session_store", store)) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { SimplePage(w, r, "mainpage") }) mux.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { SimplePage(w, r, "login") } else if r.Method == "POST" { LoginPost(w, r) } }) mux.HandleFunc("/signup", func(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { SimplePage(w, r, "signup") } else if r.Method == "POST" { SignupPost(w, r) } }) mux.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) { Logout(w, r) }) mux.HandleFunc("/home", func(w http.ResponseWriter, r *http.Request) { SimpleAuthenticatedPage(w, r, "home") }) mux.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) { APIHandler(w, r) }) mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) n.UseHandler(mux) port := os.Getenv("PORT") if port == "" { port = "3300" } n.Run(":" + port) }
/** * Constructs a new server object. */ func NewCoreServer() CoreServer { server := CoreServer{ Router: mux.NewRouter(), Middleware: negroni.New(), } /** * Add some Negroni middleware. */ server.Middleware.Use(negroni.NewLogger()) // TODO: Need to change key. storage := cookiestore.New([]byte("temporary")) server.Middleware.Use(sessions.Sessions("userprofile", storage)) config := (oauth2.Config)(GetClientConfig()) server.Middleware.Use(oauth2.Google(&config)) /** * Mux describing routes that require the user to be logged in via * oauth first. */ secureMux := http.NewServeMux() // Core app handlers; these require the user to be logged in. secureMux.HandleFunc("/app/fetch", fetch) secureMux.HandleFunc("/app", app_handler) secure := negroni.New() secure.Use(oauth2.LoginRequired()) secure.UseHandler(secureMux) /** * Handlers that don't require authentication. */ server.Router.HandleFunc("/auth", auth_handler) // Static content handler server.Router.PathPrefix("/static").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("web/")))) // Simple redirect handler server.Router.HandleFunc("/", main_handler) /** * And now connect everything together and call it a day. */ // Make sure the core router knows to let the secure router handle these routes. server.Router.Handle("/app/fetch", secure) server.Router.Handle("/app", secure) // Set negroni handler server.Middleware.UseHandler(server.Router) return server }
func Serve(r *mux.Router) { store := cookiestore.New([]byte("some-super-secret-key")) store.Options(sessions.Options{ Path: "/", // to match all requests MaxAge: 3600 * 8, // 8 hour HTTPOnly: true, }) n := negroni.Classic() n.Use(sessions.Sessions("plansource", store)) n.Use(negroni.HandlerFunc(UpdateLastSeen)) n.UseHandler(r) n.Run(fmt.Sprintf(":%s", os.Getenv("PORT"))) }
func Test_Flashes(t *testing.T) { n := negroni.Classic() store := cookiestore.New([]byte("secret123")) n.Use(sessions.Sessions("my_session", store)) mux := http.NewServeMux() mux.HandleFunc("/set", func(w http.ResponseWriter, req *http.Request) { session := sessions.GetSession(req) session.AddFlash("hello world") fmt.Fprintf(w, "OK") }) mux.HandleFunc("/show", func(w http.ResponseWriter, req *http.Request) { session := sessions.GetSession(req) l := len(session.Flashes()) if l != 1 { t.Error("Flashes count does not equal 1. Equals ", l) } fmt.Fprintf(w, "OK") }) mux.HandleFunc("/showagain", func(w http.ResponseWriter, req *http.Request) { session := sessions.GetSession(req) l := len(session.Flashes()) if l != 0 { t.Error("flashes count is not 0 after reading. Equals ", l) } fmt.Fprintf(w, "OK") }) n.UseHandler(mux) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/set", nil) n.ServeHTTP(res, req) res2 := httptest.NewRecorder() req2, _ := http.NewRequest("GET", "/show", nil) req2.Header.Set("Cookie", res.Header().Get("Set-Cookie")) n.ServeHTTP(res2, req2) res3 := httptest.NewRecorder() req3, _ := http.NewRequest("GET", "/showagain", nil) req3.Header.Set("Cookie", res2.Header().Get("Set-Cookie")) n.ServeHTTP(res3, req3) }
func NewServer(dba utils.DatabaseAccessor, cua utils.CurrentUserAccessor, clientID, clientSecret, sessionSecret string, isDevelopment bool, gaKey string) *Server { s := Server{negroni.Classic()} session := utils.NewSessionManager() basePage := utils.NewBasePageCreator(cua, gaKey) renderer := render.New() router := mux.NewRouter() router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { t, _ := template.ParseFiles("views/layout.html", "views/index.html") t.Execute(w, basePage.Get(r)) }) router.HandleFunc("/legal", func(w http.ResponseWriter, r *http.Request) { t, _ := template.ParseFiles("views/layout.html", "views/legal.html") t.Execute(w, basePage.Get(r)) }) router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t, _ := template.ParseFiles("views/layout.html", "views/404.html") t.Execute(w, basePage.Get(r)) }) accountController := controllers.NewAccountController(clientID, clientSecret, isDevelopment, session, dba, cua, basePage, renderer) accountController.Register(router) createServiceController := controllers.NewCreateServiceController(cua, basePage, renderer, dba) createServiceController.Register(router) serviceController := controllers.NewServiceController(cua, basePage, renderer, dba) serviceController.Register(router) codeController := controllers.NewReferralCodeController(cua, renderer, dba) codeController.Register(router) searchController := controllers.NewSearchController(cua, basePage, renderer, dba) searchController.Register(router) sitemapController := controllers.NewSitemapController(dba) sitemapController.Register(router) s.Use(negroni.HandlerFunc(secure.New(secure.Options{ AllowedHosts: []string{"www.refer-madness.com", "refer-madness.com"}, ContentTypeNosniff: true, BrowserXssFilter: true, FrameDeny: true, IsDevelopment: isDevelopment, }).HandlerFuncWithNext)) s.Use(sessions.Sessions("refermadness", cookiestore.New([]byte(sessionSecret)))) s.Use(middleware.NewDatabase(dba).Middleware()) s.Use(middleware.NewAuthenticator(dba, session, cua).Middleware()) s.UseHandler(router) return &s }
func Test_Options(t *testing.T) { n := negroni.Classic() store := cookiestore.New([]byte("secret123")) store.Options(sessions.Options{ Domain: "negroni-sessions.goincremental.com", }) n.Use(sessions.Sessions("my_session", store)) mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { session := sessions.GetSession(req) session.Set("hello", "world") session.Options(sessions.Options{ Path: "/foo/bar/bat", }) fmt.Fprintf(w, "OK") }) mux.HandleFunc("/foo", func(w http.ResponseWriter, req *http.Request) { session := sessions.GetSession(req) session.Set("hello", "world") fmt.Fprintf(w, "OK") }) n.UseHandler(mux) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/", nil) n.ServeHTTP(res, req) res2 := httptest.NewRecorder() req2, _ := http.NewRequest("GET", "/foo", nil) n.ServeHTTP(res2, req2) s := strings.Split(res.Header().Get("Set-Cookie"), ";") if s[1] != " Path=/foo/bar/bat" { t.Error("Error writing path with options:", s[1]) } s = strings.Split(res2.Header().Get("Set-Cookie"), ";") if s[1] != " Domain=negroni-sessions.goincremental.com" { t.Error("Error writing domain with options:", s[1]) } }
func main() { env = os.Getenv("XTREMEPAY_SERVICE") router := mux.NewRouter() n := negroni.New(negroni.NewLogger()) viperConfig := viper.New() store := cookiestore.New([]byte("secret123")) n.Use(sessions.Sessions("my_session", store)) c := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, }) serviceManager := ServiceManager{router, n, viperConfig, c} serviceManager.LoadConfig(env) serviceManager.LoadService() }
func Run() { settings, err := forge.ParseFile("config.cfg") if err != nil { panic(err) } amqp, err := settings.GetSection("amqp") username, err := amqp.GetString("uname") amqpAddress, err := amqp.GetString("amqp_address") //ueGuid, err := amqp.GetString("ueguid") host, err := settings.GetSection("host") port, err := host.GetString("port") // Process Amqp messages go processAmqp(username, amqpAddress) log.SetFlags(log.LstdFlags | log.Llongfile) log.Printf("UTM-API SERVICE (%s) REST INTERFACE LISTENING ON %s\n", logTag, listenAddress) store := cookiestore.New([]byte("secretkey789")) router := routes.LoadRoutes() // router.Handle("/", utilities.Handler(login)) //router.Handle("/login", utilities.Handler(login)) router.HandleFunc("/register", registerHandler) router.HandleFunc("/login", loginHandler) //router.Handle("/register", utilities.Handler(register)) router.Handle("/latestState", utilities.Handler(getLatestState)) router.Handle("/reportingInterval", utilities.Handler(setReportingInterval)) n := negroni.Classic() static := negroni.NewStatic(http.Dir("static")) static.Prefix = "/static" n.Use(static) n.Use(negroni.HandlerFunc(system.MgoMiddleware)) n.Use(sessions.Sessions("global_session_store", store)) n.UseHandler(router) n.Run(port) }
func Test_SessionsClear(t *testing.T) { n := negroni.Classic() data := map[string]string{ "hello": "world", "foo": "bar", "apples": "oranges", } store := cookiestore.New([]byte("secret123")) n.Use(sessions.Sessions("my_session", store)) mux := http.NewServeMux() mux.HandleFunc("/testsession", func(w http.ResponseWriter, req *http.Request) { session := sessions.GetSession(req) for k, v := range data { session.Set(k, v) } session.Clear() fmt.Fprintf(w, "OK") }) mux.HandleFunc("/show", func(w http.ResponseWriter, req *http.Request) { session := sessions.GetSession(req) for k, v := range data { if session.Get(k) == v { t.Fatal("Session clear failed") } } fmt.Fprintf(w, "OK") }) n.UseHandler(mux) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/testsession", nil) n.ServeHTTP(res, req) res2 := httptest.NewRecorder() req2, _ := http.NewRequest("GET", "/show", nil) req2.Header.Set("Cookie", res.Header().Get("Set-Cookie")) n.ServeHTTP(res2, req2) }
func Listen() { logger := iDnegroniLog.NewMiddleware(idl.StandardLogger()) logger.Stack2Http = config.AnaLog.DevelopmentEnv n := negroni.New(logger /*negroni.NewStatic(http.Dir(helper.GetFilePath("./public")))*/) cookiestore := cookiestore.New([]byte(config.AnaLog.CookieSecret)) n.Use(sessions.Sessions("perm_analog_session", cookiestore)) n.Use(negroni.HandlerFunc(preflight)) n.UseHandler(router.New()) if config.AnaLog.UseSocketMaster { listener, err := client.Listen(protocol.SocketDefinition{ Port: config.SocketMaster.Port, HTTP: &protocol.SocketHTTPDefinition{ DomainSuffix: config.SocketMaster.DomainSuffix, PathPrefix: config.SocketMaster.PathPrefix, }, /*TLS: &protocol.SocketTLSDefinition{ Cert: config.SocketMaster.Cert, Key: config.SocketMaster.Key, },*/ }) if err != nil { idl.Emerg(err) } idl.Notice("Serving via SocketMaster") http.Serve(listener, n) } else if config.AnaLog.Fcgi { listener, err := net.Listen("tcp", config.AnaLog.Listen) if err != nil { idl.Emerg(err) } idl.Notice("Serving via FastCGI") fcgi.Serve(listener, n) } else { idl.Notice("Serving via inbuilt HTTP Server") n.Run(config.AnaLog.Listen) } }
func main() { box := fritz.NewFritzbox() mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { IndexHandler(w, r, box) } }) // handlers mux.HandleFunc("/unlockPop", func(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { LockHandler(w, r, "8204", false, box) } }) mux.HandleFunc("/rebootRepeater", func(w http.ResponseWriter, r *http.Request) { /* TODO 1) POST to http://fritz.repeater/cgi-bin/webcm getpage:../html/reboot.html errorpage:../html/de/menus/menu2.html var:pagename:reset var:errorpagename:reset var:menu:system var:pagemaster: time:settings/time:1443519148,-120 var:tabReset:0 logic:command/reboot:../gateway/commands/saveconfig.html 2) POST to http://fritz.box/system/reboot.lua sid:1502bfc630ac427b reboot: */ }) n := negroni.Classic() store := cookiestore.New([]byte("terrible2os!")) n.Use(sessions.Sessions("gurkherpaderp", store)) n.UseHandler(mux) n.Run(":3001") }
func main() { app := gogo.New() app.Use(NewRecoveryMiddleware()) // app.Use(NewLoggerMiddleware()) app.Use(NewGorillaLogger()) // app.Use(NewBasicAuth("foo", "bar")) app.Use(NewGzipMiddleware(gzip.DefaultCompression)) app.Use(NewSessions("gogosession", cookiestore.New([]byte("secret123")))) app.Use(NewStaticMiddleware(http.Dir("static"))) app.Get("/", func(c context.Context, w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "gogo server\n") }) app.Get("/hello/:name", func(c context.Context, w http.ResponseWriter, r *http.Request) { name := gogo.Param(c, "name") fmt.Fprintf(w, "Hello, %s!\n", name) }) app.Run(":8080") }
func main() { c, err := config.LoadConfig(configPath) if err != nil { log.Fatal(err) } pp.Println(c) cookieStore := cookiestore.New([]byte(c.SessionKey)) cookieStore.Options(sessions.Options{Domain: c.Domain}) a := auth.New(c) n := negroni.New() n.Use(sessions.Sessions("session", cookieStore)) n.Use(a.NewOauth2Provider()) n.Use(a.LoginRequired()) n.Use(a.RestrictRequest()) n.Use(proxy.Proxy(c)) ran.Run(c.Addr, n) }
func main() { // Load configuration // TODO: How to share this config with the handlers? configuration, err := config.Load("./config.json") if err != nil { log.Fatal(err) } // Setup middleware middle := negroni.Classic() middle.Use(gzip.Gzip(gzip.DefaultCompression)) store := cookiestore.New([]byte("keyboard cat")) middle.Use(sessions.Sessions("tvtio", store)) // Setup router router := httprouter.New() router.GET("/", routes.Index) router.GET("/search", routes.Search) router.GET("/movie/:id", routes.Movie) router.GET("/tv/:id", routes.TV) router.GET("/person/:id", routes.Person) router.GET("/about", routes.About) router.GET("/login", routes.Login) router.GET("/logout", routes.Logout) router.GET("/auth/twitter", routes.AuthTwitter) router.GET("/auth/facebook", routes.AuthFacebook) router.GET("/auth/facebook/callback", routes.AuthFacebookCallback) router.ServeFiles("/css/*filepath", http.Dir(configuration.Templates+"/css")) router.ServeFiles("/js/*filepath", http.Dir(configuration.Templates+"/js")) router.ServeFiles("/img/*filepath", http.Dir(configuration.Templates+"/img")) middle.UseHandler(router) // Start server fmt.Println("Listening at " + configuration.ServerURL()) log.Fatal(http.ListenAndServe(configuration.ServerAddress(), middle)) }
func Test_Logout(t *testing.T) { recorder := httptest.NewRecorder() s := cookiestore.New([]byte("secret123")) n := negroni.Classic() n.Use(sessions.Sessions("my_session", s)) n.Use(Google(&Config{ ClientID: "foo", ClientSecret: "foo", RedirectURL: "foo", })) mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { SetToken(req, "dummy token") fmt.Fprintf(w, "OK") }) mux.HandleFunc("/get", func(w http.ResponseWriter, req *http.Request) { tok := GetToken(req) if tok != nil { t.Errorf("User credentials are still kept in the session.") } fmt.Fprintf(w, "OK") }) n.UseHandler(mux) logout, _ := http.NewRequest("GET", "/logout", nil) index, _ := http.NewRequest("GET", "/", nil) n.ServeHTTP(httptest.NewRecorder(), index) n.ServeHTTP(recorder, logout) if recorder.Code != 302 { t.Errorf("Not being redirected to the next page.") } }
func main() { db := database.NewDB() defer db.Close() go riskzone.Execute(db) orm.Init() defer orm.Close() go geocode.Parallel(orm.Get()) gob.Register(models.User{}) gob.Register(models.Address{}) middleware := negroni.Classic() middleware.Use(negroni.NewStatic(http.Dir("templates"))) middleware.Use(sessions.Sessions("dne", cookiestore.New([]byte(uuid.NewV4().String())))) middleware.UseFunc(Authenticate) middleware.UseHandler(routers.GetControllers()) middleware.Run(":8081") }
func Test_LoginRedirect(t *testing.T) { recorder := httptest.NewRecorder() n := negroni.New() n.Use(sessions.Sessions("my_session", cookiestore.New([]byte("secret123")))) n.Use(Google(&Config{ ClientID: "client_id", ClientSecret: "client_secret", RedirectURL: "refresh_url", Scopes: []string{"x", "y"}, })) r, _ := http.NewRequest("GET", "/login", nil) n.ServeHTTP(recorder, r) location := recorder.HeaderMap["Location"][0] if recorder.Code != 302 { t.Errorf("Not being redirected to the auth page.") } t.Logf(location) if strings.HasPrefix("https://accounts.google.com/o/oauth2/auth?access_type=online&approval_prompt=auto&client_id=client_id&redirect_uri=refresh_url&response_type=code&scope=x+y&state=", location) { t.Errorf("Not being redirected to the right page, %v found", location) } }