refactor(api): move authentication into a middleware
This commit is contained in:
@@ -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()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user