homepage/webserver/router/route.go

90 lines
1.8 KiB
Go
Raw Normal View History

2022-12-26 01:20:43 +00:00
package router
import (
"fmt"
2022-12-26 05:48:30 +00:00
"iothomepage/authmod"
2022-12-26 01:20:43 +00:00
"log"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
func NewRouter() *gin.Engine {
assetEngine := gin.New()
2022-12-26 04:36:19 +00:00
assetEngine.Static("/home", "./www")
2022-12-26 01:20:43 +00:00
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")
2022-12-26 05:48:30 +00:00
if strings.HasPrefix(path, "/dashboard") {
2022-12-26 01:20:43 +00:00
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
}
2022-12-26 05:48:30 +00:00
claims, err := authmod.ParseJWTwithClaims(editAuth)
if err != nil {
return false
}
fmt.Println(claims.UserInfo)
2022-12-26 01:20:43 +00:00
return true
}
func handleError(c *gin.Context) {
if r := recover(); r != nil {
log.Println(r)
c.String(http.StatusBadRequest, r.(error).Error())
}
}