Пример #1
0
func (ut *UserToken) GenToken(crypto *tkits.Crypto) (string, error) {
	bs := make([]byte, TokenLen)
	buf := bytes.NewBuffer(bs)

	// flag
	buf.WriteByte(byte(ut.Flag))

	// uid
	binary.Write(buf, binary.BigEndian, ut.Uid)

	// client ip
	ip := net.ParseIP(ut.ClientIP)
	buf.Write([]byte(ip))

	// current time
	binary.Write(buf, binary.BigEndian, time.Now().Unix())

	// current time
	binary.Write(buf, binary.BigEndian, ut.Expire)

	// encrypt
	if t, err := crypto.Encrypt(buf.Bytes()); err != nil {
		return "", err
	} else {
		return base64.URLEncoding.EncodeToString(t), nil
	}
}
Пример #2
0
func (ut *UserToken) DecodeToken(crypto *tkits.Crypto, token string) bool {
	bs, err := base64.URLEncoding.DecodeString(token)
	if err != nil {
		return false
	}

	// decrypt
	var tbs []byte
	tbs, err = crypto.Decrypt(bs)
	if err != nil {
		return false
	}

	// check the len
	if len(tbs) != TokenLen {
		return false
	}

	ut.Flag = TokenFlag(tbs[0])
	// remain bytes
	buf := bytes.NewReader(tbs[1:])

	// read uid
	if err := binary.Read(buf, binary.BigEndian, &ut.Uid); err != nil {
		return false
	}

	// ip
	var ip net.IP
	buf.Read([]byte(ip))
	ut.ClientIP = ip.String()

	// gen time
	if err := binary.Read(buf, binary.BigEndian, &ut.GenTime); err != nil {
		return false
	}

	// gen time
	if err := binary.Read(buf, binary.BigEndian, &ut.Expire); err != nil {
		return false
	}

	return true
}