2017-07-16 17:14:21 +02:00
package middlewares
2017-06-28 13:42:38 +02:00
import (
"net/http"
2017-07-13 18:05:53 +02:00
"github.com/NyaaPantsu/nyaa/config"
2017-07-16 17:14:21 +02:00
"github.com/NyaaPantsu/nyaa/controllers/router"
2017-07-16 15:35:24 +02:00
"github.com/NyaaPantsu/nyaa/templates"
2017-07-13 18:05:53 +02:00
"github.com/NyaaPantsu/nyaa/utils/log"
msg "github.com/NyaaPantsu/nyaa/utils/messages"
2017-06-28 13:42:38 +02:00
"github.com/gin-gonic/gin"
)
2017-07-23 07:46:29 +02:00
// ErrorMiddleware for managing errors on status
2017-07-16 17:14:21 +02:00
func ErrorMiddleware ( ) gin . HandlerFunc {
2017-06-28 13:42:38 +02:00
return func ( c * gin . Context ) {
c . Next ( )
2017-07-13 18:05:53 +02:00
if config . Get ( ) . Environment == "DEVELOPMENT" {
messages := msg . GetMessages ( c )
if messages . HasErrors ( ) {
log . Errorf ( "Request has errors: %v" , messages . GetAllErrors ( ) )
}
}
2017-07-04 01:15:43 +02:00
if c . Writer . Status ( ) != http . StatusOK && c . Writer . Size ( ) <= 0 {
2017-07-09 14:53:52 +02:00
if c . ContentType ( ) == "application/json" {
2017-07-13 18:05:53 +02:00
messages := msg . GetMessages ( c )
messages . AddErrorT ( "errors" , "404_not_found" )
c . JSON ( c . Writer . Status ( ) , messages . GetAllErrors ( ) )
2017-07-09 14:53:52 +02:00
return
}
2017-07-16 15:35:24 +02:00
templates . HttpError ( c , c . Writer . Status ( ) )
2017-06-28 13:42:38 +02:00
}
}
}
2017-07-16 17:14:21 +02:00
// ModMiddleware Make sure the user is a moderator, otherwise return forbidden
func ModMiddleware ( ) gin . HandlerFunc {
2017-06-28 13:42:38 +02:00
return func ( c * gin . Context ) {
2017-07-16 17:14:21 +02:00
currentUser := router . GetUser ( c )
2017-07-02 23:53:23 +02:00
if ! currentUser . HasAdmin ( ) {
2017-06-28 13:42:38 +02:00
NotFoundHandler ( c )
}
c . Next ( )
}
}
2017-07-05 14:40:05 +02:00
2017-07-05 15:17:59 +02:00
func pprofHandler ( handler http . HandlerFunc ) gin . HandlerFunc {
2017-07-05 14:40:05 +02:00
return func ( c * gin . Context ) {
2017-07-16 17:14:21 +02:00
currentUser := router . GetUser ( c )
2017-07-05 15:17:59 +02:00
if currentUser . HasAdmin ( ) {
handler . ServeHTTP ( c . Writer , c . Request )
} else {
2017-07-16 15:35:24 +02:00
templates . HttpError ( c , http . StatusNotFound )
2017-07-05 15:17:59 +02:00
}
2017-07-05 14:40:05 +02:00
}
}