Example #1
0
func main() {
	m := martini.Classic()

	// log before and after a request
	m.Use(func(c martini.Context, log *log.Logger) {
		log.Println("before a request")

		c.Next()

		log.Println("after a request")
	})
	sublime.Route(m)

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

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

	m.Get("/get", func(session sessions.Session) string {
		v := session.Get("hello")
		if v == nil {
			return ""
		}
		return v.(string)
	})

	//m.Use("/admin", auth.Basic("username", "secretpassword"))
	m.Use(martini.Static("assets"))
	m.Run()
}
func main() {
	store := sessions.NewCookieStore([]byte("secret123"))
	dbmap = initDb()

	m := martini.Classic()
	m.Use(render.Renderer())
	m.Use(sessions.Sessions("my_session", store))
	m.Use(sessionauth.SessionUser(GenerateAnonymousUser))
	sessionauth.RedirectUrl = "/new-login"
	sessionauth.RedirectParam = "new-next"

	m.Get("/", func(r render.Render) {
		r.HTML(200, "index", nil)
	})

	m.Get("/new-login", func(r render.Render) {
		r.HTML(200, "login", nil)
	})

	m.Post("/new-login", binding.Bind(MyUserModel{}), func(session sessions.Session, postedUser MyUserModel, r render.Render, req *http.Request) {
		// You should verify credentials against a database or some other mechanism at this point.
		// Then you can authenticate this session.
		user := MyUserModel{}
		err := dbmap.SelectOne(&user, "SELECT * FROM users WHERE username = $1 and password = $2", postedUser.Username, postedUser.Password)
		if err != nil {
			r.Redirect(sessionauth.RedirectUrl)
			return
		} else {
			err := sessionauth.AuthenticateSession(session, &user)
			if err != nil {
				r.JSON(500, err)
			}

			params := req.URL.Query()
			redirect := params.Get(sessionauth.RedirectParam)
			r.Redirect(redirect)
			return
		}
	})

	m.Get("/private", sessionauth.LoginRequired, func(r render.Render, user sessionauth.User) {
		r.HTML(200, "private", user.(*MyUserModel))
	})

	m.Get("/logout", sessionauth.LoginRequired, func(session sessions.Session, user sessionauth.User, r render.Render) {
		sessionauth.Logout(session, user)
		r.Redirect("/")
	})

	m.Run()
}
Example #3
0
func TestAuthenticateSession(t *testing.T) {
	store := sessions.NewCookieStore([]byte("secret123"))
	m := martini.Classic()

	m.Use(render.Renderer())
	m.Use(sessions.Sessions("my_session", store))
	m.Use(SessionUser(NewUser))

	m.Get("/setauth", func(session sessions.Session, user User) string {
		err := AuthenticateSession(session, user)
		if err != nil {
			t.Error(err)
		}
		return "OK"
	})

	m.Get("/private", LoginRequired, func(session sessions.Session, user User) string {
		return "OK"
	})

	m.Get("/logout", LoginRequired, func(session sessions.Session, user User) string {
		Logout(session, user)
		return "OK"
	})

	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/private", nil)
	m.ServeHTTP(res, req)
	if res.Code != 302 {
		t.Errorf("Private response should be 302, was %d", res.Code)
	}

	res1 := httptest.NewRecorder()
	req1, _ := http.NewRequest("GET", "/setauth", nil)
	req1.Header.Set("Cookie", res.Header().Get("Set-Cookie"))
	m.ServeHTTP(res1, req1)
	if res1.Code != 200 {
		t.Errorf("Setauth response should be 200, was %d", res.Code)
	}

	res2 := httptest.NewRecorder()
	req2, _ := http.NewRequest("GET", "/private", nil)
	req2.Header.Set("Cookie", res1.Header().Get("Set-Cookie"))
	m.ServeHTTP(res2, req2)
	if res2.Code != 200 {
		t.Errorf("Authenticated private response should be 200, was %d", res.Code)
	}

	res3 := httptest.NewRecorder()
	req3, _ := http.NewRequest("GET", "/logout", nil)
	req3.Header.Set("Cookie", res2.Header().Get("Set-Cookie"))
	m.ServeHTTP(res3, req3)
	if res3.Code != 302 {
		t.Errorf("Logout response should be 302, was %d", res.Code)
	}

	res4 := httptest.NewRecorder()
	req4, _ := http.NewRequest("GET", "/private", nil)
	req4.Header.Set("Cookie", res3.Header().Get("Set-Cookie"))
	m.ServeHTTP(res4, req4)
	if res4.Code != 302 {
		t.Errorf("Unauthenticated private response should be 302, was %d", res.Code)
	}

}
Example #4
0
File: web.go Project: qSlide/qslide
func Web() {
	var config *app.Configuration
	config = app.LoadConfiguration()
	fmt.Printf("%s is domain", config.Port)
	fmt.Printf("Domain: %s", config.Domain)
	m := martini.Classic()

	f := []template.FuncMap{
		template.FuncMap{
			"eq": func(a, b string) bool {
				return a == b
			},
		},
		template.FuncMap{
			"ne": func(a, b string) bool {
				return a != b
			},
		},
	}

	//m.Use(render.Renderer())
	m.Use(render.Renderer(render.Options{
		Directory:  "templates",                // Specify what path to load the templates from.
		Layout:     "layout",                   // Specify a layout template. Layouts can call {{ yield }} to render the current template.
		Extensions: []string{".tmpl", ".html"}, // Specify extensions to load for templates.
		//Funcs: []template.FuncMap{AppHelpers}, // Specify helper function maps for templates to access.
		//Delims: render.Delims{"{[{", "}]}"}, // Sets delimiters to the specified strings.
		Charset: "UTF-8", // Sets encoding for json and html content-types.
		Funcs:   f,
	}))

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

	m.Get("/", func(r render.Render, session sessions.Session) {
		type Site struct {
			Domain         string
			VisitCount     uint
			Env            string
			BookmarkletURL string
		}
		BookmarkletURL := "//" + config.Domain + "/javascripts/main.js"
		if config.Env == app.PROD {
			BookmarkletURL = "//" + config.Domain + "/javascripts/main.js"
		}
		site := Site{config.Domain, 12, config.Env, BookmarkletURL}
		rand := rand.New(rand.NewSource(99))
		csrf := fmt.Sprintf("%f", rand.Float64()*1000000)
		session.Set("CSRF", csrf)
		var msg string
		if nil != session.Get("FlashMessage") {
			msg = session.Get("FlashMessage").(string)
			session.Delete("FlashMessage")
		} else {
			msg = ""
		}

		r.HTML(200, "hello", struct {
			A, B, CSRF, FlashMessage string
			Site                     Site
		}{"Guesis", "bar", csrf, msg, site})
		//return "<h1>Hello, world!</h1>"
	})

	m.Get("/qslider/download", func(r render.Render, session sessions.Session) {

	})

	m.Post("/qslider/support", func(res http.ResponseWriter, req *http.Request, params martini.Params, session sessions.Session) {
		var config *app.Configuration
		config = app.LoadConfiguration()
		mg_client := mailgun.NewClient(config.MG_API_KEY, config.MG_DOMAIN)

		req.ParseForm()
		p := req.Form
		log.Println(req.Form)
		if session.Get("CSRF") == p["csrf"][0] {
			message1 := mailgun.Message{
				FromName:    "QSlider",
				FromAddress: "[email protected]",
				ToAddress:   "[email protected]",
				Subject:     "Ticket on qslide.axcoto.com",
				Body:        "Contact from: " + p["youremail"][0] + " with content: \n<br />" + p["content"][0],
			}

			fmt.Println("Attempting to send to ", mg_client.Endpoint(message1))

			body, err := mg_client.Send(message1)
			if err != nil {
				fmt.Println("Got an error:", err)
			} else {
				fmt.Println(body)
				session.Set("FlashMessage", "Message sent")
				http.Redirect(res, req, "/", 302)
				//http.Redirect(res, req, "http://slide.dev", http.StatusTemporaryRedirect)
			}
		}
	})

	m.Get("/qslider/tutorial", func(r render.Render) {
	})

	//m.Run()
	cmd := exec.Command("pwd", "> /tmp/101")
	//cmd := exec.Command("", "5")
	err := cmd.Start()
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Waiting for command to finish...")
	err = cmd.Wait()
	http.ListenAndServe(fmt.Sprintf(":%s", config.Port), m)
	//http.ListenAndServe(":10005", m)
}
Example #5
0
func main() {
	//Change secret123 to something more secure and store session in backend instead of cookie
	store := sessions.NewCookieStore([]byte("secret123"))

	dbmap = initDb()

	defer dbmap.Db.Close()

	err := dbmap.TruncateTables()
	checkErr(err, "TruncateTables failed")

	u1 := newUser("[email protected]", "pass", "Bob", false)

	//insert rows
	err = dbmap.Insert(&u1)
	checkErr(err, "Insert failed")

	//create two posts, assign to user 1 above
	p1 := newPost("Post 1", "Lorem ipsum lorem ipsum", 1)
	p2 := newPost("Post 2", "This is my second post", 1)

	// insert rows
	err = dbmap.Insert(&p1, &p2)
	checkErr(err, "Insert failed")

	m := martini.Classic()

	m.Use(render.Renderer(render.Options{
		Directory: "templates",
		Layout:    "layout",
		Funcs: []template.FuncMap{
			{
				"formatTime": func(args ...interface{}) string {
					t1 := time.Unix(args[0].(int64), 0)
					return t1.Format(time.Stamp)
				},
			},
		},
	}))

	m.Use(sessions.Sessions("my_session", store))
	m.Use(sessionauth.SessionUser(GenerateAnonymousUser))

	sessionauth.RedirectUrl = "/login"
	sessionauth.RedirectParam = "next"

	//ROUTES

	m.Get("/register", func(r render.Render, user sessionauth.User) {

		//redirect to homepage if already authenticated
		if user.IsAuthenticated() {
			r.Redirect("/")
		} else {
			r.HTML(200, "register", nil)
		}

	})

	m.Get("/login", func(r render.Render, user sessionauth.User) {

		//redirect to homepage if already authenticated
		if user.IsAuthenticated() {
			r.Redirect("/")
		} else {
			r.HTML(200, "login", nil)
		}
	})

	m.Post("/login", binding.Form(User{}), func(session sessions.Session, postedUser User, r render.Render, ferr binding.Errors, req *http.Request) {

		log.Println(ferr)

		//Example of server side error validation for the client side form
		if ferr.Count() > 0 {
			newmap := map[string]interface{}{"metatitle": "Registration", "errormessage": "Error with Form Submission"}
			r.HTML(200, "login", newmap)
		} else {

			user := User{}

			//check login credentails with DataBase
			err := dbmap.SelectOne(&user, "SELECT * FROM users WHERE email = ? and password = ?", postedUser.Email, postedUser.Password)
			if err != nil {
				r.Redirect(sessionauth.RedirectUrl)
				return
			} else {
				err := sessionauth.AuthenticateSession(session, &user)
				if err != nil {
					r.JSON(500, err)
				}

				params := req.URL.Query()
				redirect := params.Get(sessionauth.RedirectParam)
				r.Redirect(redirect)
				return
			}

		}

	})

	m.Get("/logout", sessionauth.LoginRequired, func(session sessions.Session, user sessionauth.User, r render.Render) {
		sessionauth.Logout(session, user)
		r.Redirect("/")
	})

	m.Get("/", func(r render.Render, authuser sessionauth.User) {

		var posts []Post
		_, err = dbmap.Select(&posts, "select * from posts order by post_id")
		checkErr(err, "Select failed")

		newmap := map[string]interface{}{"metatitle": "HomePage", "authuser": authuser, "posts": posts}
		r.HTML(200, "posts", newmap)
	})

	m.Get("/users", func(r render.Render, authuser sessionauth.User) {

		var users []User

		_, err = dbmap.Select(&users, "select * from users order by id")
		checkErr(err, "Select failed")

		newmap := map[string]interface{}{"metatitle": "Users listing", "authuser": authuser, "users": users}
		r.HTML(200, "users", newmap)

	})

	m.Get("/users/:id", sessionauth.LoginRequired, func(args martini.Params, r render.Render, authuser sessionauth.User) {

		var user User

		err = dbmap.SelectOne(&user, "select * from users where id=?", args["id"])

		//simple error check
		if err != nil {
			newmap := map[string]interface{}{"metatitle": "404 Error", "message": "User not found"}
			r.HTML(404, "error", newmap)
		} else {

			var posts []Post
			_, err = dbmap.Select(&posts, "select * from posts where UserId=?", args["id"])
			checkErr(err, "Select failed")

			newmap := map[string]interface{}{"metatitle": user.Name + " profile page", "authuser": authuser, "user": user, "posts": posts}
			r.HTML(200, "user", newmap)
		}

	})

	m.Post("/users", binding.Form(User{}), func(session sessions.Session, user User, ferr binding.Errors, r render.Render) {

		//Example of server side error validation for the client side form
		if ferr.Count() > 0 {
			fmt.Println(ferr)
			newmap := map[string]interface{}{"metatitle": "Registration", "errormessage": "Error with Form Submission"}
			r.HTML(200, "register", newmap)
		} else {

			u := newUser(user.Email, user.Password, user.Name, user.authenticated)

			err = dbmap.Insert(&u)
			checkErr(err, "Insert failed")

			//create the session and redirect always to homepage
			err := sessionauth.AuthenticateSession(session, &u)
			if err != nil {
				r.JSON(500, err)
			}

			r.Redirect("/")
		}

	})

	m.Put("/users/:id", binding.Bind(User{}), func(args martini.Params, user User, r render.Render, authuser sessionauth.User) {

		//convert string to int64 so you can match the struct (passing userid via ajax does not work as it comes in as a string)
		f, _ := strconv.ParseInt(args["id"], 0, 64)

		//only allow the authenticated user to update his user attributes
		if authuser.UniqueId() == f {

			//specify the user id
			user.Id = f

			count, err := dbmap.Update(&user)
			checkErr(err, "Update failed")
			log.Println("Rows updated:", count)

			if count == 1 {
				newmap := map[string]interface{}{"responseText": "success"}
				r.JSON(200, newmap)
			} else {
				newmap := map[string]interface{}{"responseText": "error"}
				r.JSON(400, newmap)
			}

		} else {
			newmap := map[string]interface{}{"responseText": "You are not allowed to update this resource."}
			r.JSON(403, newmap)
		}

	})

	m.Delete("/users/:id", func(args martini.Params, r render.Render, authuser sessionauth.User) {

		//convert id from string to int64
		f, _ := strconv.ParseInt(args["id"], 0, 64)

		//only allow the authenticated user to delete him or her
		if authuser.UniqueId() == f {

			_, err = dbmap.Exec("delete from users where id=?", args["id"])
			checkErr(err, "Delete failed")

			if err == nil {
				newmap := map[string]interface{}{"responseText": "success"}
				r.JSON(200, newmap)
				//if you delete yourself, Ajax should redirec you
			} else {
				newmap := map[string]interface{}{"responseText": "error"}
				r.JSON(400, newmap)
			}

		} else {
			newmap := map[string]interface{}{"responseText": "You are not allowed to delete this resource."}
			r.JSON(403, newmap)
		}

	})

	m.Post("/posts", sessionauth.LoginRequired, binding.Bind(Post{}), func(post Post, r render.Render, authuser sessionauth.User) {

		//convert to int64
		f := authuser.UniqueId().(int64)
		p1 := newPost(post.Title, post.Body, f)

		err = dbmap.Insert(&p1)
		checkErr(err, "Insert failed")

		r.Redirect("/")
	})

	m.Get("/posts/:id", func(args martini.Params, r render.Render, authuser sessionauth.User) {

		var post Post

		err = dbmap.SelectOne(&post, "select * from posts where post_id=?", args["id"])

		//simple error check
		if err != nil {
			newmap := map[string]interface{}{"metatitle": "404 Error", "message": "This is not found"}
			r.HTML(404, "error", newmap)
		} else {
			newmap := map[string]interface{}{"metatitle": post.Title + " more custom", "authuser": authuser, "post": post}
			r.HTML(200, "post", newmap)
		}
	})

	m.Get("/p/:str", func(args martini.Params, r render.Render, authuser sessionauth.User) {

		var post Post

		err = dbmap.SelectOne(&post, "select * from posts where url=?", args["str"])

		//simple error check
		if err != nil {
			newmap := map[string]interface{}{"metatitle": "404 Error", "message": "This is not found"}
			r.HTML(404, "error", newmap)
		} else {
			newmap := map[string]interface{}{"metatitle": post.Title + " more custom", "authuser": authuser, "post": post}
			r.HTML(200, "post", newmap)
		}
	})

	m.Put("/posts/:id", binding.Bind(Post{}), func(args martini.Params, post Post, r render.Render, authuser sessionauth.User) {

		var newTitle = post.Title
		var newBody = post.Body

		err = dbmap.SelectOne(&post, "select * from posts where post_id=?", args["id"])

		//simple database error check
		if err != nil {
			newmap := map[string]interface{}{"message": "Something went wrong."}
			r.JSON(400, newmap)
		} else {

			//owner check
			if authuser.UniqueId() == post.UserId {

				post.Title = newTitle
				post.Body = newBody

				count, err := dbmap.Update(&post)
				checkErr(err, "Update failed")

				if count == 1 {
					newmap := map[string]interface{}{"responseText": "success"}
					r.JSON(200, newmap)
				} else {
					newmap := map[string]interface{}{"responseText": "error"}
					r.JSON(400, newmap)
				}

			} else {
				newmap := map[string]interface{}{"responseText": "You are not allowed to modify this resource."}
				r.JSON(403, newmap)
			}

		}

	})

	m.Delete("/posts/:id", func(args martini.Params, r render.Render, authuser sessionauth.User) {

		//retrieve the post to check the real owner
		var post Post
		err = dbmap.SelectOne(&post, "select * from posts where post_id=?", args["id"])

		//simple DB error check
		if err != nil {
			newmap := map[string]interface{}{"message": "Something went wrong."}
			r.JSON(400, newmap)
		} else {

			//owner check
			if authuser.UniqueId() == post.UserId {

				//delete it
				_, err := dbmap.Delete(&post)
				checkErr(err, "Delete failed")

				newmap := map[string]interface{}{"responseText": "success"}
				r.JSON(200, newmap)

			} else {
				newmap := map[string]interface{}{"responseText": "You are not allowed to delete this resource."}
				r.JSON(403, newmap)
			}

		}

	})

	m.Run()
}
Example #6
0
func main() {
	m := martini.Classic()

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

	m.Use(DB())

	m.Use(render.Renderer(render.Options{
		Directory: "templates",
		Layout:    "layout",
		Funcs: []template.FuncMap{
			{
				"addInClass": func(args ...interface{}) string {
					var i int
					var className string

					i = args[0].(int)

					if i == 0 {
						className = " in"
					} else {
						className = ""
					}

					return className
				},
				"addSelected": func(args ...interface{}) string {
					var lastGameIdSearched string
					selectedString := ""

					lastGameIdSearched = args[1].(string)

					if args[0] == bson.ObjectIdHex(lastGameIdSearched) {
						selectedString = "selected"
					}

					return selectedString
				},
				"addActiveClass": func(args ...interface{}) string {
					className := ""

					for _, path := range args[1:] {
						if path == args[0] {
							className = "active"
							break
						}
					}

					return className
				},
			},
		},
	}))

	m.Get("/", func(r render.Render, db *mgo.Database, req *http.Request) {
		templateData := map[string]interface{}{"metatitle": "Battle Answers", "currentPath": req.URL.Path}
		r.HTML(200, "index", templateData)
	})

	m.Get("/games", controllers.GamesIndex)
	m.Get("/games/new", controllers.GamesNew)
	m.Post("/games", binding.Form(controllers.GameForm{}), controllers.GamesCreate)

	m.Get("/battle_answers", controllers.BattleAnswersIndex)
	m.Get("/battle_answers/new", controllers.BattleAnswersNew)
	m.Post("/battle_answers", binding.Form(controllers.BattleAnswerForm{}), controllers.BattleAnswersCreate)

	m.Get("/search_answers", controllers.SearchAnswersIndex)
	m.Get("/search_answers/new", controllers.SearchAnswersNew)
	m.Post("/search_answers", binding.Form(controllers.SearchAnswerForm{}), controllers.SearchAnswersCreate)

	m.Run()
}
Example #7
0
func (s *Server) Init() {

	s.readConfig()

	store := sessions.NewCookieStore([]byte(s.Config2.Secret))
	store.Options(sessions.Options{
		Path:   "/",
		Domain: "",
		MaxAge: 86400 * 7,
	})

	//start Runner...
	if s.Config2.Crawl {
		runner = &Runner{s}
		go runner.Start()
	}

	cache = NewCache(s.Config2.Cachesize, s.Config2.Cachefree, true)

	i404, _ = ioutil.ReadFile("templates/static/images/404.jpg")

	m := martini.New()

	m.Map(s)

	m.Use(martini.Recovery())
	m.Use(martini.Static("templates/static"))
	m.Use(sessions.Sessions("top-kek", store))

	r := martini.NewRouter()
	r.Get("/", Auth, func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "templates/index.html")
	})
	r.Get("/db/events/:offset/:tags/:name", Auth, GetReleaseWithTagAndName)
	r.Get("/db/event/:checksum/link", Auth, LinkFollow)
	r.Get("/db/event/:checksum/image", Auth, ServeImage)
	r.Get("/db/event/:checksum/score/:score", Auth, LinkFollow)
	r.Get("/log", Auth, func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "templates/log.html")
	})
	r.Get("/log/cache", Auth, func() string {
		return fmt.Sprintf("{ \"count\": %v, \"size\": %v }", cache.GetSize(), cache.GetSizeInMb())
	})
	r.Get("/log/:offset/", Auth, GetLogs)
	r.Get("/log/:offset/:level", Auth, GetLogsWithLevel)
	r.Post("/log/clearlogs", Auth, func(server *Server) string {
		server.LogDB.Exec("drop table log")
		server.LogDB.AddTableWithName(mydb.Log{}, "log").SetKeys(true, "Uid")
		server.LogDB.CreateTablesIfNotExists()
		server.LogDB.Exec("vacuum")
		return ""
	})

	r.Get("/key/:key", func(res http.ResponseWriter, req *http.Request, server *Server, session sessions.Session, parms martini.Params) {
		key := parms["key"]
		if key == server.Config2.Key {
			log.Info("Login success from %v", req.RemoteAddr)
			session.Set("login", true)
			http.Redirect(res, req, "/", http.StatusFound)
		} else {
			log.Info("Login fail from %v", req.RemoteAddr)
			http.Error(res, "forbidden", http.StatusForbidden)
		}
	})

	m.Action(r.Handle)

	log.Info("listening on %v:%v", s.Config2.Host, s.Config2.Port)
	http.ListenAndServe(s.Config2.Host+":"+s.Config2.Port, m)
}