Example #1
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()
}
Example #2
0
func secure_handler() martini.Handler {
	return secure.Secure(secure.Options{
		AllowedHosts:         []string{"bikage.herokuapp.com"},
		SSLRedirect:          true,
		SSLProxyHeaders:      map[string]string{"X-Forwarded-Proto": "https"},
		STSSeconds:           315360000,
		STSIncludeSubdomains: true,
		FrameDeny:            true,
		ContentTypeNosniff:   true,
		BrowserXssFilter:     true,
	})
}
Example #3
0
func main() {

	flag.StringVar(&appDir, "app-dir", "", "Path to grafana installation")
	flag.StringVar(&dbDir, "db-dir", "dashboards", "Path to dashboard storage dir")
	flag.StringVar(&authDomain, "auth-domain", "", "OAuth2 domain users must authenticated from (mydomain.com)")
	flag.StringVar(&basicAuth, "auth", "", "Basic auth username (user:pw)")
	flag.StringVar(&sessionSecret, "session-secret", defaultSessionSecret, "Session secret key")
	flag.StringVar(&httpAddr, "http-addr", ":8080", "HTTP Server bind address")
	flag.StringVar(&httpsAddr, "https-addr", ":8443", "HTTPS Server bind address")
	flag.StringVar(&graphiteURL, "graphite-url", "", "Graphite URL (http://host:port)")
	flag.StringVar(&influxDBURL, "influxdb-url", "", "InfluxDB URL (http://host:8086/db/mydb)")
	flag.StringVar(&influxDBUser, "influxdb-user", "", "InfluxDB username")
	flag.StringVar(&influxDBPass, "influxdb-pass", "", "InfluxDB password")
	flag.StringVar(&openTSDBUrl, "opentsdb-url", "", "OpenTSDB URL (http://host:4242)")
	flag.StringVar(&sslCert, "ssl-cert", "", "SSL cert (PEM formatted)")
	flag.StringVar(&sslKey, "ssl-key", "", "SSL key (PEM formatted)")
	flag.StringVar(&hostAddr, "host-addr", "http://localhost:8080", "Public server address (http://mydomain.com)")
	flag.StringVar(&googleClientID, "google-client-id", "", "Google Oauth2 Client ID")
	flag.StringVar(&googleClientSecret, "google-client-secret", "", "Google Oauth2 Client Sercret")

	flag.BoolVar(&version, "version", false, "show version")
	flag.Parse()

	if version {
		println(buildVersion)
		return
	}

	if sessionSecret == defaultSessionSecret {
		log.Printf("WARN: Session secret key is using the hard-coded default. Use -session-secret <value> for a live deployment.\n")
	}

	if graphiteURL == "" && influxDBURL == "" && openTSDBUrl == "" {
		fmt.Printf("No graphite-url, influxdb-url or opentsdb-url specified.\nUse -graphite-url http://host:port or -influxdb-url http://host:8086/db/mydb or -opentsdb-url http://host:4242\n")
		return
	}

	log.Printf("Starting gofana %s", buildVersion)
	if _, err := os.Stat(dbDir); os.IsNotExist(err) {
		fmt.Printf("%s does not exist. Creating.\n", dbDir)
		err := os.Mkdir(dbDir, 0766)
		if err != nil {
			fmt.Printf("ERROR: %s\n", err)
			return
		}
	}

	db = &DashboardRepository{Dir: dbDir}
	err := db.Load()
	if err != nil {
		fmt.Printf("ERROR: %s\n", err)
		return
	}

	logger := log.New(os.Stderr, "", log.LstdFlags)
	r := martini.NewRouter()
	m := martini.New()
	m.Map(logger)
	m.Use(martini.Recovery())
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)

	if sslCert != "" && sslKey != "" {
		m.Use(secure.Secure(secure.Options{}))
	}

	b := make([]byte, 32)
	_, err = rand.Read(b)
	if err != nil {
		fmt.Printf("ERROR: %s\n", err)
		return
	}

	m.Use(sessions.Sessions("session", sessions.NewCookieStore([]byte(sessionSecret))))
	if oauthEnabled() {

		if authDomain == "" {
			fmt.Println("ERROR: No -auth-domain specified.  Cannot authenticate with OAuth2.\n")
			return
		}

		gomniauth.SetSecurityKey(signature.RandomKey(64))
		providers := gomniauth.WithProviders()

		if googleOauthEnabled() {
			providers.Add(google.New(googleClientID, googleClientSecret, fmt.Sprintf("%s/google/oauth2callback", hostAddr)))
		}
		m.Use(loginRequired)
	}

	m.Use(addCorsHeaders)
	m.Use(render.Renderer())

	if basicAuth != "" && strings.Contains(basicAuth, ":") {
		parts := strings.Split(basicAuth, ":")
		m.Use(auth.Basic(parts[0], parts[1]))
	}

	var static martini.Handler
	if appDir == "" {
		static = staticbin.Static("grafana-1.9.1", grafana.Asset)
	} else {
		static = martini.Static(appDir, martini.StaticOptions{Fallback: "/index.html", Exclude: "/api/v"})
	}

	r.NotFound(static, http.NotFound)

	r.Get("/search", searchDashboards)
	r.Get("/dashboard/:id", getDashboard)
	r.Post("/dashboard/:id", saveDashboard)
	r.Delete("/dashboard/:id", deleteDashboard)
	r.Get("/plugins/datasource.gofana.js", gofanaDatasource)
	r.Get("/config.js", gofanaConfig)
	r.Get("/graphite/**", proxyGraphite)
	r.Post("/graphite/**", proxyGraphite)
	r.Get("/influxdb/**", proxyInfluxDB)
	r.Post("/influxdb/**", proxyInfluxDB)
	r.Get("/opentsdb/**", proxyOpenTSDB)
	r.Post("/opentsdb/**", proxyOpenTSDB)
	r.Get("/:provider/auth", authRedirect)
	r.Get("/:provider/oauth2callback", oauth2callback)
	r.Get("/signin", getSignin)

	// HTTP Listener
	wg.Add(1)
	go func() {
		defer wg.Done()
		log.Printf("HTTP listening on %s\n", httpAddr)
		if err := http.ListenAndServe(httpAddr, m); err != nil {
			log.Fatal(err)
		}
	}()

	// HTTPS Listener
	if sslCert != "" && sslKey != "" {
		wg.Add(1)
		go func() {
			defer wg.Done()
			log.Printf("HTTPS listening on %s", httpsAddr)
			if err := http.ListenAndServeTLS(httpsAddr, sslCert, sslKey, m); err != nil {
				log.Fatal(err)

			}
		}()
	}
	wg.Wait()
}
Example #4
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
}