package middleware

import (
	"fmt"
	"iris-demo/library/casbin"
	"iris-demo/library/logger"
	"iris-demo/library/msg"
	"iris-demo/library/response"

	"github.com/kataras/iris/v12"
)

func MiddlewareBefore(ctx iris.Context) {
	userName := ctx.Values().GetString("userName")
	path := ctx.Request().URL.Path
	method := ctx.Request().Method

	role := "admin"
	// 增加角色
	casbin.AddGroupingPolicy(userName, role)
	// 删除用户角色
	// casbin.RemoveGroupingPolicy(userName, role)
	// 角色授权Policy
	casbin.AddPolicy(role, path, method) // 增加Policy保持到DB
	// casbin.RemovePolicy(role, path, method) // 删除Policy保持到DB
	// casbin.ClearPolicy() // 临时删除Policy，但不动DB

	ok, _ := casbin.Enforce(userName, path, method)
	// logger.Info(ok)
	if !ok {
		logger.Error(fmt.Sprintf("PermissionError: %v %v %v", userName, path, method))
		response.JsonExit(ctx, msg.PermissionError, "权限错误")
		ctx.StopExecution()
	}

	// EG
	/* receiveTemplate := "path: %v type: %v params: %v post: %v"
	logger.Info(fmt.Sprintf(receiveTemplate,
		ctx.Request().URL.Path,
		ctx.Request().Method,
		ctx.URLParam("name"),
		ctx.PostValue("name"))) */
	// TO DO SOMETHING BEFORE
	ctx.Next()
}
