Example #1
0
func (s *ApiServer) RegisterMiddleware() {
	//s.Use(mw.Logger())
	s.Use(mw.LoggerWithConfig(mw.LoggerConfig{
		Format: `{"time":"${time_rfc3339}","remote_ip":"${remote_ip}",` +
			`"method":"${method}","uri":"${uri}","status":${status}, "latency":${latency},` +
			`"latency_human":"${latency_human}","bytes_in":${bytes_in},` +
			`"bytes_out":${bytes_out}}` + "\n",
		Output: golog.GlobalSqlLogger,
	}))
	s.Use(mw.Recover())
	s.Use(mw.BasicAuth(s.CheckAuth))
}
Example #2
0
func main() {
	err := config.Load()
	if err != nil {
		log.Fatal("Failed to load configuration: ", err)
	}

	backend, err := backend.Init()
	if err != nil {
		log.Fatal("Failed to initialize backend: ", err)
	}

	e := echo.New()
	e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
		Format: "${time_rfc3339}: ${status} ${latency_human} ${method} ${uri} - ${tx_bytes} bytes\n",
	}))
	e.Use(middleware.Recover())

	websocketHandler := ws.NewHandler(backend)

	fileServer := http.FileServer(&assetfs.AssetFS{
		Asset:     frontend.Asset,
		AssetDir:  frontend.AssetDir,
		AssetInfo: frontend.AssetInfo,
		Prefix:    "/",
	})

	e.Use(standard.WrapMiddleware(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if strings.HasPrefix(r.RequestURI, "/ws") {
				websocketHandler.ServeHTTP(w, r)
			} else if r.RequestURI == "/" {
				fileServer.ServeHTTP(w, r)
			} else if _, err := frontend.Asset(r.RequestURI[1:]); err == nil {
				fileServer.ServeHTTP(w, r)
			} else {
				next.ServeHTTP(w, r)
			}
		})
	}))
	e.Run(standard.New(config.Conf.HTTPPort))
}
Example #3
0
// NewRouter creates echo router with all application endpoints
func (a *App) NewRouter() *echo.Echo {
	// Create router with default middleware
	router := echo.New()

	// Implementing C.O.R.S. headers enable pages within a modern web browser
	// to consume resources (such as REST APIs) from servers that are on a different domain.
	router.Use(middleware.CORSWithConfig(middleware.CORSConfig{
		AllowOrigins: []string{"*"},
		AllowMethods: []string{echo.GET, echo.HEAD, echo.PUT, echo.PATCH, echo.POST, echo.DELETE},
	}))

	// Logger middleware
	router.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
		Format: `${time_rfc3339} | ${method} | ${uri} | ${status} | ${latency_human}` + "\n",
	}))

	// Handle static files
	router.Static("/", "public")

	return router
}
Example #4
0
func (a *app) Run(logger service.Logger) {
	var logFilePath string
	usr, err := user.Current()
	if err == nil {
		logFilePath = filepath.Join(usr.HomeDir, ".config/go-psexec/server-hidden.log")
	} else {
		logFilePath = "server-hidden.log"
	}

	rollingFile := &lumberjack.Logger{
		Filename:   logFilePath,
		MaxSize:    20, // megabytes
		MaxBackups: 20,
		MaxAge:     28, //days
	}

	apex.SetLevel(apex.DebugLevel) //Global level
	apex.SetHandler(json.New(rollingFile))

	tmpLogger := &defaultLogger{
		logger,
		apex.WithField("exe", filepath.Base(os.Args[0])),
	}
	a.logger = tmpLogger

	defer func() {
		if r := recover(); r != nil {
			a.logger.Errorf("Panic recovery in service RUN function: %T %+v", r, r)
		}
	}()

	a.logger.Infof("Running server version %s", TempVersion)

	a.gracefulTimeout = 30 * time.Second //Because a command could be busy executing

	pvtKey, err := shared.ReadPemKey(*serverPemFlag)
	if err != nil {
		logger.Errorf("Cannot read server pem file, error: %s. Exiting server.", err.Error())
		return
	}
	a.privateKey = pvtKey

	checksumsSvc := checksums.New()
	handlerServices := &HandlerServices{
		FilePathSummaries: filepath_summary.New(checksumsSvc),
	}

	a.h = &handler{logger, a.privateKey, handlerServices}

	allowedKeys, err := shared.LoadAllowedPublicKeysFile(*allowedPublicKeysFileFlag)
	if err != nil {
		logger.Errorf("Cannot read allowed public keys, error: %s. Exiting server.", err.Error())
		return
	}
	if len(allowedKeys) == 0 {
		logger.Errorf("Allowed public key file '%s' was read but contains no keys. Exiting server.", *allowedPublicKeysFileFlag)
		return
	}

	a.setAllowedPublicKeys(allowedKeys)

	watcher, err := shared.StartWatcher(*allowedPublicKeysFileFlag, a)
	if err != nil {

	} else {
		a.watcherPublicKeys = watcher
	}

	e := echo.New()
	if a.debugMode {
		e.SetDebug(true)
	}

	e.Use(middleware.Recover())
	if a.accessLogger {
		loggerCfg := middleware.DefaultLoggerConfig
		loggerCfg.Output = tmpLogger
		e.Use(middleware.LoggerWithConfig(loggerCfg))
	}

	t := &htmlTemplateRenderer{}
	e.SetRenderer(t)

	// Unrestricted group
	e.POST("/token", a.h.handleGenerateTokenFunc)
	e.GET("/webui", a.h.handleWebUIFunc)

	// Restricted group
	r := e.Group("/auth")
	r.Use(GetClientPubkey())
	r.GET("/ping", a.h.handlePingFunc)
	r.GET("/version", a.h.handleVersionFunc)
	r.POST("/stream", a.h.handleStreamFunc)
	r.POST("/start", a.h.handleStartFunc)
	r.POST("/upload-tar", a.h.handleUploadTarFunc)
	r.GET("/download-tar", a.h.handleDownloadTarFunc)
	r.POST("/delete", a.h.handleDeleteFunc)
	r.POST("/move", a.h.handleMoveFunc)
	r.POST("/copy", a.h.handleCopyFunc)
	r.POST("/symlink", a.h.handleSymlinkFunc)
	r.GET("/stats", a.h.handleStatsFunc)
	r.GET("/path-summary", a.h.handlePathSummaryFunc)
	r.GET("/get-temp-dir", a.h.handleGetTempDirFunc)
	r.GET("/get-os-type", a.h.handleGetOsTypeFunc)

	a.logger.Infof("Now serving on '%s'", *addressFlag)

	server := standard.New(*addressFlag)
	server.SetHandler(e)
	server.SetLogger(e.Logger())
	if e.Debug() {
		e.Logger().Debug("running in debug mode")
	}

	a.srv = &graceful.Server{
		Timeout: a.gracefulTimeout,
		Server:  server.Server,
	}

	a.registerInterruptSignal()

	err = a.srv.ListenAndServe()
	if err != nil {
		if !strings.Contains(err.Error(), "closed network connection") {
			logger.Errorf("Unable to ListenAndServe, error: %s", err.Error())
			time.Sleep(time.Second) //Sleep a second to give log time to write out
		}
	}
}
Example #5
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))
}