refactor(api): move authentication into a middleware

This commit is contained in:
2025-01-06 20:17:07 +03:00
parent 521e140881
commit 55986bab36
3 changed files with 30 additions and 49 deletions
+16
View File
@@ -1,8 +1,12 @@
package api
import (
"net/http"
"strconv"
"strings"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5/pgconn"
)
@@ -20,3 +24,15 @@ func HandleDBError(err error) (int, string) {
return 400, pgErr.Message
}
}
func MiddlewareAuth(c *gin.Context) {
session := sessions.Default(c)
user_id, ok := session.Get("user_id").(string)
if !ok && strings.HasPrefix(c.Request.URL.Path, "/api") {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Ты это, залогинься сначала что ли, а то чё как крыса"})
return
}
c.Set("authorized", ok)
c.Set("user_id", user_id)
c.Next()
}