// 中间件模块-检查是否已经登录
// 秒寻科技
// 2024-01-10
// 周涛

package islogin

import (
	"ipsomc/core/dao/redis/redisapi"
	"ipsomc/core/dao/redis/redismodel"
	"ipsomc/core/gin/resp"
	"ipsomc/util"

	"github.com/gin-gonic/gin"
)

// 检查PC端用户是否已登录
func PcIsLogin() func(c *gin.Context) {
	return func(c *gin.Context) {
		redisOperator := new(redismodel.RedisOperator) //操作员缓存模型
		var redisObj redisapi.RedisApi
		token := c.Request.Header.Get("token") //获取请求参数中的token字符

		//已经登录
		if len(token) > 0 {
			//基于token获得操作员缓存模型
			if err := redisObj.GetModelData(token, redisOperator); err != nil {
				resp.RespTokenExpire(c, "登录已过期，请重新登录")
				c.Abort()
			} else { //重新设置token过期时间
				myViper := util.GetViper()
				expireTime := myViper.GetInt("token.pc_expire")
				if expireTime <= 0 {
					expireTime = 10 //10分钟
				}

				redisObj.SetExpireTime(token, uint8(expireTime))
				c.Set("mycontext", redisOperator) //设置自定义键
				c.Next()
			}
		} else { //还未登录
			resp.RespFail(c, "请先登录")
			c.Abort()
		}
	}
}

// 检查移动端用户是否已登录
func MobileIsLogin() func(c *gin.Context) {
	return func(c *gin.Context) {
		modelRedis := new(redismodel.RedisUserMobile)
		var redisObj redisapi.RedisApi
		token := c.Request.Header.Get("Authorization") //获取请求参数中的token字符

		//已经登录
		if len(token) > 0 {
			if err := redisObj.GetModelData(token, modelRedis); err != nil {
				resp.RespTokenExpire(c, "登录已过期，请重新登录")
				c.Abort()
			} else { //重新设置token过期时间
				myViper := util.GetViper()
				expireTime := myViper.GetInt("token.mobile_expire")
				if expireTime <= 0 {
					expireTime = 60 //60分钟
				}

				redisObj.SetExpireTime(token, uint8(expireTime))
				c.Set("mycontext", modelRedis) //设置自定义键
				c.Next()
			}
		} else { //还未登录
			resp.RespFail(c, "请先登录")
			c.Abort()
		}
	}
}
