Add backend foundation and config-driven workbench
This commit is contained in:
67
backend/internal/platform/jwtx/jwt.go
Normal file
67
backend/internal/platform/jwtx/jwt.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package jwtx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type Manager struct {
|
||||
issuer string
|
||||
secret []byte
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
type AccessClaims struct {
|
||||
UserID string `json:"uid"`
|
||||
UserPublicID string `json:"upub"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func NewManager(issuer, secret string, ttl time.Duration) *Manager {
|
||||
return &Manager{
|
||||
issuer: issuer,
|
||||
secret: []byte(secret),
|
||||
ttl: ttl,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) IssueAccessToken(userID, userPublicID string) (string, time.Time, error) {
|
||||
expiresAt := time.Now().UTC().Add(m.ttl)
|
||||
claims := AccessClaims{
|
||||
UserID: userID,
|
||||
UserPublicID: userPublicID,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Issuer: m.issuer,
|
||||
Subject: userID,
|
||||
ExpiresAt: jwt.NewNumericDate(expiresAt),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now().UTC()),
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
signed, err := token.SignedString(m.secret)
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
return signed, expiresAt, nil
|
||||
}
|
||||
|
||||
func (m *Manager) ParseAccessToken(tokenString string) (*AccessClaims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &AccessClaims{}, func(token *jwt.Token) (any, error) {
|
||||
if token.Method != jwt.SigningMethodHS256 {
|
||||
return nil, fmt.Errorf("unexpected signing method")
|
||||
}
|
||||
return m.secret, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*AccessClaims)
|
||||
if !ok || !token.Valid {
|
||||
return nil, fmt.Errorf("invalid token claims")
|
||||
}
|
||||
return claims, nil
|
||||
}
|
||||
47
backend/internal/platform/security/token.go
Normal file
47
backend/internal/platform/security/token.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
func GenerateToken(byteLength int) (string, error) {
|
||||
raw := make([]byte, byteLength)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(raw), nil
|
||||
}
|
||||
|
||||
func GenerateNumericCode(length int) (string, error) {
|
||||
if length <= 0 {
|
||||
length = 6
|
||||
}
|
||||
|
||||
const digits = "0123456789"
|
||||
raw := make([]byte, length)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
code := make([]byte, length)
|
||||
for i := range raw {
|
||||
code[i] = digits[int(raw[i])%len(digits)]
|
||||
}
|
||||
return string(code), nil
|
||||
}
|
||||
|
||||
func HashText(value string) string {
|
||||
sum := sha256.Sum256([]byte(value))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func GeneratePublicID(prefix string) (string, error) {
|
||||
raw := make([]byte, 8)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return prefix + "_" + hex.EncodeToString(raw), nil
|
||||
}
|
||||
120
backend/internal/platform/wechatmini/client.go
Normal file
120
backend/internal/platform/wechatmini/client.go
Normal file
@@ -0,0 +1,120 @@
|
||||
package wechatmini
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
appID string
|
||||
appSecret string
|
||||
devPrefix string
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
AppID string
|
||||
OpenID string
|
||||
UnionID string
|
||||
SessionKey string
|
||||
}
|
||||
|
||||
type code2SessionResponse struct {
|
||||
OpenID string `json:"openid"`
|
||||
SessionKey string `json:"session_key"`
|
||||
UnionID string `json:"unionid"`
|
||||
ErrCode int `json:"errcode"`
|
||||
ErrMsg string `json:"errmsg"`
|
||||
}
|
||||
|
||||
func NewClient(appID, appSecret, devPrefix string) *Client {
|
||||
return &Client{
|
||||
appID: appID,
|
||||
appSecret: appSecret,
|
||||
devPrefix: devPrefix,
|
||||
httpClient: &http.Client{Timeout: 8 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) ExchangeCode(ctx context.Context, code string) (*Session, error) {
|
||||
code = strings.TrimSpace(code)
|
||||
if code == "" {
|
||||
return nil, fmt.Errorf("wechat code is required")
|
||||
}
|
||||
|
||||
if c.devPrefix != "" && strings.HasPrefix(code, c.devPrefix) {
|
||||
suffix := strings.TrimPrefix(code, c.devPrefix)
|
||||
if suffix == "" {
|
||||
suffix = "default"
|
||||
}
|
||||
return &Session{
|
||||
AppID: fallbackString(c.appID, "dev-mini-app"),
|
||||
OpenID: "dev_openid_" + normalizeDevID(suffix),
|
||||
UnionID: "",
|
||||
}, nil
|
||||
}
|
||||
|
||||
if c.appID == "" || c.appSecret == "" {
|
||||
return nil, fmt.Errorf("wechat mini app credentials are not configured")
|
||||
}
|
||||
|
||||
values := url.Values{}
|
||||
values.Set("appid", c.appID)
|
||||
values.Set("secret", c.appSecret)
|
||||
values.Set("js_code", code)
|
||||
values.Set("grant_type", "authorization_code")
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.weixin.qq.com/sns/jscode2session?"+values.Encode(), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var parsed code2SessionResponse
|
||||
if err := json.Unmarshal(body, &parsed); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if parsed.ErrCode != 0 {
|
||||
return nil, fmt.Errorf("wechat code2session failed: %d %s", parsed.ErrCode, parsed.ErrMsg)
|
||||
}
|
||||
if parsed.OpenID == "" {
|
||||
return nil, fmt.Errorf("wechat code2session returned empty openid")
|
||||
}
|
||||
|
||||
return &Session{
|
||||
AppID: c.appID,
|
||||
OpenID: parsed.OpenID,
|
||||
UnionID: parsed.UnionID,
|
||||
SessionKey: parsed.SessionKey,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func normalizeDevID(value string) string {
|
||||
sum := sha1.Sum([]byte(value))
|
||||
return hex.EncodeToString(sum[:])[:16]
|
||||
}
|
||||
|
||||
func fallbackString(value, fallback string) string {
|
||||
if value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
Reference in New Issue
Block a user