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) } }
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したほうが良い気もするが一旦 } }
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") }
// setupMiddleware is an internal method where we setup GIN middleware func setupMiddleware(r *gin.Engine) { // TODO: CACHE_URL should come from an environment variable but this requires // validating and parsing of the connection url into it's base components. store, err := sessions.NewRedisStore(10, "tcp", "localhost:6379", "", []byte(config.Config.Session_Secret)) if err != nil { log.Fatalln("Failed to connect to Redis.", err) } r.Use( secure.Secure(secure.Options{ // TODO: we should get these from config AllowedHosts: []string{}, SSLRedirect: false, SSLHost: "", SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, STSSeconds: 315360000, STSIncludeSubdomains: true, FrameDeny: true, ContentTypeNosniff: true, BrowserXssFilter: true, ContentSecurityPolicy: "default-src 'self'", }), sessions.Sessions("session", store), auth.UserMiddleware(), ) }
func init() { //初始化gin处理引擎 // gin.SetMode(gin.ReleaseMode) g = gin.New() g.Use(HandlerError()) { funcMap := template.FuncMap{"Equals": func(v1, v2 interface{}) bool { log.Logger.Debug("invoke function Equals") return v1 == v2 }} tmp := template.New("myTemplate") templatePages := TemplatesFinder("templates") tmp.Funcs(funcMap).ParseFiles(templatePages...) g.SetHTMLTemplate(tmp) { //这三个顺序不能变更,否则得不到正常处理 //先设置/读取session信息 g.Use(sessions.Sessions("my_session", session.SessionStore)) //然后校验请求的URL g.Use(userauth.CheckLoginPage()) //最后处理静态文件 g.Use(static.ServeRoot("/", "static")) // static files have higher priority over dynamic routes } } }
func main() { r := gin.Default() r.Use(RequestIdMiddleware()) DB, err := db.Connect(db.ConnectOpts{ Address: fmt.Sprintf("%s:%d", os.Getenv("RETHINKDB_PORT_28015_TCP_ADDR"), 28015), Database: "test", }) if err != nil { log.Fatalln(err.Error()) } db.TableCreate("users").RunWrite(DB) db.TableCreate("resources").RunWrite(DB) store, err := sessions.NewRedisStore(10, "tcp", fmt.Sprintf("%s:%d", os.Getenv("REDIS_1_PORT_6379_TCP_ADDR"), 6379), "", []byte(os.Getenv("REDIS_SECRET"))) if err != nil { log.Fatalln(err.Error()) } gob.Register(models.User{}) r.Use(sessions.Sessions("session", store)) api.Init(r, DB, RequestAuthMiddleware) login.Init(r, DB) r.Any("/ping", func(c *gin.Context) { if DB.IsConnected() { c.String(200, "ok") } else { c.String(500, "not ok") } }) r.Run(":8080") // listen and serve on 0.0.0.0:8080 }
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") }
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") }
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() }
//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() }, })) }
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) }) }
/* * 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") }
func init() { r := gin.New() r.LoadHTMLGlob("templates/*") r.Use(sessions.Sessions("session_id", store)) r.Static("/assets", "./assets") r.Use(gin.Recovery()) v1 := r.Group("api/v1") v1.Use(loginWithGoogle()) { v1.GET("/systems", controllers.GetSystems) v1.POST("/systems", controllers.CreateSystem) v1.GET("/systems/:id", controllers.GetSystem) v1.PUT("/systems/:id", controllers.UpdateSystem) v1.DELETE("/systems/:id", controllers.DeleteSystem) v1.GET("/developers", controllers.UpdatePage) v1.POST("/developers", controllers.UpdateDeveloper) v1.GET("/deploys", controllers.GetDeploys) v1.POST("/deploys", controllers.CreateDeploy) } r.Use(loginWithGoogle()) r.Use(updateDevPending()) { r.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "index.tmpl", gin.H{}) }) } r.GET("/logout", func(c *gin.Context) { ctx := appengine.NewContext(c.Request) url, _ := user.LogoutURL(ctx, "/") c.Redirect(http.StatusTemporaryRedirect, url) }) http.Handle("/", r) /* Use this for https instead of r.Run() r.RunTLS(":8080", pathToCertFile, pathToKeyFile) */ }
func main() { r := gin.Default() store, _ := sessions.NewRedisStore(10, "tcp", "localhost:6379", "", []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") }
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 newSession(engine *gin.Engine, conf AuthConf, store sessions.CookieStore) { engine.Use(sessions.Sessions(conf.Session.CookieKey, store)) options := sessions.Options{ Path: "/", MaxAge: conf.Session.MaxAge, HttpOnly: true, } store.Options(options) authConf = conf gob.Register(conf.LoginUser) engine.POST(conf.Login.url, conf.Login.handle) engine.POST(conf.Logout.url, conf.Logout.handle) engine.GET(conf.LoginSuccess.url, conf.LoginSuccess.handle) engine.GET(conf.LoginFailed.url, conf.LoginFailed.handle) engine.GET(conf.UnAuthenticated.url, conf.UnAuthenticated.handle) engine.GET(conf.IsAuthenticated.url, conf.IsAuthenticated.handle) }
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") }
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") }
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")) }
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") }
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)) }
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) } }
func Session(name string) gin.HandlerFunc { return sessions.Sessions(name, store) }
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") }
func Express(p string) *GinExpress { env := EnvironmentFromString(os.Getenv("APPLICATION_ENV")) gin.SetMode(env.Mode()) debug("Mode: %s", env.String()) debug("Base path: %s", p) var ( CONFIG_PATH = path.Join(p, "config") VIEWS_PATH = path.Join(p, "views") STATIC_PATH = path.Join(p, "public") ) c, err := NewConfig(env, CONFIG_PATH) if err != nil { panic(err) } s := &GinExpress{} s.Engine = gin.New() s.Config = c s.Engine.Use(gin.Recovery()) s.Engine.HTMLRender = NewHtmlMaster(VIEWS_PATH) lc, _ := c.Get("config.log") if lc != nil { s.Logger = NewLogger(&LogConfig{ lc.UString("level"), lc.UString("file"), lc.UString("format"), lc.UBool("rotate", true), }) } else { s.Logger = NewDefaultLogger() } s.Engine.Use(func(ctx *gin.Context) { start := time.Now() path := ctx.Request.URL.Path ctx.Next() end := time.Now() latency := end.Sub(start) clientIP := ctx.ClientIP() method := ctx.Request.Method statusCode := ctx.Writer.Status() comment := ctx.Errors.ByType(gin.ErrorTypePrivate).String() s.Logger.Info(statusCode, latency, clientIP, method, path, comment, ) }) cc, _ := c.Get("config.cors") if cc != nil { all := false origins := interfaceToString(cc.UList("allowed.origins")) if len(origins) == 0 || origins[0] == "*" { all = true } methods := interfaceToString(cc.UList("allowed.methods")) if len(methods) == 0 { methods = []string{"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"} } headers := interfaceToString(cc.UList("allowed.headers")) exposed := interfaceToString(cc.UList("exposed")) s.Engine.Use(cors.New(cors.Config{ AbortOnError: false, AllowAllOrigins: all, AllowedOrigins: origins, AllowedMethods: methods, AllowedHeaders: headers, ExposedHeaders: exposed, AllowCredentials: cc.UBool("credentials", false), MaxAge: time.Duration(cc.UInt("max_age", int(12*time.Hour))), })) } sc, _ := c.Get("config.smtp") if sc != nil { s.Mailer = NewSimpleMailer(&MailerConfig{ sc.UString("host"), sc.UInt("port"), sc.UString("username"), sc.UString("password"), &mail.Address{sc.UString("from.name"), sc.UString("from.email")}, VIEWS_PATH, }) } ss, _ := c.Get("config.session") if ss != nil { n := ss.UString("name", "go-default-session") if sess, err := session(ss); err != nil { debug("[ERR] Session", err.Error()) } else { s.Engine.Use(sessions.Sessions(n, sess)) } } s.Engine.Use(Gzip(DefaultCompression)) s.Engine.Static("/public", STATIC_PATH) return s }
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) } }
func Run() { db = db_connect() db_check_tables(db) router := gin.Default() store, err := get_redis_store() if err != nil { panic(err) } router.Use(sessions.Sessions(SESSION_NAME, store)) router.StaticFS("/css", http.Dir("resources/css")) router.StaticFS("/js", http.Dir("resources/js")) router.StaticFile("/robots.txt", "resources/data/robots.txt") router.GET("/", func(c *gin.Context) { c.Header("Content-Type", "text/html") c.String(http.StatusOK, gpc_home()) }) router_add_page(router, "help") // router_add_page(router, "login") /*router.POST("/login", func(c *gin.Context) { session := sessions.Default(c) if session.Get("user") == nil { email := c.DefaultPostForm("email", "") id := c.DefaultPostForm("id", "") password := c.DefaultPostForm("password", "") var user map[string]string if email == "" { user = get_user(db, id, false) } else { user = get_user(db, email, true) } if validate_pass(user["password"], password) { delete(user, "password") session.Set("user", user["id"]) save_err := session.Save() if save_err != nil { panic(err) } c.Redirect(http.StatusMovedPermanently, "/user") } else { c.String(http.StatusOK, MSG_ERR_BAD_LOGIN) } } else { c.Redirect(http.StatusMovedPermanently, "/user") } })*/ router.GET("/n/:name", func(c *gin.Context) { c.Header("Content-Type", "text/html") c.String(http.StatusOK, gpc_view_net(c.Param("name"))) }) router.GET("/p/:id", func(c *gin.Context) { c.Header("Content-Type", "text/html") c.String(http.StatusOK, gpc_view_post(c.Param("id"))) }) // router_add_page(router, "register") /*router.POST("/register", func(c *gin.Context) { email := c.DefaultPostForm("email", "") password := c.DefaultPostForm("password", "") password2 := c.DefaultPostForm("password2", "") if password != "" && password == password2 { if register(db, email, password) { fmt.Printf("registered %s\n", email) c.Redirect(http.StatusMovedPermanently, "/login") } else { fmt.Printf("failed to register %s\n", email) } } else { c.Redirect(http.StatusMovedPermanently, "/register") } })*/ router.GET("/source", func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently, "https://github.com/digicannon/eldersnet") }) router_add_page(router, "submit") router.POST("/submit", func(c *gin.Context) { parent_id := c.DefaultPostForm("parent_id", "") op_id := "" // TODO: set as id if logged in if parent_id == "" { // post title := c.DefaultPostForm("title", "") msg := c.DefaultPostForm("msg", "") net := c.DefaultPostForm("net", "elders") user := c.DefaultPostForm("user", "ANONYMOUS") nsfw := c.DefaultPostForm("nsfw", "false") == "true" if title != "" { submit_post(db, op_id, title, msg, net, user, nsfw) } } else { // comment msg := c.DefaultPostForm("msg", "") user := c.DefaultPostForm("user", "ANONYMOUS") op := false // TODO: check for op if msg != "" { submit_comment(db, parent_id, op_id, msg, user, op) } } }) /*router.GET("/u", func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently, "/user") }) router.GET("/u/:id", func(c *gin.Context) { c.Header("Content-Type", "text/html") // c.String(http.StatusOK, gpc_view_user(db, c.Param("id"))) }) router.GET("/user", func(c *gin.Context) { // c.Header("Content-Type", "text/html") session := sessions.Default(c) c.JSON(200, gin.H{"user": session.Get("user")}) // c.String(http.StatusOK, gpc_view_user_session()) })*/ router.Run(":80") }
// 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)} }
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 } }) } }
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) } }