github.com/godaddy-x/freego@v1.0.156/utils/gauth/google_auth_v2.go (about)

     1  package gauth
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/base64"
     6  	"github.com/pquerna/otp/totp"
     7  	"github.com/skip2/go-qrcode"
     8  	"image/png"
     9  )
    10  
    11  func getQRImage(url string, size int) (string, error) {
    12  	qrCode, err := qrcode.New(url, qrcode.Highest)
    13  	if err != nil {
    14  		return "", err
    15  	}
    16  	return getBase64Image(qrCode, size)
    17  }
    18  
    19  func getBase64Image(image *qrcode.QRCode, size int) (string, error) {
    20  	var buf bytes.Buffer
    21  	err := png.Encode(&buf, image.Image(size))
    22  	if err != nil {
    23  		return "", err
    24  	}
    25  	return "data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes()), nil
    26  }
    27  
    28  func Create(issuer, accountName string, size int) (string, string, error) {
    29  	secret, url, err := CreateURL(issuer, accountName)
    30  	if err != nil {
    31  		return "", "", err
    32  	}
    33  	image, err := CreateImage(url, size)
    34  	if err != nil {
    35  		return "", "", err
    36  	}
    37  	return secret, image, nil
    38  }
    39  
    40  // CreateURL 密钥,链接
    41  func CreateURL(issuer, accountName string) (string, string, error) {
    42  	key, err := totp.Generate(totp.GenerateOpts{
    43  		Issuer:      issuer,
    44  		AccountName: accountName,
    45  	})
    46  	if err != nil {
    47  		return "", "", err
    48  	}
    49  	return key.Secret(), key.URL(), nil
    50  }
    51  
    52  func CreateImage(url string, size int) (string, error) {
    53  	image, err := getQRImage(url, size)
    54  	if err != nil {
    55  		return "", err
    56  	}
    57  	return image, nil
    58  }
    59  
    60  func Validate(code, secret string) bool {
    61  	if len(secret) == 0 || len(code) != 6 {
    62  		return false
    63  	}
    64  	return totp.Validate(code, secret)
    65  }