package router import ( "fmt" "iothomepage/authmod" "log" "net/http" "strings" "github.com/gin-gonic/gin" ) func NewRouter() *gin.Engine { assetEngine := gin.New() assetEngine.Static("/home", "./www") r := gin.New() reverseProxyEngine := gin.New() reverseProxyEngine.Any("/edit/*any", reverseProxyHandle) authEngine := gin.New() authv1 := authEngine.Group("auth") { authv1.GET("/", authStart) authv1.GET("/oidc.callback", authCallback) } r.Any("/*any", func(c *gin.Context) { defer handleError(c) path := c.Param("any") if strings.HasPrefix(path, "/home") { assetEngine.HandleContext(c) return } else if strings.HasPrefix(path, "/auth") { c.Writer.Header().Set("Cache-Control", "no-cache, private, max-age=0") c.Writer.Header().Set("Pragma", "no-cache") authEngine.HandleContext(c) return } else if path == "/" && len(c.Request.URL.Query()) == 0 { c.Redirect(http.StatusPermanentRedirect, "/home") return } if checkAuthority(c) { if strings.HasPrefix(path, "/edit") { reverseProxyEngine.HandleContext(c) } else { reverseProxyHandle(c) } } else { if strings.HasPrefix(path, "/edit") { // redirect to login c.Writer.Header().Set("Cache-Control", "no-cache, private, max-age=0") c.Writer.Header().Set("Pragma", "no-cache") c.Redirect(http.StatusPermanentRedirect, "/auth") } else { c.Status(http.StatusBadRequest) } } }) return r } func checkAuthority(c *gin.Context) bool { editAuth, err := c.Cookie("__edit_access_token_") if err != nil { fmt.Println(err) return false } _, err = authmod.ParseJWTwithClaims(editAuth) return err == nil } func handleError(c *gin.Context) { if r := recover(); r != nil { log.Println(r) c.String(http.StatusBadRequest, r.(error).Error()) } }