Exemple #1
0
func Test_LoginRedirectAfterLoginRequired(t *testing.T) {
	recorder := httptest.NewRecorder()
	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(Google(&Options{
		ClientId:     "client_id",
		ClientSecret: "client_secret",
		RedirectURL:  "refresh_url",
		Scopes:       []string{"x", "y"},
	}))

	m.Get("/login-required", LoginRequired, func(tokens Tokens) (int, string) {
		return 200, tokens.Access()
	})

	r, _ := http.NewRequest("GET", "/login-required?key=value", nil)
	m.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)
	}
}
Exemple #2
0
func Test_Validate(t *testing.T) {
	m := martini.Classic()
	store := sessions.NewCookieStore([]byte("secret123"))
	m.Use(sessions.Sessions("my_session", store))
	m.Use(Generate(&Options{
		Secret:     "token123",
		SessionKey: "userID",
	}))

	// Simulate login.
	m.Get("/login", func(s sessions.Session) string {
		s.Set("userID", "123456")
		return "OK"
	})

	// Generate token.
	m.Get("/private", func(s sessions.Session, x CSRF) string {
		return x.GetToken()
	})

	m.Post("/private", Validate, func(s sessions.Session) string {
		return "OK"
	})

	// Login to set session.
	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/login", nil)
	m.ServeHTTP(res, req)

	cookie := res.Header().Get("Set-Cookie")

	// Get a new token.
	res2 := httptest.NewRecorder()
	req2, _ := http.NewRequest("GET", "/private", nil)
	req2.Header.Set("Cookie", cookie)
	m.ServeHTTP(res2, req2)

	// Post using _csrf form value.
	data := url.Values{}
	data.Set("_csrf", res2.Body.String())
	res3 := httptest.NewRecorder()
	req3, _ := http.NewRequest("POST", "/private", bytes.NewBufferString(data.Encode()))
	req3.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req3.Header.Set("Content-Length", strconv.Itoa(len(data.Encode())))
	req3.Header.Set("Cookie", cookie)
	m.ServeHTTP(res3, req3)
	if res3.Code == 400 {
		t.Error("Validation of _csrf form value failed")
	}

	// Post using X-CSRFToken HTTP header.
	res4 := httptest.NewRecorder()
	req4, _ := http.NewRequest("POST", "/private", nil)
	req4.Header.Set("X-CSRFToken", res2.Body.String())
	req4.Header.Set("Cookie", cookie)
	m.ServeHTTP(res4, req4)
	if res4.Code == 400 {
		t.Error("Validation of X-CSRFToken failed")
	}
}
Exemple #3
0
func Test_BasicAuth(t *testing.T) {
	res := httptest.NewRecorder()
	auth := "Basic " + base64.StdEncoding.EncodeToString([]byte("gopher:golf"))
	m := martini.Classic()
	m.Get("/protected", AuthBasic(), func(w http.ResponseWriter, req *http.Request, b *Basic) {
		fmt.Fprintf(w, "hi %s %s", b.Username, b.Password)
	})
	r, _ := http.NewRequest("GET", "/protected", nil)
	m.ServeHTTP(res, r)
	if res.Code != 401 {
		t.Error("Response not 401")
	}
	if strings.Contains(res.Body.String(), "hi") {
		t.Error("Auth block failed")
	}
	res = httptest.NewRecorder()
	r.Header.Set("Authorization", auth)
	m.ServeHTTP(res, r)
	if res.Code == 401 {
		t.Error("Response is 401")
	}
	if res.Body.String() != "hi gopher golf" {
		t.Error("Auth failed, got: ", res.Body.String())
	}
}
func TestBind(t *testing.T) {
	index := 0
	for test, expectStatus := range bindTests {
		recorder := httptest.NewRecorder()
		handler := func(post BlogPost, errors Errors) { handle(test, t, index, post, errors) }

		m := martini.Classic()
		switch test.method {
		case "GET":
			m.Get(route, Bind(BlogPost{}), handler)
		case "POST":
			m.Post(route, Bind(BlogPost{}), handler)
		}

		req, err := http.NewRequest(test.method, test.path, strings.NewReader(test.payload))
		req.Header.Add("Content-Type", test.contentType)

		if err != nil {
			t.Error(err)
		}
		m.ServeHTTP(recorder, req)

		if recorder.Code != expectStatus {
			t.Errorf("On test case %v, got status code %d but expected %d", test, recorder.Code, expectStatus)
		}

		index++
	}
}
Exemple #5
0
func main() {
	m := martini.Classic()
	m.Get("/", func() string {
		return "Hello World"
	})
	m.Run()
}
func testForm(t *testing.T, withInterface bool) {
	for index, test := range formTests {
		recorder := httptest.NewRecorder()
		handler := func(post BlogPost, errors Errors) { handle(test, t, index, post, errors) }
		binding := Form(BlogPost{})

		if withInterface {
			handler = func(post BlogPost, errors Errors) {
				post.Create(test, t, index)
			}
			binding = Form(BlogPost{}, (*Modeler)(nil))
		}

		m := martini.Classic()
		switch test.method {
		case "GET":
			m.Get(route, binding, handler)
		case "POST":
			m.Post(route, binding, handler)
		}

		req, err := http.NewRequest(test.method, test.path, nil)
		if err != nil {
			t.Error(err)
		}
		m.ServeHTTP(recorder, req)
	}
}
Exemple #7
0
func main() {
	//	fmt.Println("Hello World!")
	rand.Seed(time.Now().UTC().UnixNano())
	/*	database := models.GetDB()
		database.Drop(tiedotmartini2.BAND_COL)
		database.Drop(tiedotmartini2.LOCATION_COL)
		database.Drop(tiedotmartini2.GENRE_COL)
		database.Create(tiedotmartini2.BAND_COL, 1)
		database.Create(tiedotmartini2.LOCATION_COL, 1)
		database.Create(tiedotmartini2.GENRE_COL, 1)
		col := database.Use(tiedotmartini2.BAND_COL)
		col.Index([]string{"albums", "genre_id"})
		database.Close()
	*/
	m := martini.Classic()
	m.Get("/", controllers.HomeIndex)
	m.Get("/home/index", controllers.HomeIndex)
	m.Get("/band/add", controllers.BandAdd)
	m.Post("/band/verify", controllers.BandVerify)
	m.Get("/album/index/:id", controllers.AlbumIndex)
	m.Get("/album/add/:id", controllers.AlbumAdd)
	m.Post("/album/verify/:id", controllers.AlbumVerify)
	m.Get("/home/genrelist", controllers.HomeGenreList)
	m.Get("/home/bygenre/:id", controllers.HomeByGenre)
	m.Use(martini.Static("assets"))
	m.Run()
}
Exemple #8
0
func init() {
	m := martini.Classic()

	m.Group("/api/stories", func(r martini.Router) {
		r.Get("/", GetStories)
		r.Get("/:key", GetStories)
		r.Post("/new", NewStory)
		r.Put("/update/:id", UpdateStory)
		r.Delete("/delete/:id", DeleteStory)
	})

	m.Group("/api/tasks", func(r martini.Router) {
		r.Get("/", GetTasks)
		r.Get("/:key", GetTasks)
		r.Post("/new", NewTask)
		r.Put("/update/:key", UpdateTask)
		r.Delete("/delete/:key", DeleteTask)
	})

	// add test-datas
	m.Group("/testdatas", func(r martini.Router) {
		r.Get("/story", AddTestDatasForStory)
		//r.Get("/task", xxx)
	})

	http.Handle("/", m)
}
Exemple #9
0
func testEmptyJson(t *testing.T) {
	for index, test := range emptyPayloadTests {
		recorder := httptest.NewRecorder()
		handler := func(section BlogSection, errors Errors) { handleEmpty(test, t, index, section, errors) }
		binding := Json(BlogSection{})

		m := martini.Classic()
		switch test.method {
		case "GET":
			m.Get(route, binding, handler)
		case "POST":
			m.Post(route, binding, handler)
		case "PUT":
			m.Put(route, binding, handler)
		case "DELETE":
			m.Delete(route, binding, handler)
		}

		req, err := http.NewRequest(test.method, route, strings.NewReader(test.payload))
		if err != nil {
			t.Error(err)
		}
		m.ServeHTTP(recorder, req)
	}
}
Exemple #10
0
func Test_Render_NoRace(t *testing.T) {
	// This test used to fail if run with -race
	m := martini.Classic()
	m.Use(Renderer(Options{
		Directory: "fixtures/basic",
	}))

	// routing
	m.Get("/foobar", func(r Render) {
		r.HTML(200, "hello", "world")
	})

	done := make(chan bool)
	doreq := func() {
		res := httptest.NewRecorder()
		req, _ := http.NewRequest("GET", "/foobar", nil)

		m.ServeHTTP(res, req)

		expect(t, res.Code, 200)
		expect(t, res.Header().Get(ContentType), ContentHTML+"; charset=UTF-8")
		// ContentLength should be deferred to the ResponseWriter and not Render
		expect(t, res.Header().Get(ContentLength), "")
		expect(t, res.Body.String(), "<h1>Hello world</h1>\n")
		done <- true
	}
	// Run two requests to check there is no race condition
	go doreq()
	go doreq()
	<-done
	<-done
}
Exemple #11
0
func main() {

	autoUpdate()

	m := martini.Classic()
	m.Use(martini.Static("static"))
	m.Use(render.Renderer())

	m.Get("/", func(r render.Render) {
		r.HTML(200, "content", []interface{}{getPage(1)})
	})

	m.Get("/api/:id", func(params martini.Params, r render.Render) {
		s := strings.Trim(params["id"], " .)(")
		id := atoi(s)
		r.JSON(200, getPage(id))
	})

	m.Get("/page/:id", func(params martini.Params, r render.Render) {
		s := strings.Trim(params["id"], " .)(")
		id := atoi(s)
		r.HTML(200, "content", []interface{}{getPage(id)})
	})

	http.ListenAndServe("0.0.0.0:8000", m)
	m.Run()
}
Exemple #12
0
func main() {

	m := martini.Classic()
	// specify the layout to use when rendering HTML
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))
	// use the Mongo middleware
	m.Use(DB())

	// list of all cribs
	m.Get("/", func(r render.Render, db *mgo.Database) {
		r.HTML(200, "list", All(db))
	})

	/*
	   create a new crib the form submission. Contains some martini magic. The call
	   to binding.Form(Crib{}) parses out form data when the request comes in.
	   It binds the data to the struct, maps it to the request context  and
	   injects into our next handler function to insert into Mongodb.
	*/
	m.Post("/", binding.Form(Crib{}), func(crib Crib, r render.Render, db *mgo.Database) {
		db.C("cribs").Insert(crib)
		r.HTML(200, "list", All(db))
	})

	// display the crib for a specific user
	m.Get("/:handle", func(params martini.Params, r render.Render, db *mgo.Database) {
		r.HTML(200, "display", Fetch(db, params["handle"]))
	})

	http.ListenAndServe(":8080", m)

}
Exemple #13
0
func main() {
	m := martini.Classic()
	if os.Getenv("MARTINI_ENV") == "production" {
		g.devMode = false
	}

	if g.IsDevMode() {
		m.Use(runnerMiddleware)
	}
	g.InitDb()

	m.Use(martini.Static("public/app"))
	m.Use(func(resp http.ResponseWriter, req *http.Request) {
		if strings.HasPrefix(req.URL.Path, "/api/") {
			token := req.Header.Get("AuthToken")
			if token != "" {
				n, err := g.Db().SelectInt(`select count(*) from users where token=$1`, token)
				if err != nil && err != sql.ErrNoRows {
					log.Fatalf(err.Error())
				}
				if n > 0 {
					return
				}
			}

			resp.WriteHeader(http.StatusUnauthorized)
			resp.Write([]byte("You're not allowed to do this, sorry."))
		}
	})

	m.Get("/", func(r http.ResponseWriter) {
		t, err := template.ParseFiles("public/app/index.html")
		if err != nil {
			panic(err.Error())
		}
		t.Execute(r, nil)
	})

	m.Get("/auth", func(r http.ResponseWriter) {
		username, token := makeRandomUserToken()
		user := &biz.User{
			Username: username,
			Token:    token,
			Role:     biz.RoleUser,
		}
		checkErr(g.Db().Insert(user))
		resp, err := json.Marshal(map[string]interface{}{
			"username": user.Username,
			"token":    user.Token,
		})
		checkErr(err)
		r.Write(resp)
	})

	m.Get("/api/test", func(r http.ResponseWriter) {
		r.Write([]byte("CLGT"))
	})

	m.Run()
}
Exemple #14
0
func Test_Logout(t *testing.T) {
	recorder := httptest.NewRecorder()
	s := sessions.NewCookieStore([]byte("secret123"))

	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", s))
	m.Use(Google(&Options{
	// no need to configure
	}))

	m.Get("/", func(s sessions.Session) {
		s.Set(keyToken, "dummy token")
	})

	m.Get("/get", func(s sessions.Session) {
		if s.Get(keyToken) != nil {
			t.Errorf("User credentials are still kept in the session.")
		}
	})

	logout, _ := http.NewRequest("GET", "/logout", nil)
	index, _ := http.NewRequest("GET", "/", nil)

	m.ServeHTTP(httptest.NewRecorder(), index)
	m.ServeHTTP(recorder, logout)

	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the next page.")
	}
}
Exemple #15
0
func main() {
	m := martini.Classic()

	m.Get("/", func(res http.ResponseWriter, req *http.Request) {
		res.Header().Set("Content-Type", "image/jpeg")
		err := jpeg.Encode(res, thumb(), &jpeg.Options{75})
		if err != nil {
			res.WriteHeader(500)
		} else {
			res.WriteHeader(200)
		}
	})

	m.Get("/cached", func(response http.ResponseWriter, req *http.Request) {
		response.Header().Set("Content-Type", "image/jpeg")
		err := jpeg.Encode(response, preThumb(), &jpeg.Options{75})
		if err != nil {
			response.WriteHeader(500)
		} else {
			response.WriteHeader(200)
		}
	})

	log.Fatal(http.ListenAndServe(":10010", m))
	m.Run()
}
Exemple #16
0
func TestMultipartMultipleFileForm(t *testing.T) {
	for testIdx, tc := range multifileTests {
		req := buildFormFileReq(t, &tc)
		recorder := httptest.NewRecorder()
		handler := func(fup MultipleFileUpload, errors Errors) {
			// expecting everything to succeed
			if errors.Count() > 0 {
				t.Errorf("Expected no errors, got: %v", errors)
			}

			assertEqualField(t, "Title", testIdx, tc.title, fup.Title)
			if len(tc.documents) != len(fup.Document) {
				t.Errorf("Expected %d documents, got: %v", len(tc.documents), fup.Document)
			}

			for i, tcDocument := range tc.documents {
				if (fup.Document[i] == nil) != tcDocument.isNil {
					t.Errorf("Expected document.isNil: %v, got %v", tcDocument.isNil, fup.Document[i])
				}

				if fup.Document[i] != nil {
					assertEqualField(t, "Filename", testIdx, tcDocument.fileName, fup.Document[i].Filename)
					uploadData := unpackFileHeaderData(fup.Document[i], t)
					assertEqualField(t, "Document Data", testIdx, tcDocument.data, uploadData)
				}
			}
		}
		m := martini.Classic()
		m.Post(fileroute, MultipartForm(MultipleFileUpload{}), handler)
		m.ServeHTTP(recorder, req)
	}
}
func testJson(t *testing.T, withInterface bool) {
	for index, test := range jsonTests {
		recorder := httptest.NewRecorder()
		handler := func(post BlogPost, errors Errors) { handle(test, t, index, post, errors) }
		binding := Json(BlogPost{})

		if withInterface {
			handler = func(post BlogPost, errors Errors) {
				post.Create(test, t, index)
			}
			binding = Bind(BlogPost{}, (*Modeler)(nil))
		}

		m := martini.Classic()
		switch test.method {
		case "GET":
			m.Get(route, binding, handler)
		case "POST":
			m.Post(route, binding, handler)
		case "PUT":
			m.Put(route, binding, handler)
		case "DELETE":
			m.Delete(route, binding, handler)
		}

		req, err := http.NewRequest(test.method, route, strings.NewReader(test.payload))
		if err != nil {
			t.Error(err)
		}
		m.ServeHTTP(recorder, req)
	}
}
Exemple #18
0
func main() {
	m := martini.Classic()
	m.Get("/", func() string {
		return "YOLO"
	})
	m.Run()
}
func testMultipart(t *testing.T, test testCase, middleware martini.Handler, handler martini.Handler, index int) *httptest.ResponseRecorder {
	recorder := httptest.NewRecorder()

	m := martini.Classic()
	m.Post(route, middleware, handler)

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	writer.WriteField("title", test.ref.Title)
	writer.WriteField("content", test.ref.Content)
	writer.WriteField("views", strconv.Itoa(test.ref.Views))
	if len(test.ref.Multiple) != 0 {
		for _, value := range test.ref.Multiple {
			writer.WriteField("multiple", strconv.Itoa(value))
		}
	}

	req, err := http.NewRequest(test.method, test.path, body)
	req.Header.Add("Content-Type", writer.FormDataContentType())

	if err != nil {
		t.Error(err)
	}

	err = writer.Close()
	if err != nil {
		t.Error(err)
	}

	m.ServeHTTP(recorder, req)

	return recorder
}
Exemple #20
0
func main() {
	fs, err := filestore.New("s3")
	if err != nil {
		log.Fatal(err)
	}

	port := os.Getenv("PORT")
	m := martini.Classic()
	m.Map(fs)
	m.Use(martini.Static("../web/public"))
	m.Use(render.Renderer(render.Options{
		Directory: "../web/templates",
		Layout:    "layout",
	}))
	m.Get("/", func(fs *filestore.S3, r render.Render) {
		files, err := fs.List("builds")
		sort.Sort(ByTime(files))
		if err != nil {
			log.Fatal(err)
		}

		r.HTML(200, "home", files)
	})

	log.Printf("starting server at %s", port)
	err = http.ListenAndServe(":"+port, m)
	if err != nil {
		log.Fatal(err)
	}
}
Exemple #21
0
func Test_Render_Funcs(t *testing.T) {

	m := martini.Classic()
	m.Use(Renderer(Options{
		Directory: "fixtures/custom_funcs",
		Funcs: []template.FuncMap{
			{
				"myCustomFunc": func() string {
					return "My custom function"
				},
			},
		},
	}))

	// routing
	m.Get("/foobar", func(r Render) {
		r.HTML(200, "index", "jeremy")
	})

	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/foobar", nil)

	m.ServeHTTP(res, req)

	expect(t, res.Body.String(), "My custom function\n")
}
func Test_Sessions(t *testing.T) {
	m := martini.Classic()

	store := NewCookieStore([]byte("secret123"))
	m.Use(Sessions("my_session", store))

	m.Get("/testsession", func(session Session) string {
		session.Set("hello", "world")
		return "OK"
	})

	m.Get("/show", func(session Session) string {
		if session.Get("hello") != "world" {
			t.Error("Session writing failed")
		}
		return "OK"
	})

	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/testsession", nil)
	m.ServeHTTP(res, req)

	res2 := httptest.NewRecorder()
	req2, _ := http.NewRequest("GET", "/show", nil)
	req2.Header.Set("Cookie", res.Header().Get("Set-Cookie"))
	m.ServeHTTP(res2, req2)
}
Exemple #23
0
func init() {
	m := martini.Classic()

	//Todo Example
	m.Get("/todo/list", todoListHandler)
	m.Post("/todo/list", todoListHandler)
	m.Get("/todo/edit/:ID", todoEditHandler)
	m.Post("/todo/edit/:ID", todoEditHandler)
	m.Post("/todo/edit", todoEditPostHandler)
	m.Get("/todo/delete/:ID", todoDeleteHandler)
	m.Post("/todo/delete", todoDeletePostHandler)
	m.Get("/todo/create", todoCreateHandler)
	m.Post("/todo/create", todoCreatePostHandler)
	m.Get("/todo/:parentID", todoViewHandler)
	m.Post("/todo/:parentID", todoViewHandler)

	m.Get("/todo/:parentID/edit/:ID", subtaskEditHandler)
	m.Post("/subtask/edit", subtaskEditPostHandler)
	m.Get("/todo/:parentID/delete/:ID", subtaskDeleteHandler)
	m.Post("/subtask/delete", subtaskDeletePostHandler)
	m.Get("/todo/:parentID/createSubtask", subtaskCreateHandler)
	m.Post("/subtask/create", subtaskCreatePostHandler)
	// Handle this all
	http.Handle("/", m)
}
func main() {
	doProfile := flag.Bool("profile", false, "profile app")
	flag.Parse()
	go cpu.Monitor()
	go net.Monitor("eth0")

	r := martini.Classic()

	r.Get("/containers/:id/mem", containerMemUsageHandler)
	r.Get("/containers/:id/cpu", containerCpuUsageHandler)
	r.Get("/containers/:id/net", containerNetUsageHandler)

	if *doProfile {
		log.Println("Enable profiling")
		r.Get("/debug/pprof", pprof.Index)
		r.Get("/debug/pprof/cmdline", pprof.Cmdline)
		r.Get("/debug/pprof/profile", pprof.Profile)
		r.Get("/debug/pprof/symbol", pprof.Symbol)
		r.Post("/debug/pprof/symbol", pprof.Symbol)
		r.Get("/debug/pprof/block", pprof.Handler("block").ServeHTTP)
		r.Get("/debug/pprof/heap", pprof.Handler("heap").ServeHTTP)
		r.Get("/debug/pprof/goroutine", pprof.Handler("goroutine").ServeHTTP)
		r.Get("/debug/pprof/threadcreate", pprof.Handler("threadcreate").ServeHTTP)
	}
	r.Run()
}
Exemple #25
0
func Test_GenerateCustomHeader(t *testing.T) {
	m := martini.Classic()
	store := sessions.NewCookieStore([]byte("secret123"))
	m.Use(sessions.Sessions("my_session", store))
	m.Use(Generate(&Options{
		Secret:     "token123",
		SessionKey: "userID",
		SetHeader:  true,
		Header:     "X-SEESurfToken",
	}))

	// Simulate login.
	m.Get("/login", func(s sessions.Session) string {
		s.Set("userID", "123456")
		return "OK"
	})

	// Generate HTTP header.
	m.Get("/private", func(s sessions.Session, x CSRF) string {
		return "OK"
	})

	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/login", nil)
	m.ServeHTTP(res, req)

	res2 := httptest.NewRecorder()
	req2, _ := http.NewRequest("GET", "/private", nil)
	req2.Header.Set("Cookie", res.Header().Get("Set-Cookie"))
	m.ServeHTTP(res2, req2)

	if res2.Header().Get("X-SEESurfToken") == "" {
		t.Error("Failed to set X-SEESurfToken custom header")
	}
}
Exemple #26
0
func main() {
	m := martini.Classic()
	m.Use(render.Renderer(render.Options{
		Directory: "templates",
		Charset:   "utf-8",
	}))

	m.NotFound(func(r render.Render) {
		r.Redirect("/")
	})

	m.Get("/", IndexRender)

	m.Get("/feed", FeedRender)

	m.Get("/hello", func(r render.Render) {
		//r.HTML(200, "hello", "World")
		r.HTML(200, Greet("Golang"), "World")
	})

	m.Get("/api", func(r render.Render) {
		r.JSON(200, map[string]interface{}{"hello": "world"})
	})

	m.Run()
}
Exemple #27
0
func Test_GenerateCustomCookie(t *testing.T) {
	m := martini.Classic()
	store := sessions.NewCookieStore([]byte("secret123"))
	m.Use(sessions.Sessions("my_session", store))
	m.Use(Generate(&Options{
		Secret:     "token123",
		SessionKey: "userID",
		SetCookie:  true,
		Cookie:     "seesurf",
	}))

	// Simulate login.
	m.Get("/login", func(s sessions.Session) string {
		s.Set("userID", "123456")
		return "OK"
	})

	// Generate cookie.
	m.Get("/private", func(s sessions.Session, x CSRF) string {
		return "OK"
	})

	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/login", nil)
	m.ServeHTTP(res, req)

	res2 := httptest.NewRecorder()
	req2, _ := http.NewRequest("GET", "/private", nil)
	req2.Header.Set("Cookie", res.Header().Get("Set-Cookie"))
	m.ServeHTTP(res2, req2)

	if !strings.Contains(res2.Header().Get("Set-Cookie"), "seesurf") {
		t.Error("Failed to set custom csrf cookie")
	}
}
Exemple #28
0
func main() {
	m := martini.Classic()
	m.Map(SetupDB())
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))
	m.Use(martini.Static("assets"))

	m.Get("/", func(ren render.Render, r *http.Request, db *sql.DB) {
		rows, err := db.Query("SELECT * from videos")
		PanicIf(err)
		defer rows.Close()

		videos := []Video{}
		for rows.Next() {
			v := Video{}
			err := rows.Scan(&v.Id, &v.Title)
			PanicIf(err)
			videos = append(videos, v)
			// fmt.Fprintf(rw, "Title: %s", title)
		}

		ren.HTML(200, "videos", videos)
	})

	m.Run()
}
Exemple #29
0
func InitServer() *martini.ClassicMartini {
	envFileName := martini.Env + ".env"
	err := godotenv.Load(envFileName)
	if err != nil {
		log.Fatalf("Error loading: %s", envFileName)
	}

	m := martini.Classic()
	m.Map(db.Connect())

	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))

	m.Get("/", func(r render.Render) {
		r.HTML(200, "home", "")
	})
	m.Get("/api/projects", controllers.ProjectIndex)
	m.Get("/api/projects/new", controllers.ProjectNew)
	m.Get("/api/projects/:id", controllers.ProjectGet)
	m.Post("/api/projects", binding.Bind(models.Project{}), controllers.ProjectCreate)
	m.Put("/api/projects/:id", binding.Bind(models.Project{}), controllers.ProjectUpdate)
	m.Delete("/api/projects/:id", controllers.ProjectDelete)

	return m
}
Exemple #30
0
func Test_LogoutOnAccessTokenExpiration(t *testing.T) {
	recorder := httptest.NewRecorder()
	s := sessions.NewCookieStore([]byte("secret123"))

	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", s))
	m.Use(Google(&Options{
	// no need to configure
	}))

	m.Get("/addtoken", func(s sessions.Session) {
		s.Set(keyToken, "dummy token")
	})

	m.Get("/", func(s sessions.Session) {
		if s.Get(keyToken) != nil {
			t.Errorf("User not logged out although access token is expired.")
		}
	})

	addtoken, _ := http.NewRequest("GET", "/addtoken", nil)
	index, _ := http.NewRequest("GET", "/", nil)
	m.ServeHTTP(recorder, addtoken)
	m.ServeHTTP(recorder, index)
}