package controllers

import (
	"exhibitionCentre/base"
	"exhibitionCentre/logging"
	"exhibitionCentre/utils"
	"net/http"
	"time"
)

func AliyunSts(router *base.Router) (int, []byte) {
	// 鉴权，鉴权失败则需重新登陆
	jwt, authorized := Authenticate(router)
	if !authorized {
		logging.Log.Error("获取sts令牌失败")
		return 0, nil
	}
	tokenInfo := utils.GenerateStsToken(jwt.Email)
	if tokenInfo == nil {
		return 403, utils.SerializeErrorData("获取上传权限失败")
	}
	return 200, utils.Serialize(tokenInfo)
}

func SaveToken(token string, router *base.Router) {
	cookie := http.Cookie{Name: "token", Value: token, HttpOnly: true, Secure: false, Path: "/", Expires: time.Now().Add(30 * 24 * time.Hour), MaxAge: 60 * 60 * 24 * 30}
	http.SetCookie(router.Writer, &cookie)
}

func DeleteToken(router *base.Router) {
	cookie := http.Cookie{Name: "token", Value: "", HttpOnly: true, Secure: false, Path: "/", Expires: time.Now().Add(30 * 24 * time.Hour), MaxAge: 60 * 60 * 24 * 30}
	http.SetCookie(router.Writer, &cookie)
}

func Authenticate(router *base.Router) (*utils.JWTCustomClaims, bool) {
	token, err := router.Req.Cookie("token")
	if err != nil {
		Relogin(router)
		return nil, false
	}
	jwt := utils.ParseJWT(token.Value)
	if jwt == nil {
		Relogin(router)
		return nil, false
	}
	if err := jwt.Valid(); err != nil {
		Relogin(router)
		return nil, false
	}
	return jwt, true
}

func LoginAuthenticate(router *base.Router) (string, bool) {
	token, err := router.Req.Cookie("token")
	if err != nil {
		return "", false
	}
	jwt := utils.ParseJWT(token.Value)
	if jwt == nil {
		return "", false
	}
	if err := jwt.Valid(); err != nil {
		return "", false
	}
	return jwt.Email, true
}

func Relogin(router *base.Router) {
	DeleteToken(router)
	Redirect(router, "/user/login")
}

func Redirect(router *base.Router, path string) {
	http.Redirect(router.Writer, router.Req, path, http.StatusFound)
}
