99 lines
2.4 KiB
Go
99 lines
2.4 KiB
Go
package controllers
|
|
|
|
import (
|
|
"fmt"
|
|
"main/mvc/models"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func Logger(s *models.Site) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
go func() {
|
|
logEntry := fmt.Sprintf("%s | %d | %s | %s | %s\n",
|
|
time.Now().Format("2006/01/02 - 15:04:05"),
|
|
c.Writer.Status(),
|
|
c.ClientIP(),
|
|
c.Request.Method,
|
|
c.Request.URL.Path,
|
|
)
|
|
fmt.Print(logEntry)
|
|
s.Lock()
|
|
s.LogEntries = append(s.LogEntries, logEntry)
|
|
s.Unlock()
|
|
}()
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func AuthMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if AccessLvl(c) == 0 {
|
|
c.Redirect(http.StatusFound, "/index/1?Нет доступа")
|
|
// гарантирует что цепочка обработчиков оборвется
|
|
// после выполнения этого обработчика
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// Валидация страницы
|
|
func PageValidationMiddleware(s *models.Site) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
|
|
path := c.Request.URL.Path
|
|
|
|
tmplname := path[1 : strings.Index(path[1:], "/")+1]
|
|
pageNumber, err := strconv.Atoi(c.Param("id"))
|
|
|
|
// Проверка на ошибки при преобразовании id (переполнение)
|
|
if err != nil {
|
|
c.Redirect(http.StatusFound, "/index/1?Нет доступа")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// Валидация pageNumber в зависимости от tmplname
|
|
switch tmplname {
|
|
case "post", "AJAXpost", "editpage", "AJAXeditpage":
|
|
if pageNumber > len(s.Posts) || pageNumber < 1 {
|
|
c.Redirect(http.StatusFound, "/index/1?Нет доступа")
|
|
c.Abort()
|
|
return
|
|
}
|
|
case "index", "AJAXindex":
|
|
if pageNumber > s.Posts.GetMaxPageNumber() || pageNumber < 1 {
|
|
c.Redirect(http.StatusFound, "/index/1?Нет доступа")
|
|
c.Abort()
|
|
return
|
|
}
|
|
case "search", "AJAXsearch":
|
|
searchSubstring := c.Query("search")
|
|
if searchSubstring == "" ||
|
|
pageNumber > s.Posts[0:s.Tags[searchSubstring]].GetMaxPageNumber() ||
|
|
pageNumber < 1 {
|
|
|
|
c.Redirect(http.StatusFound, "/index/1?Нет доступа")
|
|
c.Abort()
|
|
return
|
|
}
|
|
default:
|
|
if pageNumber != 1 {
|
|
c.Redirect(http.StatusFound, "/index/1?Нет доступа")
|
|
c.Abort()
|
|
return
|
|
}
|
|
}
|
|
|
|
c.Set("pageNumber", pageNumber)
|
|
// Продолжаем обработку запроса
|
|
c.Next()
|
|
}
|
|
}
|