package main

import (
	"crypto/tls"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/plugins/cors"
	"github.com/coreos/go-oidc"
	"k8s-console/models"
	_ "k8s-console/routers"
	"log"
	"net/http"
	"strings"
	netcontext "golang.org/x/net/context"
)

func main() {
	if beego.BConfig.RunMode == "dev" {
		beego.BConfig.WebConfig.DirectoryIndex = true
		beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
	}

	//日志
	beego.SetLogFuncCall(true)
	beego.SetLevel(beego.LevelInformational)
	//beego.SetLogger("file", `{"filename":"logs/k8s-console.log", "daliy":false, "maxdays": 30}`)

	//设置静态页面
	beego.SetStaticPath("/", "/go/frontend/dist/index.html")
	beego.BConfig.WebConfig.StaticDir["/favicon.ico"] = "/go/frontend/dist/favicon.ico"
	beego.BConfig.WebConfig.StaticDir["/static"] = "/go/frontend/dist/static"
	beego.BConfig.WebConfig.StaticDir["/static/*"] = "/go/frontend/dist/static/*"

	//跨域设置
	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type", "x-token"},
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		AllowCredentials: true,
	}))
	beego.InsertFilter("*", beego.AfterExec, beego.FilterFunc(func(c *context.Context) {
		c.Output.Header("Access-Control-Allow-Origin", "*")
	}))

	//获取泛域名
	_, _, appExtensiveDomain, err := models.GetHarborIngressAndPwd("harbor", true)
	if err != nil {
		logs.Error("获取泛域名失败：", err.Error())
		return
	}

	ctx := netcontext.Background()
	http.DefaultClient.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
	issuerURL := beego.AppConfig.String("dexUrl") + "." + appExtensiveDomain
	provider, err := oidc.NewProvider(ctx, issuerURL)
	if err != nil {
		log.Fatal(err)
	}
	oidcConfig := &oidc.Config{
		ClientID:          beego.AppConfig.String("clientID"),
		SkipClientIDCheck: true,
	}
	verifier := provider.Verifier(oidcConfig)

	//语言参数值和token校验
	beego.InsertFilter("*", beego.BeforeExec, beego.FilterFunc(func(c *context.Context) {
		c.Output.Header("Access-Control-Allow-Origin", "*")
		query := c.Request.URL.Query().Encode()

		var filterUrls = [...]string{
			"/k8s-console/v1/oidc/authCode",
			"/k8s-console/v1/common/getClusterConfigInfo",
			"/health",
			"/k8s-console/v1/board/showAllData/1",
			"/k8s-console/v1/common/getUserAllNameSpaces",
			"/k8s-console/v1/pod/tailPodLog",
			"/terminalWebSocket",
		}

		//屏蔽拦截解析authcode请求
		isExitsUrl := false
		for _, urlStr := range filterUrls {
			//匹配请求地址或者以请求地址开头的
			if urlStr == c.Request.URL.Path || strings.HasPrefix(c.Request.URL.Path, urlStr) {
				isExitsUrl = true
				break
			}
		}

		//isExitsUrl = true

		if !isExitsUrl {
			//校验token是否失效
			logs.Debug("判断请求header参数是否包含token")
			rawIDToken := c.Request.Header.Get("X-Token")
			if rawIDToken != "" {

				// Parse and verify ID Token payload.
				_, err := verifier.Verify(ctx, rawIDToken)
				if err != nil {
					logs.Error("请求路径", c.Request.URL.Path, "token无效，跳转oidc登录页面", err.Error())
					c.Output.Body([]byte(`{"status":500,"message":"token无效，跳转oidc登录页面"}`))
					return
				}

			} else {
				logs.Error("请求路径", c.Request.URL.Path, "token不存在，跳转oidc登录页面")
				c.Output.Body([]byte(`{"status":500,"message":"token不存在，跳转oidc登录页面"}`))
				return
			}
		}

		if strings.Contains(query, "lang") {
			lang := c.Request.URL.Query().Get("lang")
			logs.GetLogger("info").Println("语言: ", lang)
			if lang != "" {
				if lang != "zh" && lang != "en" {
					m := map[string]interface{}{"status": 200, "message": "语言参数值不正确"}
					c.Output.JSON(m, false, false)
					return
				}
			} else {
				c.Request.URL.Query().Set("lang", "zh")
				//lang = "zh"
			}
			//校验license是否失效
			//verifyLicenseValidRes := controllers.VerifyLicenseValid(lang)
			//logs.GetLogger("info").Println(verifyLicenseValidRes)
			//if verifyLicenseValidRes.Status == 300 {
			//	logs.GetLogger("error").Printf("校验license是否失效: %s", verifyLicenseValidRes.Message)
			//	c.Output.JSON(verifyLicenseValidRes, false, false)
			//	return
			//}
		}
	}))
	beego.Run()
}
