DriveLinked/pkg/common/token.go

107 lines
2.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package common
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"drive-linked/config"
"drive-linked/pkg/utils"
"github.com/golang-jwt/jwt/v4"
"github.com/kataras/golog"
"io/ioutil"
"os"
"time"
)
type JwtClaims struct {
Foo string `json:"foo"`
jwt.RegisteredClaims
}
var ECDSAKey *ecdsa.PrivateKey
// 生成ES256密钥对并保存在文件中
func init() {
// 密钥对存在时跳过
//TODO:bug:会重复生成key
if isExist := utils.FileExist("id_ecdsa") && utils.FileExist("id_ecdsa.pub"); isExist {
return
}
key, err := newES256Key()
if err != nil {
golog.Fatal("生成ES256密钥错误")
}
// 写入至文件
pubKeyBytes, err := utils.EncodePublicKey(&key.PublicKey)
if err != nil {
golog.Fatal(err)
}
priKeyBytes, err := utils.EncodePrivateKey(key)
if err != nil {
golog.Fatal(err)
}
priKeyFile, err := os.OpenFile("id_ecdsa", os.O_CREATE, 0600)
if err != nil {
golog.Fatal(err)
}
pubKeyFile, err := os.OpenFile("id_ecdsa.pub", os.O_CREATE, 0655)
if err != nil {
golog.Fatal(err)
}
priKeyFile.Write(priKeyBytes)
pubKeyFile.Write(pubKeyBytes)
}
func newES256Key() (key *ecdsa.PrivateKey, err error) {
key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
return key, err
}
func LoadKey() error {
if ECDSAKey != nil {
return nil
}
priKeyBytes, err := ioutil.ReadFile(config.Cfg.Security.Jwt.PrivateKey)
if err != nil {
return err
}
key, err := utils.DecodePrivateKey(priKeyBytes)
if err != nil {
return err
}
ECDSAKey = key
return nil
}
//TODO:token解密验证
func ValidateLogin(token string) error {
return nil
}
func NewToken(auds ...string) (string, error) {
// Create the claims
claims := JwtClaims{
"bar",
jwt.RegisteredClaims{
// A usual scenario is to set the expiration time relative to the current time
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(config.Cfg.Security.Jwt.Expire) * time.Second)),
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
Issuer: "drivelinked",
Subject: "login",
Audience: []string{"eigeen"},
},
}
token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
ss, err := token.SignedString(ECDSAKey)
if err != nil {
return "", err
}
return ss, nil
}