Ejemplo n.º 1
0
func SetUser(c *gin.Context) {
	var user *model.User

	// authenticates the user via an authentication cookie
	// or an auth token.
	t, err := token.ParseRequest(c.Request, func(t *token.Token) (string, error) {
		var err error
		user, err = store.GetUserLogin(c, t.Text)
		return user.Secret, err
	})

	if err == nil {
		c.Set("user", user)

		// if this is a session token (ie not the API token)
		// this means the user is accessing with a web browser,
		// so we should implement CSRF protection measures.
		if t.Kind == token.SessToken {
			err = token.CheckCsrf(c.Request, func(t *token.Token) (string, error) {
				return user.Secret, nil
			})
			// if csrf token validation fails, exit immediately
			// with a not authorized error.
			if err != nil {
				c.AbortWithStatus(http.StatusUnauthorized)
				return
			}
		}
	}
	c.Next()
}
Ejemplo n.º 2
0
func ProjectMiddleware(c *gin.Context) {
	user := c.MustGet("user").(*models.User)

	projectID, err := util.GetIntParam("project_id", c)
	if err != nil {
		return
	}

	query, args, _ := squirrel.Select("p.*").
		From("project as p").
		Join("project__user as pu on pu.project_id=p.id").
		Where("p.id=?", projectID).
		Where("pu.user_id=?", user.ID).
		ToSql()

	var project models.Project
	if err := database.Mysql.SelectOne(&project, query, args...); err != nil {
		if err == sql.ErrNoRows {
			c.AbortWithStatus(404)
			return
		}

		panic(err)
	}

	c.Set("project", project)
	c.Next()
}
Ejemplo n.º 3
0
// Handler for the agent
func Handler(c *gin.Context) {
	startTime := time.Now()
	c.Next()
	if agent != nil {
		agent.HTTPTimer.UpdateSince(startTime)
	}
}
Ejemplo n.º 4
0
// handleErrors is the error handling middleware, it is run on each request/response as the
// last middleware and will render appropriate JSON responses for various error conditions
func handleErrors(c *gin.Context) {
	c.Next()
	fmt.Println("HANDLING ERRROS")
	errorToPrint := c.Errors.ByType(gin.ErrorTypePublic).Last()
	if errorToPrint != nil {
		// Super lame switch determined by the couchbase error's string, until I
		// figure out something more serious (str values: gocb/gocbcore/error.go)
		switch errorToPrint.Error() {
		case "Key not found.":
			c.JSON(http.StatusNotFound, gin.H{
				"status":  http.StatusNotFound,
				"message": errorToPrint.Error(),
			})
		case "Key already exists.":
			c.JSON(http.StatusBadRequest, gin.H{
				"status":  http.StatusBadRequest,
				"message": errorToPrint.Error(),
			})
		default:
			c.JSON(http.StatusInternalServerError, gin.H{
				"status":  http.StatusInternalServerError,
				"message": errorToPrint.Error(),
			})
		}
	}
}
Ejemplo n.º 5
0
Archivo: repo.go Proyecto: Ablu/drone
func MustPush(c *gin.Context) {
	user := User(c)
	perm := Perm(c)

	// if the user has push access, immediately proceed
	// the middleware execution chain.
	if perm.Push {
		c.Next()
		return
	}

	// debugging
	if user != nil {
		c.AbortWithStatus(http.StatusNotFound)
		log.Debugf("User %s denied write access to %s",
			user.Login, c.Request.URL.Path)

	} else {
		c.AbortWithStatus(http.StatusUnauthorized)
		log.Debugf("Guest denied write access to %s %s",
			c.Request.Method,
			c.Request.URL.Path,
		)
	}
}
Ejemplo n.º 6
0
// Browsers complain when the allowed origin is *, and there are cookies being
// set, which socket.io requires.
func SocketIOCors(c *gin.Context) {
	origin := c.Request.Header.Get("Origin")
	if origin != "" {
		c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
	}
	c.Next()
}
Ejemplo n.º 7
0
func Logger(c *gin.Context) {
	requestId := util.NewId()
	c.Set("request_id", requestId)

	method := c.Request.Method
	path := c.Request.URL.EscapedPath()
	ip := c.ClientIP()

	log.InfoFields("Request received", log.Fields{
		"request_id": requestId,
		"method":     method,
		"ip":         ip,
		"path":       path,
	})

	start := time.Now()
	c.Next()
	duration := time.Since(start)

	code := c.Writer.Status()

	log.InfoFields("Request handled", log.Fields{
		"request_id": requestId,
		"took":       duration.String(),
		"code":       code,
	})

}
Ejemplo n.º 8
0
func InventoryMiddleware(c *gin.Context) {
	project := c.MustGet("project").(models.Project)
	inventoryID, err := util.GetIntParam("inventory_id", c)
	if err != nil {
		return
	}

	query, args, _ := squirrel.Select("*").
		From("project__inventory").
		Where("project_id=?", project.ID).
		Where("id=?", inventoryID).
		ToSql()

	var inventory models.Inventory
	if err := database.Mysql.SelectOne(&inventory, query, args...); err != nil {
		if err == sql.ErrNoRows {
			c.AbortWithStatus(404)
			return
		}

		panic(err)
	}

	c.Set("inventory", inventory)
	c.Next()
}
Ejemplo n.º 9
0
func EnvironmentMiddleware(c *gin.Context) {
	project := c.MustGet("project").(models.Project)
	envID, err := util.GetIntParam("environment_id", c)
	if err != nil {
		return
	}

	query, args, _ := squirrel.Select("*").
		From("project__environment").
		Where("project_id=?", project.ID).
		Where("id=?", envID).
		ToSql()

	var env models.Environment
	if err := database.Mysql.SelectOne(&env, query, args...); err != nil {
		if err == sql.ErrNoRows {
			c.AbortWithStatus(404)
			return
		}

		panic(err)
	}

	c.Set("environment", env)
	c.Next()
}
Ejemplo n.º 10
0
// http://blog.mongodb.org/post/80579086742/running-mongodb-queries-concurrently-with-go
// Request a socket connection from the session to process our query.
// Close the session when the goroutine exits and put the connection
// back
// into the pool.
func (session *DatabaseSession) Database(c *gin.Context) {
	s := session.Clone()
	defer s.Close()

	c.Set("mongo_session", s.DB(session.databaseName))
	c.Next()
}
Ejemplo n.º 11
0
func Error(c *gin.Context) {
	c.Next()
	id, _ := c.Get("request_id")

	// Log out every error we have encoutered (which in most cases is just 1)
	for _, ginError := range c.Errors {
		actError := ginError.Err
		log.InfoFields("Request error", log.Fields{
			"request_id": id,
			"body":       formatErrorBody(actError.Error()),
		})
	}

	// Grab the last error and use that as the error we return to the client
	if len(c.Errors) > 0 {
		clientError := c.Errors[len(c.Errors)-1].Err

		// If it isn't an errors.Http type, assume it is a 500 and return that
		switch clientError.(type) {
		case errors.Http:
			break
		default:
			if c.IsAborted() {
				clientError = errors.NewHttp(c.Writer.Status(), formatErrorBody(clientError.Error()))
			} else {
				clientError = errors.NewHttp(http.StatusInternalServerError, "Unrecognized error")
			}
		}

		// Now write the error to the client
		c.JSON(clientError.(errors.Http).Code, clientError)
	}

}
Ejemplo n.º 12
0
Archivo: api.go Proyecto: schollz/find
func migrateDatabase(c *gin.Context) {
	fromDB := strings.ToLower(c.DefaultQuery("from", "noneasdf"))
	toDB := strings.ToLower(c.DefaultQuery("to", "noneasdf"))
	Debug.Printf("Migrating %s to %s.\n", fromDB, toDB)
	if !exists(path.Join(RuntimeArgs.SourcePath, fromDB+".db")) {
		c.JSON(http.StatusOK, gin.H{"success": false, "message": "Can't migrate from " + fromDB + ", it does not exist."})
		return
	}
	if !exists(path.Join(RuntimeArgs.SourcePath, toDB)) {
		CopyFile(path.Join(RuntimeArgs.SourcePath, fromDB+".db"), path.Join(RuntimeArgs.SourcePath, toDB+".db"))
	} else {
		db, err := bolt.Open(path.Join(RuntimeArgs.SourcePath, fromDB+".db"), 0664, nil)
		if err != nil {
			log.Fatal(err)
		}
		defer db.Close()

		db2, err := bolt.Open(path.Join(RuntimeArgs.SourcePath, toDB+".db"), 0664, nil)
		if err != nil {
			log.Fatal(err)
		}
		defer db2.Close()

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

			db.View(func(tx *bolt.Tx) error {
				b := tx.Bucket([]byte("fingerprints"))
				c := b.Cursor()
				for k, v := c.First(); k != nil; k, v = c.Next() {
					bucket.Put(k, v)
				}
				return nil
			})
			return nil
		})

		db2.Update(func(tx *bolt.Tx) error {
			bucket, err := tx.CreateBucketIfNotExists([]byte("fingerprints-track"))
			if err != nil {
				return fmt.Errorf("create bucket: %s", err)
			}

			db.View(func(tx *bolt.Tx) error {
				b := tx.Bucket([]byte("fingerprints-track"))
				c := b.Cursor()
				for k, v := c.First(); k != nil; k, v = c.Next() {
					bucket.Put(k, v)
				}
				return nil
			})
			return nil
		})
	}
	c.JSON(http.StatusOK, gin.H{"success": true, "message": "Successfully migrated " + fromDB + " to " + toDB})
}
Ejemplo n.º 13
0
// Connect middleware clones the database session for each request and
// makes the `db` object available for each handler
func Connect(c *gin.Context) {
	s := db.Session.Clone()

	defer s.Close()

	c.Set("db", s.DB(db.Mongo.Database))
	c.Next()
}
Ejemplo n.º 14
0
func renderError(c *gin.Context) {
	c.Next()
	errs := c.Errors.Errors()
	if len(errs) > 0 {
		u := ghauth.User(c)
		render(c, "error", gin.H{"User": u, "Errors": errs})
	}
}
Ejemplo n.º 15
0
func (C *DriverController) IsAreaParam(c *gin.Context) {
	//Bug do httprouter
	if c.Param(URI_PARAM) == "inArea" {
		c.Next()
	} else {
		c.AbortWithStatus(http.StatusNotFound)
	}
}
Ejemplo n.º 16
0
// Log errors
func Errors(c *gin.Context) {
	c.Next()
	for _, err := range c.Errors {
		logrus.WithFields(logrus.Fields{
			"error": err,
		}).Error("handlers: Handler error")
	}
}
Ejemplo n.º 17
0
func myLoger(c *gin.Context) {
	c.Next()
	log.Printf("RemoteAddr: %s, HttpCode: %d, BodySize: %d\n",
		c.Request.RemoteAddr, c.Writer.Status(), c.Writer.Size())
	if c.Writer.Status() == 500 {
		c.Writer.WriteHeader(200)
	}
}
Ejemplo n.º 18
0
func handleUnrouted(c *gin.Context) {
	c.Next()
	if c.HandlerName() == "main.handleUnrouted" {
		c.JSON(http.StatusNotFound, gin.H{
			"error":   http.StatusNotFound,
			"message": "Route not found.",
		})
	}
}
Ejemplo n.º 19
0
func (ss *schedulerService) ValidateID(c *gin.Context) {
	userID, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid User Id"})
		c.Abort()
		return
	}
	c.Set("id", userID)
	c.Next()
}
Ejemplo n.º 20
0
func humanMiddleware(c *gin.Context) {
	s := c.MustGet("store").(*store)
	h := c.MustGet("human").(bool)
	y, w := getISOWeek(c)
	if !h && !s.HasWeekStrict(y, w) {
		c.AbortWithStatus(http.StatusNotFound)
	} else {
		c.Next()
	}
}
Ejemplo n.º 21
0
// ErrorHandler is a middleware to handle errors encountered during requests
func ErrorHandler(c *gin.Context) {
	c.Next()

	// TODO: Handle it in a better way
	if len(c.Errors) > 0 {
		c.HTML(http.StatusBadRequest, "400", gin.H{
			"errors": c.Errors,
		})
	}
}
Ejemplo n.º 22
0
func UserMust(c *gin.Context) {
	user := User(c)
	switch {
	case user == nil:
		c.AbortWithStatus(http.StatusUnauthorized)
		// c.HTML(http.StatusUnauthorized, "401.html", gin.H{})
	default:
		c.Next()
	}
}
Ejemplo n.º 23
0
// RequestID tag the current request with an ID & add a response X-Request-Id header.
func RequestID(context *gin.Context) {
	// Generate an ID for this request.
	id := uuid.NewV4().String()

	// Bind request ID to context.
	context.Set("request_id", id)
	context.Writer.Header().Set("X-Request-ID", id)

	// Yield to other middleware handlers.
	context.Next()
}
Ejemplo n.º 24
0
// Options is a middleware function that appends headers
// for options requests and aborts then exits the middleware
// chain and ends the request.
func Options(c *gin.Context) {
	if c.Request.Method != "OPTIONS" {
		c.Next()
	} else {
		c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
		c.Header("Access-Control-Allow-Headers", "Authorization")
		c.Header("Allow", "HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS")
		c.Header("Content-Type", "application/json")
		c.AbortWithStatus(200)
	}
}
Ejemplo n.º 25
0
func SystemAdminCheck(c *gin.Context) {
	if token := c.Request.Header.Get(XAuthToken); token == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
		c.Abort()
		return
	}

	//TODO : System User Check

	c.Next()
}
Ejemplo n.º 26
0
func staticHandler(c *gin.Context) {
	path := c.Request.URL.Path[1:]
	if path == "" {
		path = "index.html"
	}
	if buf, err := Asset(path); err == nil {
		mimeType := mime.TypeByExtension(filepath.Ext(path))
		c.Data(200, mimeType, buf)
	} else {
		c.Next()
	}
}
Ejemplo n.º 27
0
func DummyMiddleware(c *gin.Context) {
	c.Set("hello", "world") // mapping obj using map
	uri := c.Request.RequestURI
	if uri == "/dummy2" { // abort the request using middleware
		resp := map[string]string{"figo": "xu"}
		c.JSON(200, resp)
		c.Abort()
		return
	}
	log.Println("Im a dummy!")
	c.Next()
}
Ejemplo n.º 28
0
func validateRequest(c *gin.Context) {
	var err error
	// Get token and user from request header
	t := c.Request.Header.Get("X-Access-Token")
	user := c.Request.Header.Get("X-Key")

	// If empty return error
	if t == "" || user == "" {
		c.AbortWithStatus(401)
		c.JSON(401, "Invalid Token or Key")
		return
	}

	// Decode the token using the original key
	token, err := jwt.Parse(t, func(token *jwt.Token) (interface{}, error) {
		return key, nil
	})

	// Token is not valid or there was error when decoding
	if err != nil || !token.Valid {
		c.AbortWithStatus(401)
		c.JSON(401, "Invalid Token or Key")
		return
	}

	// Token seems valid, but there was unexpected error
	if err != nil && token.Valid {
		c.AbortWithStatus(500)
		c.JSON(500, "Oops something went wrong")
		return
	}

	// Validate user and return error if user not found
	_, err = checkUser(user)

	// if user does not exist, return JSON error
	if err != nil {
		c.AbortWithStatus(401)
		c.JSON(401, "Invalid User")
		return
	}

	// Check if token is expired
	expireIn := int64(reflect.ValueOf(token.Claims["exp"]).Float())

	if expired(expireIn) {
		c.AbortWithStatus(400)
		c.JSON(400, "Token Expired")
		return
	}

	c.Next()
}
Ejemplo n.º 29
0
// RecoverHandlerJson is a HTTP request middleware that captures panic errors
// and returns it as HTTP JSON response.
func RecoverHandlerJson(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			jerr := web.NewJSONError().
				FromError(fmt.Errorf("panic: %+v", err)).
				Build()
			c.JSON(jerr.Status, jerr)
		}
	}()

	c.Next()
}
Ejemplo n.º 30
0
// Recover panics
func Recovery(c *gin.Context) {
	defer func() {
		if r := recover(); r != nil {
			logrus.WithFields(logrus.Fields{
				"error": errors.New(fmt.Sprintf("%s", r)),
			}).Error("handlers: Handler panic")
			c.Writer.WriteHeader(http.StatusInternalServerError)
		}
	}()

	c.Next()
}