Example #1
1
func Sessions() gin.HandlerFunc {
	switch conf.SESSION_STORE {
	case conf.REDIS:
		store, err := gin_sessions.NewRedisStore(10, "tcp", conf.REDIS_SERVER, conf.REDIS_PWD, []byte("secret"))
		if err != nil {
			panic(err)
		}
		return gin_sessions.Sessions("mysession", store)
	default:
		store := gin_sessions.NewCookieStore([]byte("secret"))
		return gin_sessions.Sessions("mysession", store)
	}
}
Example #2
0
func main() {

	r := gin.Default()
	r.Static("/assets", "assets")
	store := sessions.NewCookieStore([]byte("gssecret"))
	r.Use(sessions.Sessions("mysession", store))
	r.LoadHTMLGlob("templates/*")

	fc := new(FrontController)
	r.GET("/", fc.HomeCtr)
	r.GET("/about", fc.AboutCtr)
	r.GET("/view/:id", fc.ViewCtr)
	r.GET("/view.php", fc.ViewAltCtr)
	r.GET("/ping", fc.PingCtr)
	r.GET("/search", fc.SearchCtr)

	ac := new(AdminController)
	admin := r.Group("/admin")
	{
		admin.GET("/", ac.ListBlogCtr)
		admin.GET("/login", ac.LoginCtr)
		admin.POST("/login-process", ac.LoginProcessCtr)
		admin.GET("/logout", ac.LogoutCtr)
		admin.GET("/addblog", ac.AddBlogCtr)
		admin.POST("/save-blog-add", ac.SaveBlogAddCtr)
		admin.GET("/listblog", ac.ListBlogCtr)
		admin.GET("/deleteblog/:id", ac.DeleteBlogCtr)
		admin.POST("/save-blog-edit", ac.SaveBlogEditCtr)
		admin.GET("/editblog/:id", ac.EditBlogCtr)
	}
	// Listen and serve on 0.0.0.0:8080
	r.Run(":8080")
}
Example #3
0
func Init() {
	if router == nil {
		gin.SetMode(gin.TestMode)
		router = gin.Default()
		templ := template.New("index")
		router.SetHTMLTemplate(templ)
		store := sessions.NewCookieStore([]byte("foundation"))
		router.Use(sessions.Sessions("foundation", store))
		portNo := 0
		go func() {
			router.GET("/", func(c *gin.Context) {
				shared = *c
			})

			for portNo = 8124; true; portNo++ {

				addr := fmt.Sprintf(`:%d`, portNo)
				err := router.Run(addr)
				if err != nil {
					if strings.HasSuffix(err.Error(), `address already in use`) {
						continue
					}
				}

				break
			}

		}()
		time.Sleep(50 * time.Millisecond)
		http.Get(fmt.Sprintf("http://localhost:%d/", portNo)) // portNoが0じゃなくなるまでwaitしたほうが良い気もするが一旦
	}
}
Example #4
0
func init() {
	log.Logger.Info("init session ...")

	SessionStore = sessions.NewCookieStore([]byte("_IlikeUkeTravel.com_oyear"))

	log.Logger.Info("session inited")
}
Example #5
0
func main() {
	r := gin.Default()
	store := sessions.NewCookieStore([]byte(helper.Cookiesecret))

	r.Use(sessions.Sessions("todo_session", store))

	r.LoadHTMLGlob("templates/*")

	r.GET("/todo", displayTodo)

	r.Run(":8200")
}
Example #6
0
func main() {
	r := gin.Default()
	store := sessions.NewCookieStore([]byte(helper.Cookiesecret))

	r.Use(sessions.Sessions("todo_session", store))

	r.LoadHTMLGlob("templates/*")

	r.GET("/login", displayLogin)
	r.POST("/login", postLogin)
	r.GET("/user/:username", displayProfile)

	r.Run(":8100")
}
Example #7
0
func Run(config *config.Config, etcd *store.Etcd) {
	oauthConf := oauth2.Config{
		ClientID:     config.GitHubClientID,
		ClientSecret: config.GitHubClientSecret,
		Scopes:       []string{"user", "read:public_key"},
		Endpoint:     githuboauth.Endpoint,
	}

	if config.ReleaseMode {
		gin.SetMode(gin.ReleaseMode)
	}

	sessionStore := sessions.NewCookieStore([]byte(config.SecretKeyBase))

	r := gin.Default()
	r.Use(sessions.Sessions(AppName, sessionStore))
	r.Static("/assets", "assets")
	r.LoadHTMLGlob("templates/*")

	rootController := controller.NewRootController(config, etcd)
	appController := controller.NewAppController(config, etcd)
	argController := controller.NewArgController(config, etcd)
	envController := controller.NewEnvController(config, etcd)
	healthcheckController := controller.NewHealthcheckController(config, etcd)
	sessionController := controller.NewSessionController(config, etcd, oauthConf)

	r.GET("/", rootController.Index)

	r.GET("/signin", sessionController.SignIn)
	r.GET("/signout", sessionController.SignOut)
	r.GET("/oauth/callback", sessionController.Callback)
	r.GET("/update-keys", sessionController.UpdateKeys)

	r.GET("/apps", appController.Index)
	r.POST("/apps", appController.New)

	r.GET("/apps/:appName", appController.Get)

	r.POST("/apps/:appName/build-args", argController.New)
	r.POST("/apps/:appName/build-args/delete", argController.Delete) // TODO: DELETE /apps/:appName/build-args

	r.POST("/apps/:appName/envs", envController.New)
	r.POST("/apps/:appName/envs/delete", envController.Delete) // TODO: DELETE /apps/:appName/envs
	r.POST("/apps/:appName/envs/upload", envController.Upload)

	r.POST("/apps/:appName/healthcheck", healthcheckController.Update)

	r.Run()
}
Example #8
0
//setSessions initializes sessions & csrf middlewares
func setSessions(router *gin.Engine) {
	config := system.GetConfig()
	//https://github.com/gin-gonic/contrib/tree/master/sessions
	store := sessions.NewCookieStore([]byte(config.SessionSecret))
	store.Options(sessions.Options{HttpOnly: true, MaxAge: 7 * 86400}) //Also set Secure: true if using SSL, you should though
	router.Use(sessions.Sessions("gin-session", store))
	//https://github.com/utrack/gin-csrf
	router.Use(csrf.Middleware(csrf.Options{
		Secret: config.SessionSecret,
		ErrorFunc: func(c *gin.Context) {
			c.String(400, "CSRF token mismatch")
			c.Abort()
		},
	}))
}
Example #9
0
func init() {
	gin.SetMode(gin.DebugMode)
	rand.Seed(time.Now().UnixNano())
	servidor = gin.Default()

	store := sessions.NewCookieStore([]byte("ef7fbfd3d599befe7a86cbf37c8f05c814dcad918b8dbefb441de846c4f62ea3"))
	servidor.Use(sessions.Sessions("mysession", store))

	cargarTemplates()
	servidor.Use(static.Serve("/", static.LocalFile("./public", false)))
	servidor.StaticFile("/login", "./public/index.html")
	servidor.NoRoute(func(c *gin.Context) {
		html.ExecuteTemplate(c.Writer, "404.html", nil)
	})
}
Example #10
0
func NewRememberMe(engine *gin.Engine, cookieKey string, maxAge int, secret string) {

	rememberMeConf = RememberMeConf{
		CookieKey: cookieKey,
		MaxAge:    maxAge,
		Secret:    secret,
	}

	options := sessions.Options{
		Path:     "/",
		MaxAge:   rememberMeConf.MaxAge,
		HttpOnly: true,
	}
	cookieStore = sessions.NewCookieStore([]byte(rememberMeConf.Secret))
	cookieStore.Options(options)
}
Example #11
0
// Setup the authorization path
func Setup(redirectURL, credFile string, scopes []string, secret []byte) {
	store = sessions.NewCookieStore(secret)
	var c Credentials
	file, err := ioutil.ReadFile(credFile)
	if err != nil {
		glog.Fatalf("[Gin-OAuth] File error: %v\n", err)
	}
	json.Unmarshal(file, &c)

	conf = &oauth2.Config{
		ClientID:     c.ClientID,
		ClientSecret: c.ClientSecret,
		RedirectURL:  redirectURL,
		Scopes:       scopes,
		Endpoint:     google.Endpoint,
	}
}
Example #12
0
/*
 * Main function
 */
func main() {
	//fmt.Printf("Register function . Sqrt1(4) = %v\n", register.Sqrt1(4))

	r := gin.New()
	//	r := gin.Default()
	store := sessions.NewCookieStore([]byte("myappsecret"))
	r.Use(sessions.Sessions("mygroups", store))
	r.Use(Is_authorised())

	//r.LoadHTMLGlob("templates/*")

	templates := multitemplate.New()
	templates.AddFromFiles("home", "home.html", "header.html", "footer.html")
	templates.AddFromFiles("register", "register.html", "header.html", "footer.html")
	r.HTMLRender = templates

	//fmt.Println(register.Sqrt(2))
	//r.HTMLRender = loadTemplates("./templates")
	r.StaticFS("/css/", http.Dir("css"))
	r.StaticFS("/images/", http.Dir("images"))

	/*
		r.GET("/", func(c *gin.Context) {
			c.HTML(http.StatusOK,
				"home",
				gin.H{
					"Title": "Login Here",
				},
			)
		})
	*/

	r.GET("/", register.HomeHandler)
	r.POST("/", register.LoginHandler)
	r.POST("/register", register.RegisterHandler)
	r.GET("/register", func(c *gin.Context) {
		c.HTML(http.StatusOK,
			"register",
			gin.H{
				"Title": "New Registration",
			},
		)
	})
	r.Run(":8090")

}
Example #13
0
func main() {
	r := gin.Default()
	store := sessions.NewCookieStore([]byte("secret"))
	r.Use(sessions.Sessions("mysession", store))

	r.GET("/incr", func(c *gin.Context) {
		session := sessions.Default(c)
		var count int
		v := session.Get("count")
		if v == nil {
			count = 0
		} else {
			count = v.(int)
			count += 1
		}
		session.Set("count", count)
		session.Save()
		c.JSON(200, gin.H{"count": count})
	})
	r.Run(":8000")
}
Example #14
0
func main() {
	log.Printf("setting up gin ...")
	r := gin.Default()
	r.Static("/static", "static")
	r.LoadHTMLGlob("templates/*")

	log.Printf("setting up session store ...")
	store := sessions.NewCookieStore([]byte("secret"))
	r.Use(sessions.Sessions("whiskee", store))

	log.Printf("setting up database ...")
	r.Use(PostgresDatabase())

	log.Printf("setting up transloadit ...")
	r.Use(Transloadit())

	log.Printf("setting up routes ...")
	r.GET("/", HomeR)
	r.GET("/auth/callback", CallbackR)
	r.GET("/auth/logout", LogoutR)

	r.GET("/home", HomeR)
	r.GET("/whisky", WhiskyListR)
	r.GET("/whisky/:id", WhiskyR)
	r.GET("/user", UserListR)
	r.GET("/user/:id", UserR)

	r.GET("/add/whisky", AddWhiskyFormR)
	r.POST("/add/whisky", AddWhiskyR)
	r.GET("/edit/whisky/:id", EditWhiskyFormR)
	r.POST("/edit/whisky/:id", EditWhiskyR)

	r.POST("/add/review", AddReviewR)
	r.GET("/edit/review/:id", EditReviewFormR)
	r.POST("/edit/review/:id", EditReviewR)

	port := os.Getenv("PORT")
	log.Printf("listening on :%s", port)
	r.Run(":" + port)
}
func main() {
	// database
	mgoSession, err := mgo.Dial("128.199.130.44:27017")
	if err != nil {
		panic(err)
	}

	// register services
	userService := user.New(userStore.New(mgoSession, "example"))
	loginService := login.New(userService)
	registerService := register.New(userService)

	// create server
	r := render.New(render.Options{
		Directory:     "server/views",
		Layout:        "layout",
		Extensions:    []string{".html"},
		Delims:        render.Delims{"[[", "]]"},
		IsDevelopment: true,
	})

	g := gin.New()
	g.Use(cors.Middleware(cors.Config{
		Origins:         "*",
		Methods:         "GET, PUT, POST, DELETE",
		RequestHeaders:  "Origin, Content-Type",
		Credentials:     true,
		ValidateHeaders: false,
	}))
	g.Use(sessions.Sessions("webadmin", sessions.NewCookieStore([]byte("something-very-secret"))))
	g.Static("/assets", "./public")

	// register handlers
	NewUserHandlers(userService, r).RegisterHandlers(g)
	NewFrontendHandlers(loginService, registerService, r).RegisterHandlers(g)

	// run server
	g.Run(":3000")
}
Example #16
0
func session(config *config.Config) (s sessions.Store, err error) {

	secret := []byte(config.UString("secret", "go-default-secret"))
	t := config.UString("type", "cookie")

	switch t {
	case "cookie":
		s = sessions.NewCookieStore(secret)
	case "redis":
		s, err = sessions.NewRedisStore(
			config.UInt("size"),
			config.UString("network"),
			config.UString("address"),
			config.UString("password"),
			secret,
		)
	default:
		err = errors.New("No session type allowed.")
	}

	if err != nil {
		return nil, err
	}

	o, _ := config.Get("options")

	if o != nil {
		s.Options(sessions.Options{
			Path:     o.UString("path"),
			Domain:   o.UString("domain"),
			MaxAge:   o.UInt("max_age", int(30*time.Minute)),
			Secure:   o.UBool("secure"),
			HttpOnly: o.UBool("http_only"),
		})
	}

	return s, nil
}
Example #17
0
File: main.go Project: clude/trygo
func main() {

	fmt.Println("Booting up the server....")
	gin.SetMode("release")
	r := gin.Default()

	r.Static("/static", "./public")

	//	store, _ := sessions.NewRedisStore(10, "tcp", "localhost:6379", "", []byte("secret"))
	//	r.Use(sessions.Sessions("__usid", store))
	store := sessions.NewCookieStore([]byte("secret"))
	r.Use(sessions.Sessions("__usid", store))

	ginext.LoadTemplates(r, "tpl")
	routes.SetRouters(r)

	// connect to as for global using
	setting := new(conf.Config)
	setting.LoadFromJson("./conf.json")

	dm.ConnectAS(setting.Aerospike.Host, setting.Aerospike.Port)

	r.Run(":8000")
}
Example #18
0
func main() {
	s := db.Connect()
	defer db.Disconnect(s)
	craniumDB := db.SetDB(s)

	r := gin.Default()

	// Set up Gin cookies
	store := sessions.NewCookieStore([]byte("pladjamaicanwifflepoof"))
	r.Use(sessions.Sessions("cranium_session", store))

	var title string

	var de model.DataEntry

	r.LoadHTMLGlob("templates/*")
	r.Static("/assets", "./assets")

	// Routes
	r.GET("/", func(c *gin.Context) {
		session := sessions.Default(c)
		craniumId := session.Get("cranium_id")
		if craniumId == nil {
			// Insert a new user if the user has no cookie
			newCraniumId := randomString(30)
			db.InsertNewVisitor(craniumDB, newCraniumId)
			session.Set("cranium_id", newCraniumId)
			session.Save()
			title = newCraniumId
			readfile, _ := os.Open("templates/index-tmpl.html")
			outfile, _ := os.Create("templates/index.html")
			defer readfile.Close()
			defer outfile.Close()
			// Get all the Ids for tags in question
			aImpIds, pImpIds, imgImpIds, aNimpIds, pNimpIds, imgNimpIds := preprocess.GenerateTags(readfile, outfile)
			var atags []model.Atag
			var ptags []model.Ptag
			var imgtags []model.Imgtag

			for _, impId := range aImpIds {
				atag := model.AtagDefault
				atag.Id = impId
				atag.Important = true
				atags = append(atags, atag)
			}
			for _, impId := range pImpIds {
				ptag := model.PtagDefault
				ptag.Id = impId
				ptag.Important = true
				ptags = append(ptags, ptag)
			}
			for _, impId := range imgImpIds {
				imgtag := model.ImgtagDefault
				imgtag.Id = impId
				imgtag.Important = true
				imgtags = append(imgtags, imgtag)
			}
			for _, impId := range aNimpIds {
				atag := model.AtagDefault
				atag.Id = impId
				atag.Important = false
				atags = append(atags, atag)
			}
			for _, impId := range pNimpIds {
				ptag := model.PtagDefault
				ptag.Id = impId
				ptag.Important = false
				ptags = append(ptags, ptag)
			}
			for _, impId := range imgNimpIds {
				imgtag := model.ImgtagDefault
				imgtag.Id = impId
				imgtag.Important = false
				imgtags = append(imgtags, imgtag)
			}
			de = db.InsertNewDataEntry(craniumDB, newCraniumId, atags, ptags, imgtags)
		} else {
			readfile, _ := os.Open("templates/index-tmpl.html")
			outfile, _ := os.Create("templates/index.html")
			defer readfile.Close()
			defer outfile.Close()
			// Get all the Ids for tags in question
			preprocess.GenerateTags(readfile, outfile)
			// The user already exists, so ask the database for attributes
			title = craniumId.(string)
			visitor := db.FetchVisitor(craniumDB, craniumId.(string))
			de = visitor.Data[len(visitor.Data)-1]
		}
		craniumcss := cssgen.GenCss(de)
		c.HTML(http.StatusOK, "index.html", gin.H{
			"title":      "cranium.css | " + title,
			"craniumcss": template.CSS(craniumcss),
		})
	})

	type Entities struct {
		Data string `json:"data" binding:"required"`
	}

	r.POST("/data", func(c *gin.Context) {
		session := sessions.Default(c)
		craniumId := session.Get("cranium_id")
		var ents Entities
		c.BindJSON(&ents)
		c.JSON(200, ents)
		tags := deserialize(ents.Data)
		for _, tag := range tags {
			tag_pick := strings.Split(string(tag.Id), "-")
			if string(tag_pick[1][0]) == "a" {
				db.UpdateAtagField(craniumDB, craniumId.(string), tag)
			} else if string(tag_pick[1][0]) == "p" {
				db.UpdatePtagField(craniumDB, craniumId.(string), tag)
			} else if string(tag_pick[1][0]) == "i" {
				db.UpdateImgtagField(craniumDB, craniumId.(string), tag)
			}
		}
		// CSV the data
		app := "python"
		cmd := exec.Command(app, "learn/csvgen.py", craniumId.(string), "-de0")
		fmt.Println()
		out, err := cmd.Output()
		if err != nil {
			println(err.Error())
			return
		}
		fmt.Println(string(out))

		fmt.Println(craniumId.(string))

		cmd1 := exec.Command(app, "learn/classify.py", "learn/de_td0_a.csv", "a", craniumId.(string), "", "", "")
		cmd1.Output()

		cmd2 := exec.Command(app, "learn/classify.py", "learn/de_td0_p.csv", "p", craniumId.(string), "", "", "")
		cmd2.Output()

		cmd3 := exec.Command(app, "learn/classify.py", "learn/de_td0_img.csv", "img", craniumId.(string), "", "", "")
		cmd3.Output()

		cmd4 := exec.Command(app, "learn/classify.py", "", "solve", craniumId.(string), "learn/training/atag.csv", "learn/training/ptag.csv", "learn/training/imgtag.csv")
		cmd4.Output()

		// Run genetic

		// Save new DE entry

		// Export DE to CSV
		// cmd4 := exec.Command(app, "learn/csvgen.py", craniumId.(string))
		// cmd4.Output()

		// Concat CSV with train

		// run SVM
		// python learn/svm.py learn/training/imgtag.csv img
		// cmd5 := exec.Command(app, "learn/svm.py", "learn/training/atag.csv", "a")
		// cmd5.Output()

		// cmd6 := exec.Command(app, "learn/svm.py", "learn/training/ptag.csv", "p")
		// cmd5.Output()

		// cmd7 := exec.Command(app, "learn/svm.py", "learn/training/imgtag.csv", "img")
		// cmd5.Output()
	})

	r.Run(":1225")
}
Example #19
0
func Serve(s *server.Server) {
	config, err := NewConfigFromJSON(options.ConfigFile)
	if err != nil {
		log.Fatal("no config file")
	}

	gauthConfig := server.GoogleAuthConfig(config.GAuthKeyFile, options.Debug)
	goth.UseProviders(
		twitter.New(config.TwitterApiKey, config.TwitterApiSecret, config.TwitterApiCallback),
		gplus.New(gauthConfig.ClientID, gauthConfig.ClientSecret, gauthConfig.RedirectURL),
	)
	providers := goth.GetProviders()
	providers["google"] = providers["gplus"]

	// Assign the GetState function variable so we can return the
	// state string we want to get back at the end of the oauth process.
	// Only works with facebook and gplus providers.
	gothic.GetState = func(req *http.Request) string {
		// Get the state string from the query parameters.
		return req.URL.Query().Get("next")
	}

	r := gin.Default()
	r.HTMLRender = NewRender()
	// session
	store := sessions.NewCookieStore([]byte(options.SecretKey))
	r.Use(sessions.Sessions("ffsession", store))

	// Serve static assets
	if options.Debug {
		log.Println("==> debug mode")
		r.Static("/static", "./static")
	} else {
		r.GET("/static/*path", AssetHandler)
	}

	// oauth2
	r.GET("/auth/:provider/callback", s.AuthCallback)
	r.GET("/auth/:provider", server.AuthProvider)

	// authed
	authorized := r.Group("/account", server.LoginRequired())
	{
		authorized.GET("/", s.AccountHandler)
		authorized.GET("/import/", s.ImportHandler)
		// authorized.POST("/ffimport/", s.FriendFeedImportHandler)
		authorized.GET("/import/twitter", s.TwitterImportHandler)
		// TODO: fix get
		authorized.GET("/service/:service/delete", s.DeleteServiceHandler)
	}

	r.GET("/", s.HomeHandler)
	r.GET("favicon.ico", FaviconHandler)
	r.GET("/logout", server.LogoutHandler)

	// TODO: httproute not support "/:name" to catch all
	// see: gin #205
	r.GET("/feed/:name", s.FeedHandler)
	r.GET("/e/:uuid", s.EntryHandler)

	r.GET("/a/entry/:uuid", s.ExpandCommentHandler)
	r.GET("/a/expandlikes/:uuid", s.ExpandLikeHandler)
	action := r.Group("/a", server.LoginRequired())
	{
		action.POST("/share", s.EntryPostHandler)
		action.POST("/like", s.LikeHandler)
		action.POST("/like/delete", s.LikeDeleteHandler)
		action.POST("/comment", s.CommentHandler)
		action.POST("/comment/delete", s.CommentDeleteHandler)
	}

	r.GET("/public", s.PublicHandler)

	r.NotFound404(NotFoundHandler)

	fmt.Println("Starting server...")
	r.Run(fmt.Sprintf(":%v", options.Port))
}
Example #20
0
func main() {
	VersionNum = "2.0"
	// _, executableFile, _, _ := runtime.Caller(0) // get full path of this file
	flag.StringVar(&RuntimeArgs.Port, "p", ":8003", "port to bind")
	flag.StringVar(&RuntimeArgs.Socket, "s", "", "unix socket")
	flag.StringVar(&RuntimeArgs.ServerCRT, "crt", "", "location of ssl crt")
	flag.StringVar(&RuntimeArgs.ServerKey, "key", "", "location of ssl key")
	flag.CommandLine.Usage = func() {
		fmt.Println(`find (version ` + VersionNum + `)
run this to start the server and then visit localhost at the port you specify
(see parameters).
Example: 'find yourserver.com'
Example: 'find -p :8080 localhost:8080'
Example: 'find -s /var/run/find.sock'
Example: 'find -db /var/lib/find/db.bolt localhost:8003'
Example: 'find -p :8080 -crt ssl/server.crt -key ssl/server.key localhost:8080'
Options:`)
		flag.CommandLine.PrintDefaults()
	}
	flag.Parse()
	RuntimeArgs.ExternalIP = flag.Arg(0)
	if RuntimeArgs.ExternalIP == "" {
		RuntimeArgs.ExternalIP = GetLocalIP() + RuntimeArgs.Port
	}

	// var ps FullParameters = *NewFullParameters()
	// getParameters("findtest2", &ps)
	// calculatePriors("findtest2", &ps)
	// saveParameters("findtest2", ps)
	// // fmt.Println(string(dumpParameters(ps)))
	// saveParameters("findtest2", ps)
	// fmt.Println(ps.MacVariability)
	// fmt.Println(ps.NetworkLocs)
	// optimizePriors("findtest2")
	// ps, _ = openParameters("findtest2")
	//
	// getPositionBreakdown("findtest2", "zack")

	gin.SetMode(gin.ReleaseMode)
	r := gin.Default()
	r.LoadHTMLGlob(path.Join(RuntimeArgs.Cwd, "templates/*"))
	r.Static("static/", path.Join(RuntimeArgs.Cwd, "static/"))
	store := sessions.NewCookieStore([]byte("secret"))
	r.Use(sessions.Sessions("mysession", store))

	// 404 page
	r.NoRoute(func(c *gin.Context) {
		c.HTML(http.StatusOK, "login.tmpl", gin.H{
			"ErrorMessage": "Please login first.",
		})
	})

	// webpages (routes.go)
	r.GET("/pie/:group/:network/:location", slashPie)
	r.GET("/", slash)
	r.GET("/login", slashLogin)
	r.POST("/login", slashLoginPOST)
	r.GET("/logout", slashLogout)
	r.GET("/dashboard/:group", slashDashboard)
	r.GET("/location/:group/:user", slashLocation)
	r.GET("/explore/:group/:network/:location", slashExplore2)

	// fingerprinting (fingerprint.go)
	r.POST("/fingerprint", handleFingerprint)
	r.POST("/learn", handleFingerprint)
	r.POST("/track", trackFingerprint)

	// API routes (api.go)
	r.GET("/whereami", whereAmI)
	r.GET("/editname", editName)
	r.GET("/editusername", editUserName)
	r.GET("/editnetworkname", editNetworkName)
	r.DELETE("/location", deleteName)
	r.DELETE("/user", deleteUser)
	r.GET("/calculate", calculate)
	r.GET("/userlocs", userLocations)
	r.GET("/status", getStatus)
	dat, _ := ioutil.ReadFile("./static/logo.txt")
	fmt.Println(string(dat))
	if RuntimeArgs.Socket != "" {
		r.RunUnix(RuntimeArgs.Socket)
	} else if RuntimeArgs.ServerCRT != "" && RuntimeArgs.ServerKey != "" {
		fmt.Println("(version " + VersionNum + ") is up and running on https://" + RuntimeArgs.ExternalIP)
		fmt.Println("-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----")
		r.RunTLS(RuntimeArgs.Port, RuntimeArgs.ServerCRT, RuntimeArgs.ServerKey)
	} else {
		fmt.Println("(version " + VersionNum + ") is up and running on http://" + RuntimeArgs.ExternalIP)
		fmt.Println("-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----")
		r.Run(RuntimeArgs.Port)
	}
}
Example #21
0
func main() {
	// database setting
	user := os.Getenv("ISHOCON1_DB_USER")
	pass := os.Getenv("ISHOCON1_DB_PASSWORD")
	dbname := "ishocon1"
	db, _ = sql.Open("mysql", user+":"+pass+"@/"+dbname)
	db.SetMaxIdleConns(5)

	r := gin.Default()
	// load templates
	r.Use(static.Serve("/css", static.LocalFile("public/css", true)))
	r.Use(static.Serve("/images", static.LocalFile("public/images", true)))
	layout := "templates/layout.tmpl"

	// session store
	store := sessions.NewCookieStore([]byte("showwin_happy"))
	store.Options(sessions.Options{HttpOnly: true})
	r.Use(sessions.Sessions("mysession", store))

	// GET /login
	r.GET("/login", func(c *gin.Context) {
		session := sessions.Default(c)
		session.Clear()
		session.Save()

		tmpl, _ := template.ParseFiles("templates/login.tmpl")
		r.SetHTMLTemplate(tmpl)
		c.HTML(http.StatusOK, "login", gin.H{
			"Message": "ECサイトで爆買いしよう!!!!",
		})
	})

	// POST /login
	r.POST("/login", func(c *gin.Context) {
		email := c.PostForm("email")
		pass := c.PostForm("password")

		session := sessions.Default(c)
		user, result := authenticate(email, pass)
		if result {
			// 認証成功
			session.Set("uid", user.ID)
			session.Save()

			user.UpdateLastLogin()

			c.Redirect(http.StatusSeeOther, "/")
		} else {
			// 認証失敗
			tmpl, _ := template.ParseFiles("templates/login.tmpl")
			r.SetHTMLTemplate(tmpl)
			c.HTML(http.StatusOK, "login", gin.H{
				"Message": "ログインに失敗しました",
			})
		}
	})

	// GET /logout
	r.GET("/logout", func(c *gin.Context) {
		session := sessions.Default(c)
		session.Clear()
		session.Save()

		tmpl, _ := template.ParseFiles("templates/login.tmpl")
		r.SetHTMLTemplate(tmpl)
		c.Redirect(http.StatusFound, "/login")
	})

	// GET /
	r.GET("/", func(c *gin.Context) {
		cUser := currentUser(sessions.Default(c))

		page, err := strconv.Atoi(c.Query("page"))
		if err != nil {
			page = 0
		}
		products := getProductsWithCommentsAt(page)
		// shorten description and comment
		var sProducts []ProductWithComments
		for _, p := range products {
			if utf8.RuneCountInString(p.Description) > 70 {
				p.Description = string([]rune(p.Description)[:70]) + "…"
			}

			var newCW []CommentWriter
			for _, c := range p.Comments {
				if utf8.RuneCountInString(c.Content) > 25 {
					c.Content = string([]rune(c.Content)[:25]) + "…"
				}
				newCW = append(newCW, c)
			}
			p.Comments = newCW
			sProducts = append(sProducts, p)
		}

		r.SetHTMLTemplate(template.Must(template.ParseFiles(layout, "templates/index.tmpl")))
		c.HTML(http.StatusOK, "base", gin.H{
			"CurrentUser": cUser,
			"Products":    sProducts,
		})
	})

	// GET /users/:userId
	r.GET("/users/:userId", func(c *gin.Context) {
		cUser := currentUser(sessions.Default(c))

		uid, _ := strconv.Atoi(c.Param("userId"))
		user := getUser(uid)

		products := user.BuyingHistory()

		var totalPay int
		for _, p := range products {
			totalPay += p.Price
		}

		// shorten description
		var sdProducts []Product
		for _, p := range products {
			if utf8.RuneCountInString(p.Description) > 70 {
				p.Description = string([]rune(p.Description)[:70]) + "…"
			}
			sdProducts = append(sdProducts, p)
		}

		r.SetHTMLTemplate(template.Must(template.ParseFiles(layout, "templates/mypage.tmpl")))
		c.HTML(http.StatusOK, "base", gin.H{
			"CurrentUser": cUser,
			"User":        user,
			"Products":    sdProducts,
			"TotalPay":    totalPay,
		})
	})

	// GET /products/:productId
	r.GET("/products/:productId", func(c *gin.Context) {
		pid, _ := strconv.Atoi(c.Param("productId"))
		product := getProduct(pid)
		comments := getComments(pid)

		cUser := currentUser(sessions.Default(c))
		bought := product.isBought(cUser.ID)

		r.SetHTMLTemplate(template.Must(template.ParseFiles(layout, "templates/product.tmpl")))
		c.HTML(http.StatusOK, "base", gin.H{
			"CurrentUser":   cUser,
			"Product":       product,
			"Comments":      comments,
			"AlreadyBought": bought,
		})
	})

	// POST /products/buy/:productId
	r.POST("/products/buy/:productId", func(c *gin.Context) {
		// need authenticated
		if notAuthenticated(sessions.Default(c)) {
			tmpl, _ := template.ParseFiles("templates/login.tmpl")
			r.SetHTMLTemplate(tmpl)
			c.HTML(http.StatusForbidden, "login", gin.H{
				"Message": "先にログインをしてください",
			})
		} else {
			// buy product
			cUser := currentUser(sessions.Default(c))
			cUser.BuyProduct(c.Param("productId"))

			// redirect to user page
			tmpl, _ := template.ParseFiles("templates/mypage.tmpl")
			r.SetHTMLTemplate(tmpl)
			c.Redirect(http.StatusFound, "/users/"+strconv.Itoa(cUser.ID))
		}
	})

	// POST /comments/:productId
	r.POST("/comments/:productId", func(c *gin.Context) {
		// need authenticated
		if notAuthenticated(sessions.Default(c)) {
			tmpl, _ := template.ParseFiles("templates/login.tmpl")
			r.SetHTMLTemplate(tmpl)
			c.HTML(http.StatusForbidden, "login", gin.H{
				"Message": "先にログインをしてください",
			})
		} else {
			// create comment
			cUser := currentUser(sessions.Default(c))
			cUser.CreateComment(c.Param("productId"), c.PostForm("content"))

			// redirect to user page
			tmpl, _ := template.ParseFiles("templates/mypage.tmpl")
			r.SetHTMLTemplate(tmpl)
			c.Redirect(http.StatusFound, "/users/"+strconv.Itoa(cUser.ID))
		}
	})

	// GET /initialize
	r.GET("/initialize", func(c *gin.Context) {
		db.Exec("DELETE FROM users WHERE id > 5000")
		db.Exec("DELETE FROM products WHERE id > 10000")
		db.Exec("DELETE FROM comments WHERE id > 200000")
		db.Exec("DELETE FROM histories WHERE id > 500000")

		c.String(http.StatusOK, "Finish")
	})

	r.Run(":8080")
}
Example #22
0
func NewCookieSession(engine *gin.Engine, conf AuthConf) {
	store := sessions.NewCookieStore([]byte(conf.Session.Secret))
	newSession(engine, conf, store)
}
Example #23
0
import (
	"config"
	"controllers"
	dbUtils "db-utils"
	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/golang/appengine/log"
	"google.golang.org/appengine"
	"google.golang.org/appengine/user"
	"models"
	"net/http"
	"strings"
)

var store = sessions.NewCookieStore([]byte(config.GetConfig().AuthKey))

var db = dbUtils.DB

func updateDevPending() gin.HandlerFunc {
	return func(c *gin.Context) {
		var developer models.Developer
		developer.LoggedUser(&db, c)
		if developer.Name == "" || developer.GithubAccount == "" {
			c.HTML(http.StatusAccepted, "user.tmpl", gin.H{
				"developer": &developer,
			})
			c.Abort()
			return
		}
	}
Example #24
0
func main() {
	// _, executableFile, _, _ := runtime.Caller(0) // get full path of this file
	cwd, _ := os.Getwd()
	databaseFile := path.Join(cwd, "data.db")
	flag.StringVar(&RuntimeArgs.Port, "p", ":8003", "port to bind")
	flag.StringVar(&RuntimeArgs.DatabaseLocation, "db", databaseFile, "location of database file")
	flag.StringVar(&RuntimeArgs.AdminKey, "a", "", "key to access admin privaleges")
	flag.StringVar(&RuntimeArgs.ServerCRT, "crt", "", "location of SSL certificate")
	flag.StringVar(&RuntimeArgs.ServerKey, "key", "", "location of SSL key")
	flag.StringVar(&RuntimeArgs.WikiName, "w", "cowyo", "custom name for wiki")
	flag.BoolVar(&RuntimeArgs.ForceWss, "e", false, "force encrypted sockets (use if using Caddy auto HTTPS)")
	flag.BoolVar(&RuntimeArgs.Debug, "d", false, "debugging mode")
	flag.StringVar(&RuntimeArgs.DumpDataset, "dump", "", "directory to dump all data to")
	flag.StringVar(&RuntimeArgs.RestoreDataset, "restore", "", "directory to restore all data from")
	flag.CommandLine.Usage = func() {
		fmt.Println(`cowyo (version ` + VersionNum + `)

Usage: cowyo [options] [address]

If address is not provided then cowyo
will determine the best internal IP address.

Example: 'cowyo'
Example: 'cowyo yourserver.com'
Example: 'cowyo -p :8080 localhost:8080'
Example: 'cowyo -p :8080 -crt ssl/server.crt -key ssl/server.key localhost:8080'

Options:`)
		flag.CommandLine.PrintDefaults()
	}
	flag.Parse()

	// Set the log level
	if RuntimeArgs.Debug == false {
		logger.Level(2)
	} else {
		logger.Level(0)
	}

	if len(RuntimeArgs.DumpDataset) > 0 {
		fmt.Println("Dumping data to '" + RuntimeArgs.DumpDataset + "' folder...")
		dumpEverything(RuntimeArgs.DumpDataset)
		os.Exit(1)
	}

	RuntimeArgs.ExternalIP = flag.Arg(0)
	if RuntimeArgs.ExternalIP == "" {
		logger.Debug("Getting external ip...")
		RuntimeArgs.ExternalIP = GetLocalIP() + RuntimeArgs.Port
		logger.Debug("Using ip: %s and port %s", GetLocalIP(), RuntimeArgs.Port)
	}
	RuntimeArgs.SourcePath = cwd

	if len(RuntimeArgs.AdminKey) == 0 {
		RuntimeArgs.AdminKey = RandStringBytesMaskImprSrc(50)
	}
	// create programdata bucket
	Open(RuntimeArgs.DatabaseLocation)

	err := db.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists([]byte("programdata"))
		if err != nil {
			return fmt.Errorf("create bucket: %s", err)
		}
		return err
	})
	if err != nil {
		panic(err)
	}
	Close()

	// Default page
	defaultPage, _ := ioutil.ReadFile(path.Join(RuntimeArgs.SourcePath, "templates/aboutpage.md"))
	p := WikiData{"help", "", []string{}, []string{}, false, "zzz"}
	p.save(string(defaultPage))
	defaultPage, _ = ioutil.ReadFile(path.Join(RuntimeArgs.SourcePath, "templates/privacypolicy.md"))
	p = WikiData{"privacypolicy", "", []string{}, []string{}, false, "zzz"}
	p.save(string(defaultPage))

	if len(RuntimeArgs.RestoreDataset) > 0 {
		fmt.Println("Restoring data from '" + RuntimeArgs.RestoreDataset + "' folder...")
		filepath.Walk(RuntimeArgs.RestoreDataset, restoreFile)
		os.Exit(1)
	}
	// var q WikiData
	// q.load("about")
	// fmt.Println(getImportantVersions(q))

	r := gin.Default()
	r.LoadHTMLGlob(path.Join(RuntimeArgs.SourcePath, "templates/*"))
	store := sessions.NewCookieStore([]byte("secret"))
	r.Use(sessions.Sessions("mysession", store))
	r.GET("/", newNote)
	r.HEAD("/", func(c *gin.Context) { c.Status(200) })
	r.GET("/:title", editNote)
	r.PUT("/:title", putFile)
	r.PUT("/", putFile)
	r.GET("/:title/*option", everythingElse)
	r.POST("/:title/*option", encryptionRoute)
	r.DELETE("/listitem", deleteListItem)
	r.DELETE("/deletepage", deletePage)
	if RuntimeArgs.ServerCRT != "" && RuntimeArgs.ServerKey != "" {
		RuntimeArgs.Socket = "wss"
		fmt.Println("--------------------------")
		fmt.Println("cowyo (version " + VersionNum + ") is up and running on https://" + RuntimeArgs.ExternalIP)
		fmt.Println("Admin key: " + RuntimeArgs.AdminKey)
		fmt.Println("--------------------------")
		r.RunTLS(RuntimeArgs.Port, RuntimeArgs.ServerCRT, RuntimeArgs.ServerKey)
	} else {
		RuntimeArgs.Socket = "ws"
		if RuntimeArgs.ForceWss {
			RuntimeArgs.Socket = "wss"
		}
		fmt.Println("--------------------------")
		fmt.Println("cowyo (version " + VersionNum + ") is up and running on http://" + RuntimeArgs.ExternalIP)
		fmt.Println("Admin key: " + RuntimeArgs.AdminKey)
		fmt.Println("--------------------------")
		r.Run(RuntimeArgs.Port)
	}
}
Example #25
0
func main() {

	// connect to db
	db, err := gorm.Open("postgres", getPostgresConn())
	if err != nil {
		log.Fatal("Unable to open database:", err.Error())
	}
	if err := db.DB().Ping(); err != nil {
		log.Fatal("Unable to ping database:", err.Error())
	}
	db.DB().SetMaxIdleConns(10)
	db.DB().SetMaxOpenConns(100)

	// run migrations
	db.AutoMigrate(&table.Post{}, &table.Group{}, &table.User{}, &table.Vote{}, &table.Comment{}, &table.Permission{})

	// get api handler instances
	ph := handlers.NewPostHandler(db)
	gh := handlers.NewGroupHandler(db)
	ch := handlers.NewCommentHandler(db)
	uh := handlers.NewUserHandler(db)
	ah := handlers.NewAdminHandler(db)
	vh := handlers.NewVoteHandler(db)
	eh := handlers.NewExportHandler(db)

	// get view controller instances
	pvc := controllers.NewPageController(db)
	avc := controllers.NewAdminController(db)

	// init router
	router := gin.Default()

	// serve static files
	router.Static("/css", "./static/css")
	router.Static("/js", "./static/js")
	router.Static("/img", "./static/img")

	// session management
	store := sessions.NewCookieStore([]byte(getAuthSecret()))
	router.Use(sessions.Sessions("ddvote_session", store))

	// view routes
	views := router.Group("")
	{
		views.GET("/g/:gname", pvc.ShowGroupPage)
		views.GET("/admin/:gname", avc.ShowAdminPage)
	}

	// v1 api calls
	v1 := router.Group("api/v1")
	{
		// endpoints WITHOUT auth
		v1.POST("/login", uh.LoginWithClientID)
		v1.POST("/admin/login", ah.Login)
		v1.GET("/groups/:gname/posts", ph.GetAllPostsForGroup)

		// api v1 calls WITH auth
		v1auth := v1.Group("")
		{
			v1auth.Use(UseAuth)
			v1auth.POST("/logout", uh.Logout)
			v1auth.POST("/groups/:gname/posts", ph.CreatePost)
			v1auth.DELETE("/posts/:puuid", ph.DeletePost)
			v1auth.POST("/groups", gh.GetOrCreateGroup)
			v1auth.POST("/posts/:puuid/comments", ch.CreateComment)
			v1auth.POST("/posts/:puuid/votes", vh.CreateOrUpdateVote)
			v1auth.GET("/groups/:gname/votes/user", vh.GetUserVotes)
			v1auth.GET("/groups/:gname/export/all", eh.GetAllQuestionsCSV)
			v1auth.GET("/groups/:gname/export/top", eh.GetTopUsersCSV)
		}
	}

	router.Run(":8081")
}
Example #26
0
func main() {
	// _, executableFile, _, _ := runtime.Caller(0) // get full path of this file
	if len(Build) == 0 {
		Build = "devdevdevdevdevdevdev"
	}
	// Bing flags for changing parameters of FIND
	flag.StringVar(&RuntimeArgs.Port, "p", ":8003", "port to bind")
	flag.StringVar(&RuntimeArgs.Socket, "s", "", "unix socket")
	flag.StringVar(&RuntimeArgs.ServerCRT, "crt", "", "location of ssl crt")
	flag.StringVar(&RuntimeArgs.ServerKey, "key", "", "location of ssl key")
	flag.StringVar(&RuntimeArgs.MqttServer, "mqtt", "", "ADDRESS:PORT of mosquitto server")
	flag.StringVar(&RuntimeArgs.MqttAdmin, "mqttadmin", "", "admin to read all messages")
	flag.StringVar(&RuntimeArgs.MqttAdminPassword, "mqttadminpass", "", "admin to read all messages")
	flag.StringVar(&RuntimeArgs.MosquittoPID, "mosquitto", "", "mosquitto PID (`pgrep mosquitto`)")
	flag.StringVar(&RuntimeArgs.Dump, "dump", "", "group to dump to folder")
	flag.StringVar(&RuntimeArgs.Message, "message", "", "message to display to all users")
	flag.StringVar(&RuntimeArgs.SourcePath, "data", "", "path to data folder")
	flag.StringVar(&RuntimeArgs.RFPort, "rf", "", "port for random forests calculations")
	flag.StringVar(&RuntimeArgs.FilterMacFile, "filter", "", "JSON file for macs to filter")
	flag.CommandLine.Usage = func() {
		fmt.Println(`find (version ` + VersionNum + ` (` + Build[0:8] + `), built ` + BuildTime + `)
Example: 'findserver yourserver.com'
Example: 'findserver -p :8080 localhost:8080'
Example (mosquitto): 'findserver -mqtt 127.0.0.1:1883 -mqttadmin admin -mqttadminpass somepass -mosquitto ` + "`pgrep mosquitto`" + `
Options:`)
		flag.CommandLine.PrintDefaults()
	}
	flag.Parse()
	RuntimeArgs.ExternalIP = flag.Arg(0)
	if RuntimeArgs.ExternalIP == "" {
		RuntimeArgs.ExternalIP = GetLocalIP() + RuntimeArgs.Port
	}

	if RuntimeArgs.SourcePath == "" {
		RuntimeArgs.SourcePath = path.Join(RuntimeArgs.Cwd, "data")
	}
	fmt.Println(RuntimeArgs.SourcePath)

	// Check whether all the MQTT variables are passed to initiate the MQTT routines
	if len(RuntimeArgs.MqttServer) > 0 && len(RuntimeArgs.MqttAdmin) > 0 && len(RuntimeArgs.MosquittoPID) > 0 {
		RuntimeArgs.Mqtt = true
		setupMqtt()
	} else {
		RuntimeArgs.Mqtt = false
	}

	// Check whether random forests are used
	if len(RuntimeArgs.RFPort) > 0 {
		RuntimeArgs.RandomForests = true
	}

	// Check whether macs should be filtered
	if len(RuntimeArgs.FilterMacFile) > 0 {
		b, err := ioutil.ReadFile(RuntimeArgs.FilterMacFile)
		if err != nil {
			panic(err)
		}
		RuntimeArgs.FilterMacs = make(map[string]bool)
		json.Unmarshal(b, &RuntimeArgs.FilterMacs)
		fmt.Printf("Filtering %+v", RuntimeArgs.FilterMacs)
		RuntimeArgs.Filtering = true
	}
	// Check whether we are just dumping the database
	if len(RuntimeArgs.Dump) > 0 {
		err := dumpFingerprints(strings.ToLower(RuntimeArgs.Dump))
		if err == nil {
			fmt.Println("Successfully dumped.")
		} else {
			log.Fatal(err)
		}
		os.Exit(1)
	}

	// Check if there is a message from the admin
	if _, err := os.Stat(path.Join(RuntimeArgs.Cwd, "message.txt")); err == nil {
		messageByte, _ := ioutil.ReadFile(path.Join(RuntimeArgs.Cwd, "message.txt"))
		RuntimeArgs.Message = string(messageByte)
	}

	// Check whether SVM libraries are available
	cmdOut, _ := exec.Command("svm-scale", "").CombinedOutput()
	if len(cmdOut) == 0 {
		RuntimeArgs.Svm = false
		fmt.Println("SVM is not detected.")
		fmt.Println(`To install:
sudo apt-get install g++
wget http://www.csie.ntu.edu.tw/~cjlin/cgi-bin/libsvm.cgi?+http://www.csie.ntu.edu.tw/~cjlin/libsvm+tar.gz
tar -xvf libsvm-*.tar.gz
cd libsvm-*
make
cp svm-scale /usr/local/bin/
cp svm-predict /usr/local/bin/
cp svm-train /usr/local/bin/`)
	} else {
		RuntimeArgs.Svm = true
	}

	// Setup Gin-Gonic
	gin.SetMode(gin.ReleaseMode)
	r := gin.Default()

	// Load templates
	r.LoadHTMLGlob(path.Join(RuntimeArgs.Cwd, "templates/*"))

	// Load static files (if they are not hosted by external service)
	r.Static("static/", path.Join(RuntimeArgs.Cwd, "static/"))

	// Create cookie store to keep track of logged in user
	store := sessions.NewCookieStore([]byte("secret"))
	r.Use(sessions.Sessions("mysession", store))

	// 404-page redirects to login
	r.NoRoute(func(c *gin.Context) {
		c.HTML(http.StatusOK, "login.tmpl", gin.H{
			"ErrorMessage": "Please login first.",
		})
	})

	// r.PUT("/message", putMessage)

	// Routes for logging in and viewing dashboards (routes.go)
	r.GET("/", slash)
	r.GET("/login", slashLogin)
	r.POST("/login", slashLoginPOST)
	r.GET("/logout", slashLogout)
	r.GET("/dashboard/:group", slashDashboard)
	r.GET("/explore/:group/:network/:location", slashExplore2)
	r.GET("/pie/:group/:network/:location", slashPie)

	// Routes for performing fingerprinting (fingerprint.go)
	r.POST("/learn", learnFingerprintPOST)
	r.POST("/track", trackFingerprintPOST)

	// Routes for MQTT (mqtt.go)
	r.PUT("/mqtt", putMQTT)

	// Routes for API access (api.go)
	r.GET("/location", getUserLocations)
	r.GET("/editname", editName)
	r.GET("/editusername", editUserName)
	r.GET("/editnetworkname", editNetworkName)
	r.DELETE("/location", deleteLocation)
	r.DELETE("/locations", deleteLocations)
	r.DELETE("/user", deleteUser)
	r.DELETE("/database", deleteDatabase)
	r.GET("/calculate", calculate)
	r.GET("/status", getStatus)
	r.GET("/userlocs", userLocations) // to be deprecated
	r.GET("/whereami", whereAmI)      // to be deprecated
	r.PUT("/mixin", putMixinOverride)
	r.PUT("/database", migrateDatabase)

	// Load and display the logo
	dat, _ := ioutil.ReadFile("./static/logo.txt")
	fmt.Println(string(dat))

	// Check whether user is providing certificates
	if RuntimeArgs.Socket != "" {
		r.RunUnix(RuntimeArgs.Socket)
	} else if RuntimeArgs.ServerCRT != "" && RuntimeArgs.ServerKey != "" {
		fmt.Println(`(version ` + VersionNum + ` build ` + Build[0:8] + `) is up and running on https://` + RuntimeArgs.ExternalIP)
		fmt.Println("-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----")
		r.RunTLS(RuntimeArgs.Port, RuntimeArgs.ServerCRT, RuntimeArgs.ServerKey)
	} else {
		fmt.Println(`(version ` + VersionNum + ` build ` + Build[0:8] + `) is up and running on http://` + RuntimeArgs.ExternalIP)
		fmt.Println("-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----")
		r.Run(RuntimeArgs.Port)
	}
}
Example #27
0
func main() {
	mode := flag.String("mode", "debug", "Application mode: debug, release, test")
	flag.Parse()

	system.SetMode(mode)
	system.Init()

	//Periodic tasks
	if system.GetMode() == system.ReleaseMode {
		system.CreateXMLSitemap() //refresh sitemap now
	}
	gocron.Every(1).Day().Do(system.CreateXMLSitemap) //refresh daily
	gocron.Start()

	gin.SetMode(system.GetMode())
	router := gin.Default()
	store := sessions.NewCookieStore([]byte(system.GetConfig().SessionSecret))
	router.Use(sessions.Sessions("gin-session", store))
	router.SetHTMLTemplate(system.GetTemplates())
	router.GET("/", controllers.Home)
	router.StaticFS("/public", http.Dir("public"))
	router.GET("/signin", controllers.SignInGet)
	router.POST("/signin", controllers.SignInPost)
	router.GET("/logout", controllers.LogOut)
	if system.GetConfig().SignupEnabled {
		router.GET("/signup", controllers.SignUpGet)
		router.POST("/signup", controllers.SignUpPost)
	}

	router.GET("/pages/:idslug", controllers.PageShow)
	router.GET("/articles", controllers.ArticlesIndex)
	router.GET("/articles/:idslug", controllers.ArticleShow)
	router.GET("/reviews", controllers.ReviewsIndex)
	router.GET("/reviews/:id", controllers.ReviewShow)
	router.POST("/new_request", controllers.RequestCreatePost)
	router.POST("/new_comment", controllers.CommentCreatePost)
	//http.Handle("/edit_comment", Default(controllers.CommentPublicUpdate))
	router.GET("/new_review", controllers.ReviewCreateGet)
	router.POST("/new_review", controllers.ReviewCreatePost)
	router.GET("/edit_review", controllers.ReviewUpdateGet)
	router.POST("/edit_review", controllers.ReviewUpdatePost)

	router.Use(system.Authenticated())
	{
		router.GET("/admin", controllers.Dashboard)
		router.GET("/admin/users", controllers.UsersAdminIndex)
		router.GET("/admin/new_user", controllers.UserAdminCreateGet)
		router.POST("/admin/new_user", controllers.UserAdminCreatePost)
		router.GET("/admin/edit_user/:id", controllers.UserAdminUpdateGet)
		router.POST("/admin/edit_user/:id", controllers.UserAdminUpdatePost)
		router.POST("/admin/delete_user", controllers.UserAdminDelete)

		router.GET("/admin/pages", controllers.PagesAdminIndex)
		router.GET("/admin/new_page", controllers.PageAdminCreateGet)
		router.POST("/admin/new_page", controllers.PageAdminCreatePost)
		router.GET("/admin/edit_page/:id", controllers.PageAdminUpdateGet)
		router.POST("/admin/edit_page/:id", controllers.PageAdminUpdatePost)
		router.POST("/admin/delete_page", controllers.PageAdminDelete)

		router.GET("/admin/articles", controllers.ArticlesAdminIndex)
		router.GET("/admin/new_article", controllers.ArticleAdminCreateGet)
		router.POST("/admin/new_article", controllers.ArticleAdminCreatePost)
		router.GET("/admin/edit_article/:id", controllers.ArticleAdminUpdateGet)
		router.POST("/admin/edit_article/:id", controllers.ArticleAdminUpdatePost)
		router.POST("/admin/delete_article", controllers.ArticleAdminDelete)

		router.GET("/admin/comments", controllers.CommentsAdminIndex)
		router.GET("/admin/edit_comment/:id", controllers.CommentAdminUpdateGet)
		router.POST("/admin/edit_comment/:id", controllers.CommentAdminUpdatePost)
		router.POST("/admin/delete_comment", controllers.CommentAdminDelete)

		router.GET("/admin/reviews", controllers.ReviewsAdminIndex)
		router.GET("/admin/new_review", controllers.ReviewAdminCreateGet)
		router.POST("/admin/new_review", controllers.ReviewAdminCreatePost)
		router.GET("/admin/edit_review/:id", controllers.ReviewAdminUpdateGet)
		router.POST("/admin/edit_review/:id", controllers.ReviewAdminUpdatePost)
		router.POST("/admin/delete_review", controllers.ReviewAdminDelete)

		router.POST("/admin/ckupload", controllers.CkUpload)
	}

	log.Fatal(router.Run(":8010"))
}
Example #28
0
// CookieSessionMiddleware returns Middleware of CookieSession
func CookieSessionMiddleware(opt SessionOptions, name string, keyPairs ...[]byte) Middleware {
	store := sessions.NewCookieStore(keyPairs...)
	store.Options(sessions.Options(opt))
	return Middleware{Func: sessions.Sessions(name, store)}
}
Example #29
0
func ExposeRoutes(router *gin.Engine) {
	router.LoadHTMLGlob("web/templates/*.html")
	router.HTMLRender = createCustomRender()
	if config.IsEnvironment("production") && config.GetConfig("SPACE_CDN") != "" {
		spaceCDN = config.GetConfig("SPACE_CDN")
	} else {
		spaceCDN = "/public"
		router.Static("/public", "web/public")
	}
	store := sessions.NewCookieStore([]byte(config.GetConfig("SPACE_SESSION_SECRET")))
	store.Options(sessions.Options{
		Secure:   config.IsEnvironment("production"),
		HttpOnly: true,
	})
	router.Use(sessions.Sessions("jupiter.session", store))
	views := router.Group("/")
	{
		views.GET("/", jupiterHandler)
		views.GET("/profile", jupiterHandler)

		views.GET("/signup", func(c *gin.Context) {
			c.HTML(http.StatusOK, "satellite", utils.H{
				"AssetsEndpoint": spaceCDN,
				"Title":          " - Sign up",
				"Satellite":      "io",
				"Data": utils.H{
					"feature.gates": utils.H{
						"user.create": feature.Active("user.create"),
					},
				},
			})
		})

		views.GET("/signin", func(c *gin.Context) {
			c.HTML(http.StatusOK, "satellite", utils.H{
				"AssetsEndpoint": spaceCDN,
				"Title":          " - Sign in",
				"Satellite":      "ganymede",
			})
		})

		views.GET("/signout", func(c *gin.Context) {
			session := sessions.Default(c)

			userPublicId := session.Get("userPublicId")
			if userPublicId != nil {
				session.Delete("userPublicId")
				session.Save()
			}

			c.Redirect(http.StatusFound, "/signin")
		})

		views.GET("/session", func(c *gin.Context) {
			session := sessions.Default(c)

			userPublicId := session.Get("userPublicId")
			if userPublicId != nil {
				c.Redirect(http.StatusFound, "/")
				return
			}

			var nextPath string = "/"
			var scope string = c.Query("scope")
			var grantType string = c.Query("grant_type")
			var code string = c.Query("code")
			var clientId string = c.Query("client_id")
			var _nextPath string = c.Query("_")
			//var state string = c.Query("state")

			if scope == "" || grantType == "" || code == "" || clientId == "" {
				// Original response:
				// c.String(http.StatusMethodNotAllowed, "Missing required parameters")
				c.Redirect(http.StatusFound, "/signin")
				return
			}
			if _nextPath != "" {
				if _nextPath, err := url.QueryUnescape(_nextPath); err == nil {
					nextPath = _nextPath
				}
			}

			client := services.FindOrCreateClient("Jupiter")
			if client.Key == clientId && grantType == oauth.AuthorizationCode && scope == models.PublicScope {
				grantToken := services.FindSessionByToken(code, models.GrantToken)
				if grantToken.ID != 0 {
					session.Set("userPublicId", grantToken.User.PublicId)
					session.Save()
					services.InvalidateSession(grantToken)
					c.Redirect(http.StatusFound, nextPath)
					return
				}
			}

			c.Redirect(http.StatusFound, "/signin")
		})

		views.GET("/authorize", authorizeHandler)
		views.POST("/authorize", authorizeHandler)

		views.GET("/error", func(c *gin.Context) {
			errorReason := c.Query("response_type")

			c.HTML(http.StatusOK, "error", utils.H{
				"AssetsEndpoint": spaceCDN,
				"errorReason":    errorReason,
			})
		})

		views.POST("/token", func(c *gin.Context) {
			var grantType string = c.PostForm("grant_type")

			authorizationBasic := strings.Replace(c.Request.Header.Get("Authorization"), "Basic ", "", 1)
			client := oauth.ClientAuthentication(authorizationBasic)
			if client.ID == 0 {
				c.Header("WWW-Authenticate", fmt.Sprintf("Basic realm=\"%s\"", c.Request.RequestURI))
				c.JSON(http.StatusUnauthorized, utils.H{
					"error": oauth.AccessDenied,
				})
				return
			}

			switch grantType {
			// Authorization Code Grant
			case oauth.AuthorizationCode:
				result, err := oauth.AccessTokenRequest(utils.H{
					"grant_type":   grantType,
					"code":         c.PostForm("code"),
					"redirect_uri": c.PostForm("redirect_uri"),
					"client":       client,
				})
				if err != nil {
					c.JSON(http.StatusMethodNotAllowed, utils.H{
						"error": result["error"],
					})
					return
				} else {
					c.JSON(http.StatusOK, utils.H{
						"user_id":       result["user_id"],
						"access_token":  result["access_token"],
						"token_type":    result["token_type"],
						"expires_in":    result["expires_in"],
						"refresh_token": result["refresh_token"],
						"scope":         result["scope"],
					})
					return
				}
				return
			// Refreshing an Access Token
			case oauth.RefreshToken:
				result, err := oauth.RefreshTokenRequest(utils.H{
					"grant_type":    grantType,
					"refresh_token": c.PostForm("refresh_token"),
					"scope":         c.PostForm("scope"),
					"client":        client,
				})
				if err != nil {
					c.JSON(http.StatusMethodNotAllowed, utils.H{
						"error": result["error"],
					})
					return
				} else {
					c.JSON(http.StatusOK, utils.H{
						"user_id":       result["user_id"],
						"access_token":  result["access_token"],
						"token_type":    result["token_type"],
						"expires_in":    result["expires_in"],
						"refresh_token": result["refresh_token"],
						"scope":         result["scope"],
					})
					return
				}
				return
			// Resource Owner Password Credentials Grant
			// Client Credentials Grant
			case oauth.Password, oauth.ClientCredentials:
				c.JSON(http.StatusMethodNotAllowed, utils.H{
					"error": oauth.UnsupportedGrantType,
				})
				return
			default:
				c.JSON(http.StatusBadRequest, utils.H{
					"error": oauth.InvalidRequest,
				})
				return
			}
		})
	}
}