qrcode.go 1.9 KB
package domain

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"image/png"
	"time"

	"github.com/boombuler/barcode"
	"github.com/boombuler/barcode/qr"
	jwt "github.com/dgrijalva/jwt-go"
)

const (
	qrcodeTokenSecret string = "bbe35ad433dd8e67"
	qrcodeCodeExpire  int64  = 60 * 30 //15分钟过期
)

type QrcodeMessage struct {
	jwt.StandardClaims
	Id      string `json:"id"`
	Token   string `json:"token"`
	IsLogin bool   `json:"isLogin"`
	//用户id
	UserId     int64 `json:"userId"`
	UserBaseId int64 `json:"userBaseId"`
	// 账号
	Account string `json:"account"`
	// 公司id
	CompanyId int64 `json:"companyId"`
	// 组织id
	OrgId int64 `json:"orgId"`
}

func (qrmsg *QrcodeMessage) GenerateImageBase64() ([]byte, error) {
	nowTime := time.Now().Unix()
	qrmsg.StandardClaims = jwt.StandardClaims{
		NotBefore: nowTime,
		IssuedAt:  nowTime,
		ExpiresAt: nowTime + qrcodeCodeExpire,
		Issuer:    "allied_creation_gateway",
	}
	qrmsg.Id = fmt.Sprintf("%d", time.Now().UnixNano())
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, *qrmsg)
	str, err := token.SignedString([]byte(qrcodeTokenSecret))
	if err != nil {
		return nil, err
	}
	//初始化数据
	qrmsg.Token = str
	qrmsg.IsLogin = false

	qrCode, err := qr.Encode(str, qr.M, qr.Auto)
	if err != nil {
		return nil, err
	}
	qrCode, err = barcode.Scale(qrCode, 200, 200)
	if err != nil {
		return nil, err
	}
	var buf bytes.Buffer
	err = png.Encode(&buf, qrCode)
	if err != nil {
		return nil, err
	}
	var result []byte
	base64.StdEncoding.Encode(result, buf.Bytes())
	return result, err
}

func (qrmsg *QrcodeMessage) ParseToken(str string) error {
	tokenClaims, err := jwt.ParseWithClaims(
		str,
		qrmsg,
		func(token *jwt.Token) (interface{}, error) {
			return []byte(loginTokenSecret), nil
		})
	if err != nil {
		return err
	}
	if claim, ok := tokenClaims.Claims.(*QrcodeMessage); ok && tokenClaims.Valid {
		*qrmsg = *claim
	}
	return nil
}