package Account import ( "Cold_Api/conf" "fmt" "github.com/astaxie/beego/cache" _ "github.com/astaxie/beego/cache/redis" "github.com/beego/beego/v2/core/logs" uuid "github.com/satori/go.uuid" "log" "strconv" "strings" "time" ) var redisCache_Tokey cache.Cache var Admin_r *Admin func init() { //注册模型 //orm.RegisterModel(new(Tokey)) config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`, "redis_User_Tokey", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password) fmt.Println(config) var err error redisCache_Tokey, err = cache.NewCache("redis", config) if err != nil || redisCache_Tokey == nil { errMsg := "failed to init redis" logs.Error(errMsg, err) panic(errMsg) } } // ---------------- Redis ------------------- // Redis_Set(m.T_sn,m) // Redis 更新缓存 func Add_Tokey_Set(Uuid string) string { var Tokey string for true { Tokey = uuid.NewV4().String() if !redisCache_Tokey.IsExist(Tokey) { break } fmt.Print("申请 TOKEY 重复!重新生成。", Tokey) } err := redisCache_Tokey.Put(Tokey, Uuid+"|0", 2*time.Hour) if err != nil { logs.Error("Add_Tokey_Set", err) } return Tokey } // if r,is :=Redis_Get(T_sn);is{ // return r,nil // } func Redis_Tokey_Get(Tokey string) (string, bool) { if len(Tokey) < 10 { return "", false } if redisCache_Tokey.IsExist(Tokey) { //println("找到key:",key) v := redisCache_Tokey.Get(Tokey) value := string(v.([]byte)) //这里的转换很重要,Get返回的是interface err := redisCache_Tokey.Put(Tokey, value, 2*time.Hour) // 重新计次 if err != nil { logs.Error("Redis_Tokey_Get", err) } return value, true } //println("没有 找到key:",key) return "", false } func Redis_Tokey_T_pid_Set(Tokey string, T_pid int) bool { if len(Tokey) < 10 { return false } if redisCache_Tokey.IsExist(Tokey) { //println("找到key:",key) v := redisCache_Tokey.Get(Tokey) value := string(v.([]byte)) //这里的转换很重要,Get返回的是interface T_uuid := strings.Split(value, "|")[0] err := redisCache_Tokey.Put(Tokey, T_uuid+"|"+strconv.Itoa(T_pid), 2*time.Hour) // 重新计次 if err != nil { logs.Error("Redis_Tokey_T_pid_Set", err) } return true } return false } func Redis_Tokey_T_pid_Get(Tokey string) (int, bool) { if len(Tokey) < 10 { return 0, false } if redisCache_Tokey.IsExist(Tokey) { //println("找到key:",key) v := redisCache_Tokey.Get(Tokey) value := string(v.([]byte)) //这里的转换很重要,Get返回的是interface T_pid, _ := strconv.Atoi(strings.Split(value, "|")[1]) return T_pid, true } return 0, false } // 登录验证 func Verification(GetCookie string, GetString string) (bool, Admin) { // 自适应 参数 User_tokey := GetCookie if len(User_tokey) == 0 { User_tokey = GetString } if len(User_tokey) == 0 { return false, Admin{} } tokey, is := Redis_Tokey_Get(User_tokey) T_uuid := strings.Split(tokey, "|")[0] if !is { return false, Admin{} } var err error admin_r, err := Read_Admin_ByUuid(T_uuid) if err != nil { return false, Admin{} } Admin_r = &admin_r log.Println("登录 Admin_name 为:", admin_r.T_name) return true, admin_r }