Пример #1
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
}
Пример #2
0
func main() {
	store := sessions.NewCookieStore([]byte("secret123"))
	dbmap = initDb()

	m := martini.Classic()
	m.Use(render.Renderer())

	// Default our store to use Session cookies, so we don't leave logged in
	// users roaming around
	store.Options(sessions.Options{
		MaxAge: 0,
	})
	m.Use(sessions.Sessions("my_session", store))
	m.Use(sessionauth.SessionUser(GenerateAnonymousUser))
	sessionauth.RedirectUrl = "/login"
	sessionauth.RedirectParam = "index"

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

	m.Get("/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()
}
Пример #3
0
func main() {
	m := martini.Classic()

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

	m.Use(secure.Secure(secure.Options{
		SSLRedirect:     true,
		SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"},
	}))
	store := sessions.NewCookieStore([]byte(os.Getenv("COOKIE_SECRET")))
	m.Use(sessions.Sessions("the_session", store))
	m.Use(sessionauth.SessionUser(GenerateAnonymousUser))

	/** Main router **/

	m.Get("/", sessionauth.LoginRequired, cameraList)
	m.Get("/camimage", sessionauth.LoginRequired, cameraImage)

	/** Login Handling **/

	m.Get("/login", func(r render.Render) {
		r.HTML(200, "login", nil, render.HTMLOptions{
			Layout: "_login_layout",
		})
	})

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

		// if not logged in
		if postedUser.Passcode != "" && postedUser.Passcode == os.Getenv("WEB_PASSCODE") {
			user := &User{}
			err := sessionauth.AuthenticateSession(session, user)
			if err != nil {
				r.Text(500, "Error authenticating session")
				return
			}

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

		}
	})

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

	m.Run()
}
Пример #4
0
func init() {
	// All the parallelism are belong to us!
	runtime.GOMAXPROCS(runtime.NumCPU())

	// Print Version
	fmt.Println(VERSION)

	//Init Martini
	// render html templates from templates directory
	m.Use(render.Renderer(render.Options{
		Directory:  "templates",                 // Specify what path to load the templates from.
		Extensions: []string{".tmpl", ".html"},  // Specify extensions to load for templates.
		Charset:    "UTF-8",                     // Sets encoding for json and html content-types. Default is "UTF-8".
		Delims:     render.Delims{"{{%", "%}}"}, // Sets delimiters to the specified strings.
	}))

	//Init Conifg
	m.Use(cfg.Config())

	//InitDb()
	m.Use(db.MongoDB(cfg.GetCfg()))

	//InitSessionsAuth
	// Default our store to use Session cookies, so we don't leave logged in
	// users roaming around
	store := sessions.NewCookieStore([]byte(cfg.GetCfg().CookieSecret))
	store.Options(sessions.Options{
		MaxAge: 120,
	})
	m.Use(sessions.Sessions(cfg.GetCfg().SessionsName, store))
	m.Use(sessionauth.SessionUser(models.GenerateAnonymousUser))
	sessionauth.RedirectUrl = "/signin"
	sessionauth.RedirectParam = "next"

	//InitRouter
	InitRouter()
}
Пример #5
0
func main() {
	store := sessions.NewCookieStore([]byte("secret123"))
	m := martini.Classic()

	templateOptions := render.Options{}
	templateOptions.Delims.Left = "#{"
	templateOptions.Delims.Right = "}#"
	m.Use(render.Renderer(templateOptions))

	store.Options(sessions.Options{MaxAge: 0})
	m.Use(sessions.Sessions("my_session", store))

	// Every request is bound with empty user. If there's a session,
	// that empty user is filled with appopriate data
	m.Use(sessionauth.SessionUser(GenerateAnonymousUser))
	sessionauth.RedirectUrl = "/login"
	sessionauth.RedirectParam = "next"

	m.Get("/", indexHandler)
	m.Get("/login", getLoginPage)
	m.Get("/edit", getEditPage)
	m.Get("/register", getRegisterPage)
	m.Get("/logout", sessionauth.LoginRequired, logoutHandler)
	m.Post("/login", binding.Bind(User{}), postLoginHandler)
	m.Post("/register", binding.Bind(User{}), postRegisterHandler)
	m.Post("/edit", sessionauth.LoginRequired, binding.Bind(User{}), postEditHandler)

	m.Get("/hub", sessionauth.LoginRequired, getHub)

	//m.Post("/room/:name", sessionauth.LoginRequired, binding.Bind(hub{}), createHub)
	//m.Get("/room", sessionauth.LoginRequired, getRoom)

	m.Get("/ws", sessionauth.LoginRequired, wsHandler)

	m.Use(martini.Static("static"))
	m.Run()
}
Пример #6
0
func (self *oprloginComponent) Start(peer netfw.IPeer) {

	m := peer.(martinihttp.IMartiniAcceptor).GetInterface()

	var config coredef.OperateConfig
	netfw.GetConfig("OperateConfig", &config)

	store := sessions.NewCookieStore([]byte("secret123"))

	store.Options(sessions.Options{
		MaxAge: 0,
	})

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

	// 显示登陆页面
	m.Get("/login", func(r render.Render) {
		r.HTML(200, "login", nil)
	})

	// 提交登陆
	m.Post("/login", binding.Bind(gmUserPostForm{}), func(session sessions.Session, msg gmUserPostForm, r render.Render, req *http.Request) {

		var verify bool

		for _, v := range config.GetAccount() {
			if msg.UserName == v.GetAccount() && msg.Password == EncodePassword(v.GetPassword()) {
				verify = true
				break
			}
		}

		if !verify {
			r.Redirect("login")
		}

		err := sessionauth.AuthenticateSession(session, &User{AutoID: 1})
		if err != nil {
			r.JSON(500, err)
		}

		r.Redirect("index")

	})

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

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

	m.Get("/", func(r render.Render) {
		r.Redirect("index")
	})

}
Пример #7
0
// NewApp creates a application object with some basic default middleware. It's based on ClassicMartini.
// Classic also maps martini.Routes as a service.
func NewApp(cfg Config, newUser func() sessionauth.User) *PolarisApplication {
	// Create config object
	if !cfg.LoadConfig() {
		log.Error("Failed to init config object")
		return nil
	}
	config := cfg.GetBasicConfig()

	log.Debug("Application started......")
	// create router object
	rtr := martini.NewRouter()

	// create matini object
	server := martini.New()

	// replace log for testing
	server.Map((*log.LevelBasedLogger)(nil))
	server.Use(Logger())

	server.Use(martini.Recovery())
	server.Use(martini.Static(config.DirStatic))
	server.MapTo(rtr, (*martini.Routes)(nil))
	server.Action(rtr.Handle)

	app := &PolarisApplication{server, rtr, cfg, nil, nil}

	log.Debug("Add middleware -- martini-contrib/render......")
	app.Use(render.Renderer(render.Options{
		Directory:  config.DirTemplate,
		Extensions: []string{config.TempExtension},
		Charset:    config.TempEncoding,
	}))

	log.Debug("Add middleware -- martini-contrib/sessions......")
	if "redis" == strings.ToLower(strings.TrimSpace(config.SessionStore)) {
		var err error
		log.Debug("Connect to redis......" + config.Redis.Address)
		if app.Store == nil {
			app.Store, err = redistore.NewRediStoreWithDB(
				config.Redis.Size,
				config.Redis.Network,
				config.Redis.Address,
				config.Redis.Password,
				config.Redis.DB,
				[]byte(config.SessionMask),
			)
			if err != nil {
				log.Error("Failed to connect to redis : " + err.Error())
				return nil
			}
		}
		app.Use(sessions.Sessions(config.SessionName, app.Store))
	} else {
		app.Use(sessions.Sessions(config.SessionName, sessions.NewCookieStore([]byte(config.SessionMask))))
	}

	if len(config.Database.Database) > 0 {
		log.Debug("Connect to databse......[" + config.Database.Database + "]")
		// ensure the connection can be made corrrectly, connect to the dabase when starting
		app.DbEngine = config.Database.InitDB()
		if app.DbEngine == nil {
			log.Error("Failed to connect to database (" + config.Database.Database + ")")
			return nil
		}
		log.Debug("Add middleware -- gorp......")
		app.Use(config.Database.MartiniHandler())
	}

	log.Debug("Add middleware -- martini-contrib/sessionauth......")
	app.Use(sessionauth.SessionUser(newUser))
	sessionauth.RedirectUrl = config.url["RedirectUrl"]
	sessionauth.RedirectParam = config.url["RedirectParam"]

	log.Debug("Add User defined router mapping......")
	if !cfg.RoterMap(app) {
		log.Error("Failed to add Roter Mapping")
		return nil
	}
	return app
}
Пример #8
0
func init() {
	m = martini.New()
	// Setup middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(martini.Static("public"))
	m.Use(MapEncoder)
	// m.Use(strict.Strict)
	// Setup routes
	r := martini.NewRouter()

	//warnasecretkey
	store := sessions.NewCookieStore([]byte("799a41cbe4de9a67eaa42acc83c76be7aa57e684"))
	store.Options(sessions.Options{
		MaxAge: 3600,
	})

	m.Use(sessions.Sessions("admin_session", store))
	m.Use(sessionauth.SessionUser(models.GenerateAnonymousUser))
	sessionauth.RedirectUrl = "/hq"

	r.Group("/warnabroda", func(r martini.Router) {

		r.Get(`/messages/:lang_key`, routes.GetMessages)
		r.Get(`/contact_types`, routes.GetContact_types)
		r.Get(`/subjects`, routes.GetSubjects)
		r.Post(`/captcha`, binding.Json(models.Captcha{}), routes.CaptchaResponse)

		r.Post(`/warnings`, binding.Json(models.Warning{}), routes.AddWarning)
		r.Get(`/warnings/counter`, routes.CountSentWarnings)
		r.Post(`/warnings/delivery`, binding.Json(models.DefaultStruct{}), routes.SendConfirmation)

		r.Post(`/ignore-list`, binding.Json(models.Ignore_List{}), routes.AddIgnoreList)
		r.Put(`/ignore-list`, binding.Json(models.Ignore_List{}), routes.ConfirmIgnoreList)

		r.Get(`/reply/:hash`, routes.GetReplyByHash)
		r.Post(`/reply`, binding.Json(models.WarningResp{}), routes.SetReply)
		r.Put(`/reply`, binding.Json(models.WarningResp{}), routes.ReadReply)

		r.Group("/hq", func(r martini.Router) {

			r.Get(`/auth-on`, routes.GetAuthenticatedUser)
			r.Post(`/login`, binding.Json(models.UserLogin{}), routes.DoLogin)
			r.Get(`/logout`, routes.DoLogout)
			r.Get(`/user/private`, routes.IsAuthenticated)

			r.Get(`/account/:id`, routes.GetUserById)

			r.Get(`/totals`, routes.WarnaCounter)

			r.Get(`/warnings`, binding.Json(models.Warn{}), routes.ListWarnings)
			r.Get(`/warnings/:id`, routes.GetWarningDetail)

			r.Post(`/messages`, binding.Json(models.MessageStruct{}), routes.SaveOrUpdateMessage)
			r.Get(`/messages/:id`, routes.GetMessage)
			r.Get(`/stats`, routes.GetMessagesStats)

		})

	})

	// Inject database
	m.MapTo(models.Dbm, (*gorp.SqlExecutor)(nil))
	// Add the router action
	m.Action(r.Handle)
}
Пример #9
0
func UserSessionAuth() martini.Handler {
	return sessionauth.SessionUser(models.GenerateAnonymousUser)
}
Пример #10
0
func AdminSessionAuth() martini.Handler {
	return sessionauth.SessionUser(models.GenerateAnonymousAdmin)
}
Пример #11
0
func setupMartini(root string) *martini.Martini {
	m := martini.New()

	// database
	InitDb(os.Getenv("DATABASE_URL"))

	// Security
	m.Use(secure.Secure(secure.Options{
		SSLRedirect: true,
	}))

	// Sessions Cookie store
	store := sessions.NewCookieStore([]byte(os.Getenv("COOKIE_SECRET")))
	store.Options(sessions.Options{
		Path:   "/",
		MaxAge: 60 * 60 * 24 * 30,
	})
	m.Use(sessions.Sessions("rr_session", store))
	m.Use(sessionauth.SessionUser(GuestAccount))
	sessionauth.RedirectUrl = "/login"
	sessionauth.RedirectParam = "return"

	// middleware
	m.Use(ReqLogger())
	m.Use(martini.Recovery())
	m.Use(martini.Static("public", martini.StaticOptions{
		Prefix:      "assets",
		SkipLogging: true,
	}))

	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST"},
		AllowHeaders:     []string{"Origin"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	// routes
	r := martini.NewRouter()
	r.Get("/", RedirectAuthenticated("/account"), func(r render.Render) {
		r.HTML(200, "index", nil)
	})

	r.Get("/signout", sessionauth.LoginRequired, GetSignout)

	r.Post("/accounts", PostAccounts)
	r.Get("/account", sessionauth.LoginRequired, GetAccount)
	r.Post("/account/billing", sessionauth.LoginRequired, PostAccountBilling)

	r.Get("/setup", sessionauth.LoginRequired, GetSetup)

	r.Get("/confirm/:confirmation_token", GetConfirmAccount)
	r.Get("/t/:public_key/:article_id/:user_id/:signature.gif", GetTrackReadReceipts(root))
	r.Post("/read_receipts", PostReadReceipts)
	r.Get(`/articles/**`, GetArticles)
	r.Post("/articles", AuthAccount, PostArticles)

	r.Get("/readers/:distinct_id", AuthAccount, GetReader)
	r.Get("/readers/:distinct_id/articles/all", AuthAccount, GetReaderArticlesAll)
	r.Get("/readers/:distinct_id/articles", GetReaderArticles)

	// go-workers stats
	workers.Configure(map[string]string{
		"process": "web",
		"server":  os.Getenv("REDIS_URL"),
	})
	r.Get("/workers/stats", workers.Stats)

	r.Get("/favicon.ico", serveFile("./public/favicon.ico"))
	r.Get("/ws/:public_key", WebsocketHandler)

	// start websocket hub
	go hub.run()

	// Inject database
	m.Map(dbmap)

	// Inject gokiq client
	gokiq.Client.RedisNamespace = "rr"
	gokiq.Client.RedisPool = redis.NewPool(RedisConnect(os.Getenv("REDIS_URL")), 1)
	gokiq.Client.Register(&UserCallbackJob{}, "default", 5)
	gokiq.Client.Register(&NewAccountEmailJob{}, "default", 5)

	m.Map(gokiq.Client)

	m.Action(r.Handle)

	return m
}