Exemple #1
0
func main() {
	ga.AdminPort = 8000
	ga.MysqlDsn = "root:scjh1234@tcp(192.168.1.15:3306)/galaxy2"
	ga.TemplatePath = "/Users/sunlei/go/src/galaxy/templates"
	ga.DbName = "default"
	go ga.Run()
	m := martini.Classic()
	store := sessions.NewCookieStore([]byte("secret123"))
	m.Use(render.Renderer(render.Options{
		Directory:  "/Users/sunlei/go/src/github.com/go-galaxy/galaxy/example/template", // Specify what path to load the templates from.
		Extensions: []string{".tmpl", ".html"},                                          // Specify extensions to load for templates.
		Layout:     "",
	}))
	m.Use(sessions.Sessions("my_session", store))
	m.Use(func(res http.ResponseWriter, req *http.Request, session sessions.Session) {
		if strings.Contains(req.URL.String(), "login") {
			return
		}
		v := session.Get("login")
		if v == nil {
			http.Redirect(res, req, "login", http.StatusFound)
		}
	})
	m.Use(sessions.Sessions("my_session", store))
	m.Get("/login", Login)
	m.Get("/", Index)
	m.Post("/login", Login)
	m.Get("/logout", LogOut)
	m.Get("/test", Test)
	m.RunOnAddr(":3000")
}
Exemple #2
0
//InitSession - initializes authentication middleware for controllers
func InitSession(m *martini.ClassicMartini, rc redisCreds) {
	m.Use(render.Renderer())

	if rediStore, err := sessions.NewRediStore(10, "tcp", rc.Uri(), rc.Pass(), []byte(sessionSecret)); err == nil {
		m.Use(sessions.Sessions(sessionName, rediStore))
	}
}
Exemple #3
0
func main() {
	m := martini.Classic()
	m.Map(SetupDB())
	m.Use(martini.Logger())
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))

	store := sessions.NewCookieStore([]byte(CookieSecret))
	m.Use(sessions.Sessions("bunkaisession", store))
	log.Println("env is", martini.Env)
	m.Map(martini.Env)

	m.Group("/", func(m martini.Router) {
		m.Get("", Home)
	}, AssetMap)

	m.Group("/api", func(m martini.Router) {
		m.Post("/login", PostLogin)
		m.Post("/users", UserCreate)

		m.Group("/sentences", func(m martini.Router) {
			m.Post("", SentenceCreate)
			m.Get("", SentenceList)
			m.Delete("/:id", SentenceDelete)
		}, RequireLogin)

		m.Group("/users", func(m martini.Router) {
			m.Post("/logout", Logout)
			m.Get("/me", UserGet)
		}, RequireLogin)
	})

	m.Run()
}
Exemple #4
0
func main() {
	m := martini.Classic()
	dbMap := initDb()
	m.Map(dbMap)
	store := sessions.NewCookieStore([]byte("nonotestetstsst"))
	m.Use(sessions.Sessions("gogonki", store))
	m.Use(render.Renderer())
	m.Get("/", Index)

	m.Get("/coords", Coords)
	m.Get("/move/:x/:y", Move) // ToDo: make this post request
	m.Get("/state", GetState)
	m.Get("/profile", ShowProfile)
	m.Get("/login", LoginForm)
	m.Post("/login", Login)
	m.Get("/logout", Logout)
	m.Post("/create", binding.Bind(User{}), CreateUser)
	m.Get("/signup", SignupForm)
	m.Post("/signup", Signup)
	m.Post("/create-room", CreateRoom)
	m.Post("/list-rooms", ListRooms)

	//m.Use(Auth)
	m.Run()
}
Exemple #5
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)
}
Exemple #6
0
func main() {
	m := martini.Classic()

	store := sessions.NewCookieStore([]byte("secret-isucon"))
	m.Use(sessions.Sessions("isucon_go_session", store))

	m.Use(martini.Static("../public"))
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))

	m.Get("/", func(r render.Render, session sessions.Session) {
		r.HTML(200, "index", map[string]string{"Flash": getFlash(session, "notice")})
	})

	m.Post("/login", func(req *http.Request, r render.Render, session sessions.Session) {
		user, err := attemptLogin(req)

		notice := ""
		if err != nil || user == nil {
			switch err {
			case ErrBannedIP:
				notice = "You're banned."
			case ErrLockedUser:
				notice = "This account is locked."
			default:
				notice = "Wrong username or password"
			}

			session.Set("notice", notice)
			r.Redirect("/")
			return
		}

		session.Set("user_id", strconv.Itoa(user.ID))
		r.Redirect("/mypage")
	})

	m.Get("/mypage", func(r render.Render, session sessions.Session) {
		currentUser := getCurrentUser(session.Get("user_id"))

		if currentUser == nil {
			session.Set("notice", "You must be logged in")
			r.Redirect("/")
			return
		}

		currentUser.getLastLogin()
		r.HTML(200, "mypage", currentUser)
	})

	m.Get("/report", func(r render.Render) {
		r.JSON(200, map[string][]string{
			"banned_ips":   bannedIPs(),
			"locked_users": lockedUsers(),
		})
	})

	http.ListenAndServe(":8080", m)
}
Exemple #7
0
func main() {
	m := martini.Classic()
	conf := config.LoadConf(martini.Env)
	//create new session middleware
	store := sessions.NewCookieStore([]byte("MushareSecret"))
	store.Options(sessions.Options{
		Path:     "/",
		Domain:   conf.App.Host,
		MaxAge:   60 * 60 * 60 * 24,
		HttpOnly: true,
	})

	//middleware
	m.Handlers(
		middlewares.LogOutput,
		middlewares.Recovery(),
		martini.Logger(),
		sessions.Sessions("_session", store),
		martini.Static("static", martini.StaticOptions{}),
		middlewares.InjectRedis(),
		middlewares.InjectDB(),
	)
	m.Map(conf)

	//routers
	router.Include(m)
	//start server
	m.RunOnAddr(conf.App.Host + ":" + conf.App.Port)
}
func adminserver() {
	m := martini.Classic()
	// m.Use(martini.Static("./assets/"))

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

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

	/***********static*************/
	m.Get("/css/**", http.FileServer(http.Dir("./assets")).ServeHTTP)
	m.Get("/editor/**", http.FileServer(http.Dir("./assets")).ServeHTTP)
	m.Get("/fonts/**", http.FileServer(http.Dir("./assets")).ServeHTTP)
	m.Get("/img/**", http.FileServer(http.Dir("./assets")).ServeHTTP)
	m.Get("/js/**", http.FileServer(http.Dir("./assets")).ServeHTTP)

	/***********biz*************/
	m.Get("/", admin.ArchivesHandler)
	m.Get("/archives", admin.ArchivesHandler)

	m.Post("/login", admin.LoginHandler)
	m.Get("/logout", admin.LogoutHandler)
	m.Get("/login", admin.GoLoginHandler)
	m.Get("/login/:path", admin.GoLoginHandler)

	http.ListenAndServe(fmt.Sprintf(":%s", base.AdminWebPort), m)
}
Exemple #9
0
func NewApi(address string, rdb *db.Rethinkdb, auth auth.Authenticator, sessionKey string) (*dialogueApi, error) {
	m := martini.Classic()
	// sessions
	store := sessions.NewCookieStore([]byte(sessionKey))
	m.Use(sessions.Sessions("dialogue", store))

	a := &dialogueApi{
		m:       m,
		rdb:     rdb,
		auth:    auth,
		address: address,
	}
	// middleware
	m.Use(render.Renderer())
	// routes
	// content
	m.Get("/topics", a.apiAuthorize, a.GetTopics)
	m.Post("/topics", a.apiAuthorize, a.PostTopics)
	m.Post("/topics/:topicId", a.apiAuthorize, a.PostTopicsPosts)
	m.Get("/topics/:topicId", a.apiAuthorize, a.GetTopic)
	m.Delete("/topics/:topicId", a.apiAuthorize, a.DeleteTopic)
	m.Delete("/posts/:postId", a.apiAuthorize, a.DeletePost)

	// authentication
	m.Post("/auth", a.Authenticate)
	m.Post("/users", a.apiAuthorize, a.PostUsers)
	m.Put("/users/:username", a.apiAuthorize, a.PutUser)
	// setup
	m.Get("/setup", a.Setup)

	return a, nil
}
Exemple #10
0
func main() {
	m := martini.Classic()

	// set up the session, and map it into martini
	store := sessions.NewCookieStore([]byte("secret-pass"))
	m.Use(sessions.Sessions("go-webapp", store))

	//on login, we will set the users username in the session
	m.Post("/login", func(w http.ResponseWriter, r *http.Request, session sessions.Session) string {
		username := r.FormValue("username")
		session.Set("username", username)
		http.Redirect(w, r, "/home", http.StatusFound)
		return "OK"
	})

	//if the user has no username, we will redirect them to the login page
	m.Get("/home", authorize, func(user *User) string {
		return "Welcome back, " + user.Username
	})

	//on logout, clear the username in the session
	m.Get("/logout", func(w http.ResponseWriter, r *http.Request, session sessions.Session) string {
		session.Delete("username")
		http.Redirect(w, r, "/login", http.StatusFound)
		return "OK"
	})

	m.Run()
}
Exemple #11
0
func main() {
	m := martini.Classic()
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
		Funcs: []template.FuncMap{
			{
				"add": func(a, b int) int {
					return a + b
				},
			},
		},
	}))

	m.Use(sessions.Sessions("reader_session", nil))

	m.Get("/", controllers.HomeController)

	m.Get("/read/*", controllers.ReadController)

	fmt.Println("Listening on port 8989")
	err := http.ListenAndServe(":8989", m)
	if err != nil {
		fmt.Println(err)
	}
}
Exemple #12
0
func main() {

	m := martini.Classic()
	m.Use(martini_amber.Renderer(map[string]string{

	}))
	store := sessions.NewCookieStore([]byte("secret...."))
	m.Use(sessions.Sessions("msession",store))
	m.Get("/", func(r martini_amber.Render,request *http.Request,session sessions.Session) {
		log.Println(request.UserAgent())
		name := session.Get("name")
		if name==nil && request.FormValue("name")!=""{
			session.Set("name",request.FormValue("name"))
		}
		vars := map[string]interface{}{"cats": []string{"Home", "Product", "Contact","Live Showing"},"arts":arts,"name":name}
		r.Amber(200, "home", vars)
	})
	m.Get("/test", func(r martini_amber.Render,request *http.Request,session sessions.Session) {
		log.Println(request.UserAgent())
		name := session.Get("name")
		if name==nil && request.FormValue("name")!=""{
			session.Set("name",request.FormValue("name"))
		}
		vars := map[string]interface{}{"cats": []string{"Home", "Product", "Contact","Live Showing"},"arts":arts,"name":name}
		r.Amber(200, "test", vars)
	})

	m.RunOnAddr(":8080")
}
Exemple #13
0
func main() {
	cfg, err := os.Open("config.json")
	if err != nil {
		log.Fatal(err)
	}
	parser := json.NewDecoder(cfg)
	if err = parser.Decode(common.Config); err != nil {
		log.Fatal(err)
	}

	initDB()
	initQueue()
	initS3()

	m := martini.Classic()

	store := sessions.NewCookieStore([]byte(common.Config.SessionsSecret))
	m.Use(sessions.Sessions("semquery", store))

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

	routes.RegisterRoutes(m)

	if len(os.Args) > 1 {
		m.RunOnAddr(os.Args[1])
	} else {
		m.Run()
	}
}
Exemple #14
0
func main() {
	db := sqlx.MustConnect("postgres", "postgres://localhost:15432/auth_sh?sslmode=disable")
	defer db.Close()

	s := oauth.New(db)

	m := martini.Classic()
	m.Use(handlers.NoCache())
	m.Use(sessions.Sessions("auth-sh", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(render.Renderer(render.Options{Layout: "layout"}))
	m.Use(dump_request)
	m.Map(db)
	m.Map(s)

	m.Get("/login", handlers.GET_login)
	m.Get("/link", handlers.GET_link)
	m.Any("/authorize", handlers.GET_authorize)
	m.Any("/token", handlers.GET_token)
	m.Any("/info", handlers.GET_info)
	m.Get("/continue/:provider", handlers.GET_continue)
	m.Get("/logout", handlers.GET_logout)
	m.Get("/callback", handlers.GET_callback)

	m.Get("/", handlers.MayAuthenticate(), handlers.GET_home)
	m.Get("/me", handlers.MustAuthenticate(), handlers.GET_me)
	m.Get("/profile", handlers.MustAuthenticate(), handlers.GET_profile)
	m.Post("/applications", handlers.MustAuthenticate(), handlers.POST_application)

	m.Run()
}
Exemple #15
0
func main() {
	m := martini.Classic()
	m.Map(SetupDB())
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
		Funcs: []template.FuncMap{
			{
				"unescaped": func(args ...interface{}) template.HTML {
					return template.HTML(args[0].(string))
				},
			},
		},
	}))

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

	m.Get("/", IndexArticles)
	m.Get("/create", CreateArticle)
	m.Get("/read", ReadArticle)
	m.Get("/update", UpdateArticle)
	m.Get("/delete", DeleteArticle)
	m.Post("/save", SaveArticle)
	m.Get("/login", LoginForm)
	m.Post("/login", UserLogin)
	m.Get("/signup", SignupForm)
	m.Post("/signup", UserSignup)
	m.Get("/logout", UserLogout)
	m.Get("/wrong", WrongLogin)

	m.Run()
}
Exemple #16
0
func NewWeb(mailConf *conf.MailConf, debug bool) *MailWeb {
	var web *MailWeb = new(MailWeb)
	web.mconf = mailConf
	web.debug = debug
	web.userTimeout = 86400 // 1 day

	store := sessions.NewCookieStore(securecookie.GenerateRandomKey(128))
	// 1) Set a maximum age for the client-side cookies (forces a session timeout afterwards)
	store.Options(sessions.Options{MaxAge: int(web.userTimeout)})

	web.martini = martini.Classic()
	web.martini.Use(render.Renderer(render.Options{
		Directory:  "static/templates",
		Extensions: []string{".html"},
	}))
	web.martini.Use(sessions.Sessions("watneySession", store))
	web.martini.Use(sessionauth.SessionUser(auth.GenerateAnonymousUser))
	sessionauth.RedirectUrl = "/sessionTimeout"
	sessionauth.RedirectParam = "next"

	// 2) Register a cleanup go routine that checks every x minutes, for outdated users, which
	//	  simply left the page without logging out
	web.registerUserCleanup(30)

	// x) Define and set all handlers
	web.initHandlers()
	return web
}
Exemple #17
0
func StartWeb() {
	m := martini.Classic()

	store := sessions.NewCookieStore([]byte("mandela"))
	m.Use(sessions.Sessions("session", store))

	m.Use(render.Renderer(render.Options{
		Extensions: []string{".html"},
	}))
	m.Use(martini.Static("../../statics"))

	r := martini.NewRouter()

	r.Get("/", Home_handler)               //首页
	r.Get("/getdomain", GetDomain_handler) //获得本机的域名

	m.Action(r.Handle)

	webPort := 80
	for i := 0; i < 1000; i++ {
		_, err := net.ListenPacket("udp", ":"+strconv.Itoa(webPort))
		if err != nil {
			webPort = webPort + 1
		} else {
			break
		}
	}
	m.RunOnAddr(":" + strconv.Itoa(webPort))
	m.Run()
}
Exemple #18
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(
		&oauth2.Config{
			ClientID:     "client_id",
			ClientSecret: "client_secret",
			Scopes:       []string{"x", "y"},
			RedirectURL:  "redirect_url",
		},
	))
	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 #19
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(
		&oauth2.Config{
			ClientID:     "client_id",
			ClientSecret: "client_secret",
			RedirectURL:  "redirect_url",
		},
	))
	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 #20
0
func main() {
	m := martini.Classic()
	m.Use(render.Renderer(render.Options{
		Directory:  "templates",
		Extensions: []string{".tmpl", ".html"},
		Charset:    "UTF-8",
		Funcs: []template.FuncMap{
			{
				"equal": func(args ...interface{}) bool {
					return args[0] == args[1]
				},
			},
		},
	}))
	store := sessions.NewCookieStore([]byte("secret123"))
	m.Use(sessions.Sessions("my_session", store))
	m.Get("/", youth)
	m.Get("/firtConfirm", firtConfirm)
	m.Post("/firtConfirm", binding.Form(model.User{}), firtConfirmPost)
	m.Post("/userSiginCheck", binding.Bind(SiginIfo{}), userSiginCheck)
	m.Get("/userInforEdit", userInforEdit)
	m.Post("/userInforEdit", binding.Form(model.User{}), userInforEditPost)
	m.Get("/editReruenInfo/:status", editReruenInfo)
	m.Run()
}
Exemple #21
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(
		&oauth2.Config{
			ClientID:     "client_id",
			ClientSecret: "client_secret",
			RedirectURL:  "redirect_url",
		},
	))
	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)
}
Exemple #22
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 #23
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 #24
0
func Test_OriginHeader(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,
	}))

	// 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"))
	req2.Header.Set("Origin", "https://www.example.com")
	m.ServeHTTP(res2, req2)

	if res2.Header().Get("X-CSRFToken") != "" {
		t.Error("X-CSRFToken present in cross origin request")
	}
}
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
/*
 * Main function
 */
func main() {
	m := martini.Classic()

	//sessions
	store := sessions.NewCookieStore([]byte("yyt726ddd318"))
	m.Use(sessions.Sessions("yunyun", store))

	m.Map(GetMongoDB())
	m.Map(GetKotobaCollection())
	//render html templates from directory
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))

	m.Post(auth.FUNC_LOGIN, auth.PostLogin)
	m.Post(auth.FUNC_REGISTER, auth.Register)
	m.Get(auth.FUNC_LOGOUT, auth.Logout)
	m.Post(FUNC_SEARCH, auth.RequireLogin, kotoba.Search)
	m.Get(FUNC_HOME, auth.RequireLogin, kotoba.Home)
	m.Get(PAGE_ADD, auth.RequireLogin, AddWord)
	m.Get(FUNC_KOTOBA, auth.RequireLogin, kotoba.ShowKotoba)
	m.Post(FUNC_ADD, auth.RequireLogin, kotoba.AddKotoba)
	m.Get(PAGE_REVIEW, auth.RequireLogin, kotoba.DoReviews)
	m.Post(FUNC_CHECK, auth.RequireLogin, kotoba.CheckReview)
	m.Get(PAGE_EDIT, auth.RequireLogin, kotoba.EditKotoba)
	m.Post(FUNC_EDIT, auth.RequireLogin, kotoba.SaveEditKotoba)
	m.Get(PAGE_STATS, auth.RequireLogin, kotoba.ShowStats)
	// todo: not yet implemented
	//m.Get(apiReviews, auth.RequireLogin, GetReviews)

	m.Run()
}
Exemple #27
0
func main() {
	martini.Env = martini.Prod
	m := martini.Classic()

	m.Use(martini.Static("../../admin/static/"))
	m.Use(martini.Static(APP_STORE_DIR))
	m.Use(sessions.Sessions("compass_session", sessions.NewCookieStore([]byte("compass_session_cookie"))))

	m.Get("/", func(w http.ResponseWriter) string {
		w.Header().Set("content-type", "text/html")
		return SCRIPT_LOGIN
	})

	m.Get("/checkcode", func(r *http.Request, w http.ResponseWriter, s sessions.Session) {
		code := captcha.NewLen(4)
		s.Set("checkcode", code)
		captcha.WriteImage(w, code, 110, 40)
	})

	showTemplate([]string{"footer", "form", "index", "left", "login", "main", "right", "top"}, m)

	for actionName, actionHandler := range admin.ActionHandlers {
		m.Post(fmt.Sprintf("/action/%s", actionName), actionHandler)
	}

	m.RunOnAddr(SERVER_ADDR)
}
Exemple #28
0
func ExampleLogin() {
	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(oauth2.Google(
		goauth2.Client("client_id", "client_secret"),
		goauth2.RedirectURL("redirect_url"),
		goauth2.Scope("https://www.googleapis.com/auth/drive"),
	))
	// Tokens are injected to the handlers
	m.Get("/", func(tokens oauth2.Tokens) string {
		if tokens.Expired() {
			return "not logged in, or the access token is expired"
		}
		return "logged in"
	})

	// Routes that require a logged in user
	// can be protected with oauth2.LoginRequired handler.
	// If the user is not authenticated, they will be
	// redirected to the login path.
	m.Get("/restrict", oauth2.LoginRequired, func(tokens oauth2.Tokens) string {
		return tokens.Access()
	})

	m.Run()
}
Exemple #29
0
func main() {
	var v Vcap
	err := json.Unmarshal([]byte(os.Getenv("VCAP_APPLICATION")), &v)
	if err != nil {
		log.Fatal(err)
	}

	m := martini.Classic()

	app_uri := v.Uris[0]
	cfhost := strings.SplitAfterN(app_uri, ".", 2)[1]
	oauthOpts := &gooauth2.Options{
		ClientID:     os.Getenv("CLIENT_ID"),
		ClientSecret: os.Getenv("CLIENT_SECRET"),
		RedirectURL:  "https://" + app_uri + "/oauth2callback",
		Scopes:       []string{""},
	}

	cf := oauth2.NewOAuth2Provider(
		oauthOpts,
		"https://login."+cfhost+"/oauth/authorize",
		"http://uaa."+cfhost+"/oauth/token",
	)

	m.Get("/oauth2error", func() string {
		log.Fatal("oAuth error")
		return "oAuth error :("
	})

	m.Handlers(
		sessions.Sessions("session", sessions.NewCookieStore([]byte("secret123"))),
		cf,
		oauth2.LoginRequired,
		martini.Logger(),
		martini.Static("public"),
	)

	m.Get("/", func(tokens oauth2.Tokens) string {

		if tokens.IsExpired() {
			return "Not logged in, or the access token is expired"
		}

		// oAuth user information from the UAA
		body := oauth_get("http://uaa."+cfhost+"/userinfo", tokens)
		var u User
		err := json.Unmarshal(body, &u)
		if err != nil {
			log.Fatal(err)
		}

		// Example actual API call to get the list of spaces the user belongs to
		space_body := oauth_get("http://api."+cfhost+"/v2/users/"+u.User_id+"/spaces", tokens)

		return fmt.Sprintf("User ID: %s\n\nSpaces info: %s", u.User_id, space_body)
	})

	m.Run()
}
Exemple #30
0
func InitDebugMiddleware(m *martini.ClassicMartini) {
	m.Use(PARAMS)
	m.Use(DB())
	m.Use(sessions.Sessions("lol_session", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(render.Renderer(render.Options{Directory: TemplatesLocation}))
	m.Use(martini.Static("resources/public", martini.StaticOptions{Prefix: "/public"}))
	SetId("1", "10153410152015744", "Sean Myers") // Me. Set these to act like facebook, using a nice cache
}