package middleware

import (
	"encoding/json"

	"git.trj.tw/golang/go-gallery/modules/context"
	"git.trj.tw/golang/go-gallery/modules/memstore"
)

// VerifyToken -
func VerifyToken(c *context.Context) {
	token := c.GetHeader("X-Auth-Token")

	if len(token) == 0 {
		c.CustomRes("Forbidden", nil)
		return
	}

	str, err := memstore.RedisGet("golang", token)
	if err != nil || len(str) == 0 {
		c.CustomRes("Forbidden", "token invaild")
		return
	}

	jsonData := make(map[string]interface{})
	err = json.Unmarshal([]byte(str), &jsonData)
	if err != nil {
		c.ServerError(nil)
	}

	c.Set("token", jsonData)

	c.Next()
}
