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, }) }
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) } }
func AuthCheck(c *gin.Context) { id, _ := c.Get("request_id") log.InfoFields("Checking auth token", log.Fields{ "request_id": id, }) token := c.Query("token") if token == "" { tokenHeaders := c.Request.Header["Token"] if len(tokenHeaders) == 0 { c.AbortWithError(http.StatusUnauthorized, fmt.Errorf("No notion access token provided")) return } else { token = tokenHeaders[0] } } in, user, err := db.GetUserByToken(token) if err != nil { c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("Internal server error")) return } if !in { c.AbortWithError(http.StatusUnauthorized, fmt.Errorf("Notion access token provided is not currently valid")) return } c.Set("request_user_id", user.Id) }
func AccessControl(c *gin.Context) { id, _ := c.Get("request_id") log.InfoFields("Setting access control headers", log.Fields{ "request_id": id, }) c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH") c.Header("Access-Control-Allow-Headers", "*") c.Header("Access-Control-Allow-Credentials", "true") }