package controllers

import (
	"strings"
	"wechat-conf/service/user"
	"wechat-conf/utils"

	"github.com/astaxie/beego"
)

const (
	SESSION_USER = "wechat-conf.user"
)

// auth 鉴权
func (c *BaseController) auth() {
	apiPrefix := beego.AppConfig.String("ApiPrefix")
	path := strings.TrimPrefix(c.Ctx.Request.URL.Path, apiPrefix)
	method := c.Ctx.Request.Method
	userID, _ := c.GetSession(SESSION_USER).(string)
	serv := user.NewUserServ(c.Context)

	code, err := serv.CheckUserRoute(userID, path, method)
	if err != nil {
		c.ResponseError(err, code)
	}

	if userID != "" {
		userDetail, err := serv.GetUserByID(userID)

		if err != nil {
			c.ResponseError(err)
		}

		if userDetail.UserId == "" {
			c.ResponseError(utils.LogError("用户不存在, 请重新登录"))
		}

		c.Context.Set("user", userDetail)
	}
}