Exemple #1
0
// EchoServer creates HTTP server using echo framework.
//
// Implemented API:
//  GET /login             authenticate user and return JWT token
//  GET /restricted/hello  return "hello, world!" (requires authentication)
func EchoServer() *echo.Echo {
	e := echo.New()

	e.POST("/login", func(ctx echo.Context) error {
		username := ctx.FormValue("username")
		password := ctx.FormValue("password")

		if username == "ford" && password == "betelgeuse7" {
			// create token
			token := jwt.New(jwt.SigningMethodHS256)

			// generate encoded token and send it as response
			t, err := token.SignedString([]byte("seret"))
			if err != nil {
				return err
			}
			return ctx.JSON(http.StatusOK, map[string]string{
				"token": t,
			})
		}

		return echo.ErrUnauthorized
	})

	r := e.Group("/restricted")

	r.Use(middleware.JWT([]byte("seret")))

	r.GET("/hello", func(ctx echo.Context) error {
		return ctx.String(http.StatusOK, "hello, world!")
	})

	return e
}
Exemple #2
0
func main() {
	e := echo.New()

	// Middleware
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())

	// Login route
	e.POST("/login", login)

	// Unauthenticated route
	e.GET("/", accessible)

	// Restricted group
	r := e.Group("/restricted")
	r.Use(middleware.JWT([]byte("secret")))
	r.GET("", restricted)

	e.Logger.Fatal(e.Start(":1323"))
}
Exemple #3
0
// Serve sets up and starts the server
func (s *APIServer) Serve() error {
	e := echo.New()
	e.Debug = true
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())
	e.Use(middleware.CORS())
	e.Use(middleware.BodyLimit("1024K"))
	e.Use(middleware.Gzip())

	// Serve the ember app
	e.File("/", "assets/index.html")
	e.Static("/assets", "assets/assets")

	//	e.OPTIONS("/api/login/", s.updateUser)
	e.POST("/api/login/", s.login)

	// Restricted group
	r := e.Group("/api/v1")
	r.Use(middleware.JWT([]byte("secret")))
	r.Use(s.getDBUser)
	r.GET("/feeds", s.getFeeds)
	r.POST("/feeds", s.addFeed)
	r.GET("/feeds/:id", s.getFeed)
	r.PATCH("/feeds/:id", s.updateFeed)
	r.PUT("/feeds/:id/subscribe", s.subFeed)
	r.PUT("/feeds/:id/unsubscribe", s.unsubFeed)

	customServer := &http.Server{
		Addr:           fmt.Sprintf(":%d", s.Port),
		ReadTimeout:    20 * time.Second,
		WriteTimeout:   20 * time.Second,
		MaxHeaderBytes: 2048,
	}

	err := e.StartServer(customServer)
	if err != nil {
		return fmt.Errorf("Error starting server: %s", err)
	}
	return nil
}
Exemple #4
0
func main() {
	logrus.Println("running migrations")
	allErrors, ok := migrate.UpSync(dbAddr, "./migrations")
	if !ok {
		logrus.Println("Oh no ...")
		logrus.Fatal(allErrors)
		// do sth with allErrors slice
	}

	// Echo instance
	e := echo.New()
	e.Use(mw.LoggerWithConfig(mw.LoggerConfig{
		Format: "method=${method}, uri=${uri}, status=${status}\n",
	}))
	e.Use(mw.Recover())
	e.Use(mw.CORS())

	s := store.Connect(dbAddr)
	s.EnsureAdmin()
	e.Use(h.SetDB(s))

	// catch sql no rows errors and return as a 404
	// e.Use(func(h echo.HandlerFunc) echo.HandlerFunc {
	// 	return func(c echo.Context) error {
	// 		err := h(c)
	// 		if err == store.ErrNoRows {
	// 			return echo.NewHTTPError(http.StatusNotFound)
	// 		}
	// 		return err
	// 	}
	// })

	// e.Post("/session", h.CreateSession(signingkey, signingmethod))
	e.Post("/activate/:token", h.ActivateAccount)
	e.Get("/setup", h.CanSetup)
	e.Post("/setup", h.SetupApp)

	decoded, err := base64.URLEncoding.DecodeString(signingkey)
	if err != nil {
		panic(err)
	}

	auth := e.Group("")
	auth.Use(mw.JWT(decoded))
	auth.Get("/me", h.GetSession)
	// Accounts
	auth.Get("/account", h.GetAllAccounts)
	auth.Post("/account", h.CreateAccount)
	auth.Delete("/account/:id", h.DeleteAccount)

	// People
	g := auth.Group("/person")
	g.GET("", h.GetAllPeople)
	g.POST("", h.CreatePerson)
	g.GET("/:id", h.GetPerson)
	g.PUT("/:id", h.UpdatePerson)
	g.DELETE("/:id", h.DeletePerson)

	// Courses
	g = auth.Group("/course")
	g.GET("", h.GetAllCourses)
	g.POST("", h.CreateCourse)
	g.GET("/:id", h.GetCourse)
	g.PUT("/:id", h.UpdateCourse)
	g.PUT("/:courseID/term/:termID", h.CreateCourseTerm)
	g.DELETE("/:id", h.DeleteCourse)
	g.GET("/:courseID/term/:termID/assignments", h.GetCourseAssignments)
	g.GET("/:courseID/term/:termID/gradebook", h.GetGradebook)

	// Attempt
	g = auth.Group("/attempt")
	g.GET("", h.GetAllAttempts)
	g.POST("", h.CreateAttempt)
	g.GET("/:id", h.GetAttempt)
	g.PUT("/:id", h.UpdateAttempt)
	g.DELETE("/:id", h.DeleteAttempt)

	// Announcement
	g = auth.Group("/announcement")
	g.GET("", h.GetAllAnnouncements)
	g.POST("", h.CreateAnnouncement)
	g.GET("/:id", h.GetAnnouncement)
	g.PUT("/:id", h.UpdateAnnouncement)
	g.DELETE("/:id", h.DeleteAnnouncement)

	// Enrollments
	g = auth.Group("/enrollment")
	g.GET("", h.GetAllEnrollments)
	g.POST("", h.CreateEnrollment)
	g.GET("/:id", h.GetEnrollment)
	g.PUT("/:id", h.UpdateEnrollment)
	g.DELETE("/:id", h.DeleteEnrollment)

	// Terms
	g = auth.Group("/term")
	g.GET("", h.GetAllTerms)
	g.POST("", h.CreateTerm)
	g.GET("/:id", h.GetTerm)
	g.PUT("/:id", h.UpdateTerm)
	g.DELETE("/:id", h.DeleteTerm)

	// Levels
	g = auth.Group("/level")
	g.GET("", h.GetAllLevels)
	g.POST("", h.CreateLevel)
	g.GET("/:id", h.GetLevel)
	g.PUT("/:id", h.UpdateLevel)
	g.DELETE("/:id", h.DeleteLevel)

	// Assignments
	g = auth.Group("/assignment")
	g.GET("", h.GetAllAssignments)
	g.POST("", h.CreateAssignment)
	g.GET("/:id", h.GetAssignment)
	g.PUT("/:id", h.UpdateAssignment)
	g.DELETE("/:id", h.DeleteAssignment)

	// AssignmentGroups
	g = auth.Group("/group")
	g.GET("", h.GetAllAssignmentGroups)
	g.POST("", h.CreateAssignmentGroup)
	g.GET("/:id", h.GetAssignmentGroup)
	g.PUT("/:id", h.UpdateAssignmentGroup)
	g.DELETE("/:id", h.DeleteAssignmentGroup)

	// AssignmentGrades
	g = auth.Group("/grade")

	// Start server
	logrus.Println("Listening On:", port)

	e.Run(standard.New(":" + port))
}
Exemple #5
0
func main() {
	app := echo.New()
	// create new Studio
	utils.ST = badactor.NewStudio(1024) // studio capacity... RAM?

	// add the rule to the stack
	utils.ST.AddRule(mw.LoginRule)
	err := utils.ST.CreateDirectors(1024)
	if err != nil {
		log.Fatal(err)
	}

	//poll duration
	dur := time.Minute * time.Duration(60)
	// Start the reaper
	utils.ST.StartReaper(dur)

	app.Use(middleware.Recover())
	app.Use(middleware.Gzip())
	app.Use(middleware.Secure())
	app.Use(middleware.BodyLimit("100K"))

	api := app.Group("/api")

	if config.Mode == "dev" {
		// Enable Debug
		app.Use(middleware.Logger())
		app.SetDebug(true)
		corsEnabled := middleware.CORSWithConfig(middleware.CORSConfig{
			AllowHeaders: []string{
				echo.HeaderOrigin,
				echo.HeaderContentType,
				echo.HeaderAcceptEncoding,
				echo.HeaderAuthorization,
			},
		})
		// Enable CORS /
		app.Use(corsEnabled)
		// Enable CORS /api
		api.Use(corsEnabled)
	}

	// admin routing
	// app.Static("/admin", "public/admin")
	app.Static("/admin/assets", "public/admin/assets")
	app.Static("/tinymce", "public/tinymce")
	app.File("/admin*", "public/admin/index.html")
	app.File("/admin/*", "public/admin/index.html")

	// Public
	// Setup Theme
	theme.Setup(app, config.Mode)

	users := controllers.UsersController{}
	app.POST("/auth/login", users.Login, mw.Jailer)
	app.POST("/auth/delegation", users.Delegate)

	// Get jwt signingkey
	signingKey, err := models.GetSettingString("admin_signingkey")
	if err != nil {
		panic(err)
	}
	// get api routes
	api.Use(middleware.JWT([]byte(signingKey)))

	APIRoutes(api)

	// ======= SITES =====
	site := controllers.SiteController{}
	app.GET("/", site.Home)
	app.GET("/:slug", site.Single)
	app.GET("/sitemap.xml", site.Sitemap)

	app.Run(fasthttp.New(config.Port))
}