package middleware

import (
	"gd_management_gateway/errors"
	"fmt"

	"gd_management_gateway/common.in/jsonrpc2"
	dsignal "gd_management_gateway/common.in/signal"
	"gd_management_gateway/common.in/task"
	"gd_management_gateway/common.in/utils"
	"github.com/astaxie/beego/context"
)

type (
	JwtRequest struct {
		Token string `json:"token" required:"true" in:"header"`
		Uid   string `json:"uid"  required:"true" in:"header"`
	}
)

func JwtAuth(ctx *context.Context) {
	var req JwtRequest
	getParamsTask := func() error {
		if dsignal.ExitRecieved == true {
			return jsonrpc2.NewJsonError(10003, "服务停止中")
		}
		req.Uid = ctx.Input.Header("uid")
		req.Token = ctx.Input.Header("token")
		if req.Uid == "" || req.Token == "" {
			return errors.ArgsError
		}
		return nil
	}
	handleTokenCheck := func() error {
		uid, _, err := utils.ParseToken(req.Token)
		if err != nil {
			return err
		}
		if fmt.Sprintf("%d", uid) != req.Uid {
			return errors.UserTokenillegality
		}

		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   ctx,
		LogID: ""}, ctx,
		getParamsTask, handleTokenCheck,
	)
}
