更新项目架构与存储适配器,添加用户认证功能

本次提交包含以下主要更改:
1. 更新 `.gitignore` 文件,添加对 `node_modules` 和环境变量文件的忽略。
2. 修改 `.gitmodules` 文件,替换为新的子模块 `cloudflare-worker`。
3. 新增 `ARCHITECTURE.md` 和 `PROJECT_REFACTOR_PLAN.md` 文档,详细描述项目架构和改造计划。
4. 实现用户认证功能,添加 GitHub OAuth 处理逻辑,支持 JWT 生成与解析。
5. 引入新的存储接口 `CanvasStore`,并实现相应的存储逻辑,支持用户画布的增删改查。
6. 更新 `main.go` 文件,整合新的认证与存储逻辑,优化路由设置。

这些更改旨在提升项目的可扩展性与用户体验,支持多用户环境下的画布管理与存储。
This commit is contained in:
Yuzhong Zhang
2025-07-05 23:13:17 +08:00
parent 61abbc612b
commit 94953a5eac
26 changed files with 2078 additions and 293 deletions
+176
View File
@@ -0,0 +1,176 @@
package kv
import (
"encoding/json"
"excalidraw-complete/core"
"excalidraw-complete/handlers/auth"
"excalidraw-complete/middleware"
"excalidraw-complete/stores"
"io"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
"github.com/sirupsen/logrus"
)
func HandleListCanvases(store stores.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
claims, ok := r.Context().Value(middleware.ClaimsContextKey).(*auth.AppClaims)
if !ok {
render.Status(r, http.StatusUnauthorized)
render.JSON(w, r, map[string]string{"error": "User claims not found"})
return
}
canvases, err := store.List(r.Context(), claims.Subject)
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err,
"userID": claims.Subject,
}).Error("Failed to list canvases")
render.Status(r, http.StatusInternalServerError)
render.JSON(w, r, map[string]string{"error": "Failed to list canvases"})
return
}
// If canvases is nil (e.g., user has no canvases), return an empty slice instead of null.
if canvases == nil {
canvases = []*core.Canvas{}
}
render.JSON(w, r, canvases)
}
}
func HandleGetCanvas(store stores.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
claims, ok := r.Context().Value(middleware.ClaimsContextKey).(*auth.AppClaims)
if !ok {
render.Status(r, http.StatusUnauthorized)
render.JSON(w, r, map[string]string{"error": "User claims not found"})
return
}
key := chi.URLParam(r, "key")
if key == "" {
render.Status(r, http.StatusBadRequest)
render.JSON(w, r, map[string]string{"error": "Canvas key is required"})
return
}
canvas, err := store.Get(r.Context(), claims.Subject, key)
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err,
"userID": claims.Subject,
"key": key,
}).Warn("Failed to get canvas")
// This could be a not found error or a real server error.
// For simplicity, we'll return 404, but in a real app, you might want to distinguish.
render.Status(r, http.StatusNotFound)
render.JSON(w, r, map[string]string{"error": "Canvas not found"})
return
}
// The canvas data is returned as raw bytes.
w.Header().Set("Content-Type", "application/json")
w.Write(canvas.Data)
}
}
func HandleSaveCanvas(store stores.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
claims, ok := r.Context().Value(middleware.ClaimsContextKey).(*auth.AppClaims)
if !ok {
render.Status(r, http.StatusUnauthorized)
render.JSON(w, r, map[string]string{"error": "User claims not found"})
return
}
key := chi.URLParam(r, "key")
if key == "" {
render.Status(r, http.StatusBadRequest)
render.JSON(w, r, map[string]string{"error": "Canvas key is required"})
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err,
"key": key,
}).Error("Failed to read request body")
render.Status(r, http.StatusInternalServerError)
render.JSON(w, r, map[string]string{"error": "Failed to read request body"})
return
}
defer r.Body.Close()
// For simplicity, we use the key as the name. A more advanced implementation
// might parse a name from the body or have a separate field.
var canvasData struct {
AppState struct {
Name string `json:"name"`
} `json:"appState"`
}
// We make a copy of the body because json.Unmarshal will consume the reader.
bodyCopy := make([]byte, len(body))
copy(bodyCopy, body)
canvasName := key // Default to key
if err := json.Unmarshal(bodyCopy, &canvasData); err == nil && canvasData.AppState.Name != "" {
canvasName = canvasData.AppState.Name
}
canvas := &core.Canvas{
ID: key,
UserID: claims.Subject,
Name: canvasName,
Data: body,
}
if err := store.Save(r.Context(), canvas); err != nil {
logrus.WithFields(logrus.Fields{
"error": err,
"userID": claims.Subject,
"key": key,
}).Error("Failed to save canvas")
render.Status(r, http.StatusInternalServerError)
render.JSON(w, r, map[string]string{"error": "Failed to save canvas"})
return
}
render.Status(r, http.StatusOK)
}
}
func HandleDeleteCanvas(store stores.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
claims, ok := r.Context().Value(middleware.ClaimsContextKey).(*auth.AppClaims)
if !ok {
render.Status(r, http.StatusUnauthorized)
render.JSON(w, r, map[string]string{"error": "User claims not found"})
return
}
key := chi.URLParam(r, "key")
if key == "" {
render.Status(r, http.StatusBadRequest)
render.JSON(w, r, map[string]string{"error": "Canvas key is required"})
return
}
if err := store.Delete(r.Context(), claims.Subject, key); err != nil {
logrus.WithFields(logrus.Fields{
"error": err,
"userID": claims.Subject,
"key": key,
}).Error("Failed to delete canvas")
render.Status(r, http.StatusInternalServerError)
render.JSON(w, r, map[string]string{"error": "Failed to delete canvas"})
return
}
render.Status(r, http.StatusOK)
}
}
+207
View File
@@ -0,0 +1,207 @@
package openai
import (
"bytes"
"encoding/json"
"excalidraw-complete/handlers/auth"
"excalidraw-complete/middleware"
"io"
"log"
"net/http"
"os"
"time"
"github.com/go-chi/render"
)
var (
openaiAPIKey string
openaiBaseURL string
)
func Init() {
openaiAPIKey = os.Getenv("OPENAI_API_KEY")
openaiBaseURL = os.Getenv("OPENAI_BASE_URL")
if openaiBaseURL == "" {
openaiBaseURL = "https://api.openai.com" // Default value
}
if openaiAPIKey == "" {
log.Println("WARNING: OPENAI_API_KEY environment variable not set. OpenAI proxy will not work.")
}
}
// Structures for OpenAI compatibility
type LiteralType string
const (
LiteralTypeText LiteralType = "text"
LiteralTypeImageURL LiteralType = "image_url"
)
// UserTextContentPart corresponds to a part of a multi-part message with text.
type UserTextContentPart struct {
Type LiteralType `json:"type"`
Text string `json:"text"`
}
// ImageURL details the URL and detail level of an image.
type ImageURL struct {
URL string `json:"url"`
Detail string `json:"detail,omitempty"`
}
// UserImageContentPart corresponds to a part of a multi-part message with an image.
type UserImageContentPart struct {
Type LiteralType `json:"type"`
ImageURL ImageURL `json:"image_url"`
}
type UserContentPart struct {
Type string `json:"type"`
Content string `json:"content"`
}
type UserContext struct {
UserID int `json:"user_id"`
}
type ChatMessage struct {
Role string `json:"role"`
Content any `json:"content"` // Can be string or a slice of UserTextContentPart/UserImageContentPart
Name string `json:"name,omitempty"`
}
type ChatCompletionRequest struct {
Model string `json:"model"`
Messages []ChatMessage `json:"messages"`
MaxTokens *int `json:"max_tokens,omitempty"`
Stream *bool `json:"stream"`
// Other fields like temperature, max_tokens etc. are ignored for this mock
}
type ChatCompletionChoice struct {
Index int `json:"index"`
Message ChatMessage `json:"message"`
FinishReason string `json:"finish_reason"`
}
type Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
}
type ChatCompletionResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
Model string `json:"model"`
Choices []ChatCompletionChoice `json:"choices"`
Usage Usage `json:"usage"`
}
// FlusherWriter is a helper to ensure that data is flushed to the client for streaming
type FlusherWriter struct {
w http.ResponseWriter
f http.Flusher
}
func (fw *FlusherWriter) Write(p []byte) (int, error) {
n, err := fw.w.Write(p)
if fw.f != nil {
fw.f.Flush()
}
return n, err
}
func HandleChatCompletion() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Verify user is authenticated
_, ok := r.Context().Value(middleware.ClaimsContextKey).(*auth.AppClaims)
if !ok {
render.Status(r, http.StatusUnauthorized)
render.JSON(w, r, map[string]string{"error": "User claims not found"})
return
}
if openaiAPIKey == "" {
render.Status(r, http.StatusInternalServerError)
render.JSON(w, r, map[string]string{"error": "OpenAI API key is not configured on the server"})
return
}
// Read the original request body
body, err := io.ReadAll(r.Body)
if err != nil {
render.Status(r, http.StatusInternalServerError)
render.JSON(w, r, map[string]string{"error": "Failed to read request body"})
return
}
defer r.Body.Close()
// Unmarshal to check if it's a streaming request
var req ChatCompletionRequest
if err := json.Unmarshal(body, &req); err != nil {
render.Status(r, http.StatusBadRequest)
render.JSON(w, r, map[string]string{"error": "Invalid JSON in request body"})
return
}
// Create the proxy request to OpenAI
proxyURL := openaiBaseURL + "/v1/chat/completions"
proxyReq, err := http.NewRequestWithContext(r.Context(), "POST", proxyURL, bytes.NewReader(body))
if err != nil {
render.Status(r, http.StatusInternalServerError)
render.JSON(w, r, map[string]string{"error": "Failed to create proxy request"})
return
}
// Set necessary headers
proxyReq.Header.Set("Authorization", "Bearer "+openaiAPIKey)
proxyReq.Header.Set("Content-Type", "application/json")
proxyReq.Header.Set("Accept", "application/json")
// Send the request to OpenAI
client := &http.Client{Timeout: 5 * time.Minute}
resp, err := client.Do(proxyReq)
if err != nil {
render.Status(r, http.StatusBadGateway)
render.JSON(w, r, map[string]string{"error": "Failed to communicate with OpenAI API"})
return
}
defer resp.Body.Close()
// Handle the response based on whether it's a stream or not
if req.Stream != nil && *req.Stream {
// Streaming response
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}
// Copy headers from OpenAI response to our response
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.WriteHeader(resp.StatusCode)
fw := &FlusherWriter{w: w, f: flusher}
if _, err := io.Copy(fw, resp.Body); err != nil {
// Log error, but the response is likely already sent/broken.
log.Printf("Error streaming response from OpenAI: %v", err)
}
} else {
// Non-streaming response
// Copy headers from OpenAI response
for key, values := range resp.Header {
for _, value := range values {
w.Header().Add(key, value)
}
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}
}
}
+180
View File
@@ -0,0 +1,180 @@
package auth
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"excalidraw-complete/core"
"fmt"
"io"
"net/http"
"os"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"golang.org/x/oauth2/github"
)
var (
githubOauthConfig *oauth2.Config
jwtSecret []byte
)
const oauthStateString = "random"
// AppClaims represents the custom claims for the JWT.
type AppClaims struct {
jwt.RegisteredClaims
Login string `json:"login"`
AvatarURL string `json:"avatarUrl"`
Name string `json:"name"`
}
func Init() {
githubOauthConfig = &oauth2.Config{
ClientID: os.Getenv("GITHUB_CLIENT_ID"),
ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
RedirectURL: os.Getenv("GITHUB_REDIRECT_URL"),
Scopes: []string{"read:user", "user:email"},
Endpoint: github.Endpoint,
}
jwtSecret = []byte(os.Getenv("JWT_SECRET"))
if githubOauthConfig.ClientID == "" || githubOauthConfig.ClientSecret == "" {
logrus.Warn("GitHub OAuth credentials are not set. Authentication routes will not work.")
}
if len(jwtSecret) == 0 {
logrus.Warn("JWT_SECRET is not set. Authentication routes will not work.")
}
}
func generateStateOauthCookie(w http.ResponseWriter) string {
b := make([]byte, 16)
rand.Read(b)
state := base64.URLEncoding.EncodeToString(b)
cookie := &http.Cookie{
Name: "oauthstate",
Value: state,
Expires: time.Now().Add(10 * time.Minute),
HttpOnly: true,
}
http.SetCookie(w, cookie)
return state
}
func HandleGitHubLogin(w http.ResponseWriter, r *http.Request) {
if githubOauthConfig.ClientID == "" {
http.Error(w, "GitHub OAuth is not configured", http.StatusInternalServerError)
return
}
state := generateStateOauthCookie(w)
url := githubOauthConfig.AuthCodeURL(state)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func HandleGitHubCallback(w http.ResponseWriter, r *http.Request) {
if githubOauthConfig.ClientID == "" {
http.Error(w, "GitHub OAuth is not configured", http.StatusInternalServerError)
return
}
oauthState, _ := r.Cookie("oauthstate")
if r.FormValue("state") != oauthState.Value {
logrus.Error("invalid oauth github state")
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
token, err := githubOauthConfig.Exchange(context.Background(), r.FormValue("code"))
if err != nil {
logrus.Errorf("failed to exchange token: %s", err.Error())
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
client := githubOauthConfig.Client(context.Background(), token)
resp, err := client.Get("https://api.github.com/user")
if err != nil {
logrus.Errorf("failed to get user from github: %s", err.Error())
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
logrus.Errorf("failed to read github response body: %s", err.Error())
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
var githubUser struct {
ID int64 `json:"id"`
Login string `json:"login"`
AvatarURL string `json:"avatar_url"`
Name string `json:"name"`
}
if err := json.Unmarshal(body, &githubUser); err != nil {
logrus.Errorf("failed to unmarshal github user: %s", err.Error())
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
// For now we don't have a user database, so we create a user object on the fly.
// In phase 3, we will save/get the user from the database here.
user := &core.User{
GitHubID: githubUser.ID,
Login: githubUser.Login,
AvatarURL: githubUser.AvatarURL,
Name: githubUser.Name,
}
jwtToken, err := createJWT(user)
if err != nil {
logrus.Errorf("failed to create JWT: %s", err.Error())
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
// Redirect to frontend with token
http.Redirect(w, r, fmt.Sprintf("/?token=%s", jwtToken), http.StatusTemporaryRedirect)
}
func createJWT(user *core.User) (string, error) {
claims := AppClaims{
RegisteredClaims: jwt.RegisteredClaims{
Subject: fmt.Sprintf("%d", user.GitHubID),
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24 * 7)), // 1 week
IssuedAt: jwt.NewNumericDate(time.Now()),
},
Login: user.Login,
AvatarURL: user.AvatarURL,
Name: user.Name,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(jwtSecret)
}
func ParseJWT(tokenString string) (*AppClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &AppClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return jwtSecret, nil
})
if err != nil {
return nil, err
}
if claims, ok := token.Claims.(*AppClaims); ok && token.Valid {
return claims, nil
}
return nil, fmt.Errorf("invalid token")
}