refactor(web): make a separate auth middlewares for server

also slightly change api auth middleware
This commit is contained in:
Masahiko AMANO 2025-01-07 04:32:49 +03:00
parent 8b417dc623
commit 2228dc5f14
4 changed files with 20 additions and 10 deletions

View File

@ -32,7 +32,6 @@ func MiddlewareAuth(c *gin.Context) {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Ты это, залогинься сначала что ли, а то чё как крыса"}) c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Ты это, залогинься сначала что ли, а то чё как крыса"})
return return
} }
c.Set("authorized", ok)
c.Set("user_id", user_id) c.Set("user_id", user_id)
c.Next() c.Next()
} }

View File

@ -7,8 +7,8 @@ import (
) )
func root(c *gin.Context) { func root(c *gin.Context) {
authorized := c.GetBool("authorized") user_id := c.GetString("user_id")
if authorized { if user_id != "" {
c.Redirect(http.StatusSeeOther, "/quotes") c.Redirect(http.StatusSeeOther, "/quotes")
} else { } else {
c.HTML(http.StatusOK, "auth.html", nil) c.HTML(http.StatusOK, "auth.html", nil)
@ -16,10 +16,5 @@ func root(c *gin.Context) {
} }
func quotes(c *gin.Context) { func quotes(c *gin.Context) {
authorized := c.GetBool("authorized")
if authorized {
c.HTML(http.StatusOK, "quotes.html", nil) c.HTML(http.StatusOK, "quotes.html", nil)
} else {
c.Redirect(http.StatusSeeOther, "/")
}
} }

View File

@ -20,7 +20,7 @@ func Serve(addr string) {
r.Static("/static", "./static") r.Static("/static", "./static")
r.GET("/", api.MiddlewareAuth, root) r.GET("/", api.MiddlewareAuth, root)
r.GET("/quotes", api.MiddlewareAuth, quotes) r.GET("/quotes", api.MiddlewareAuth, middlewareAuth, quotes)
r.Run(addr) r.Run(addr)
} }

16
web/server/utils.go Normal file
View File

@ -0,0 +1,16 @@
package server
import (
"net/http"
"github.com/gin-gonic/gin"
)
func middlewareAuth(c *gin.Context) {
user_id := c.GetString("user_id")
if user_id == "" {
c.Redirect(http.StatusSeeOther, "/")
return
}
c.Next()
}