feat: 初始提交 - Code Server Bridge完整实现

- OAuth认证系统(Gitea + Lua扩展)
- Git自动化操作(本地/SSH远程)
- 实时进度WebSocket推送
- 现代化Tab界面UI
- Cobra CLI命令行(init/version/serve)
- 完整构建系统(Makefile + Taskfile)
- UPX压缩支持(体积减少70%)
This commit is contained in:
2026-01-08 23:32:29 +08:00
commit 8265df0dcd
40 changed files with 3786 additions and 0 deletions

View File

@@ -0,0 +1,8 @@
package auth
type Identify struct {
Provider string `lua:"provider"`
UserId string `lua:"uid"`
Username string `lua:"username"`
Avatar string `lua:"avatar"`
}

87
internal/auth/token.go Normal file
View File

@@ -0,0 +1,87 @@
package auth
import (
"crypto/rand"
"cs-bridge/internal/db"
"encoding/hex"
"errors"
"fmt"
"time"
"gorm.io/gorm"
)
var (
ErrTokenNotFound = errors.New("token not found")
ErrTokenExpired = errors.New("token expired")
ErrTokenUsed = errors.New("token already used")
)
// GenerateWorkspaceToken 生成workspace访问token
// workspacePath: workspace的路径
// ttl: token有效期
// 返回生成的token字符串和可能的错误
func GenerateWorkspaceToken(workspacePath string, ttl time.Duration) (string, error) {
// 生成随机token (32字节 = 64个十六进制字符)
tokenBytes := make([]byte, 32)
if _, err := rand.Read(tokenBytes); err != nil {
return "", err
}
token := hex.EncodeToString(tokenBytes)
// 计算过期时间
expiresAt := time.Now().Add(time.Second * ttl)
fmt.Println("GenerateWorkspaceToken: expiresAt: ", expiresAt)
// 保存到数据库
workspaceToken := db.WorkspaceToken{
Token: token,
WorkspacePath: workspacePath,
ExpiresAt: expiresAt,
Used: false,
}
database := db.GetDB()
if err := database.Create(&workspaceToken).Error; err != nil {
return "", err
}
return token, nil
}
// ValidateToken 验证token (可多次使用,直到过期)
// token: 要验证的token字符串
// 返回workspace路径和可能的错误
func ValidateAndConsumeToken(token string) (string, error) {
database := db.GetDB()
var workspaceToken db.WorkspaceToken
// 查找token
if err := database.Where("token = ?", token).First(&workspaceToken).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return "", ErrTokenNotFound
}
return "", err
}
// 检查是否过期
if time.Now().After(workspaceToken.ExpiresAt) {
return "", ErrTokenExpired
}
// Token有效,可以多次使用直到过期
return workspaceToken.WorkspacePath, nil
}
// CleanExpiredTokens 清理过期的token
// 删除所有已过期的token记录
func CleanExpiredTokens() error {
database := db.GetDB()
// 删除所有过期的token
result := database.Where("expires_at < ?", time.Now()).Delete(&db.WorkspaceToken{})
return result.Error
}

129
internal/config/config.go Normal file
View File

@@ -0,0 +1,129 @@
package config
import (
"cs-bridge/internal/consts"
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"sync"
"github.com/go-yaml/yaml"
"github.com/spf13/viper"
)
var (
globalViper *viper.Viper
globalViperOnce sync.Once
configMu sync.RWMutex
cachedConfig *Config
)
// NewConfig 初始化配置
func NewConfig() *Config {
globalViperOnce.Do(func() {
globalViper = viper.New()
})
configPath := loadConfigFile()
if configPath == "" {
log.Println("⚠️ 未找到配置文件,使用默认配置并导出为 config.yaml")
cachedConfig = DefaultConfig()
exportConfig(cachedConfig, "yaml")
return cachedConfig
}
conf, err := parseConfig()
if err != nil {
log.Printf("⚠️ 解析配置失败,使用默认配置并导出为 config.yaml: %v", err)
conf = DefaultConfig()
exportConfig(conf, "yaml")
}
cachedConfig = conf
return conf
}
// loadConfigFile 加载配置文件
func loadConfigFile() string {
files := []string{
fmt.Sprintf("%s.yaml", consts.ConfigName),
fmt.Sprintf("%s.yml", consts.ConfigName),
}
for _, file := range files {
if _, err := os.Stat(file); err == nil {
ext := filepath.Ext(file)[1:]
globalViper.SetConfigFile(file)
globalViper.SetConfigType(ext)
globalViper.AddConfigPath(".")
if err := globalViper.ReadInConfig(); err != nil {
log.Printf("⚠️ 读取配置文件 %s 失败: %v", file, err)
continue
}
log.Printf("✅ 成功加载配置文件: %s", file)
return file
}
}
return ""
}
// parseConfig 将配置解析为结构体
func parseConfig() (*Config, error) {
configMu.Lock()
defer configMu.Unlock()
var conf Config
if err := globalViper.Unmarshal(&conf); err != nil {
return nil, err
}
return &conf, nil
}
// exportConfig 导出配置文件(默认保存为 config.yaml
func exportConfig(conf *Config, format string) {
var (
data []byte
err error
)
switch format {
case "json":
data, err = json.MarshalIndent(conf, "", " ")
case "yaml", "yml", "":
format = "yaml"
data, err = yaml.Marshal(conf)
default:
log.Printf("⚠️ 不支持的导出格式: %s", format)
return
}
if err != nil {
log.Printf("⚠️ 导出 %s 格式配置失败: %v", format, err)
return
}
filename := fmt.Sprintf("%s.%s", consts.ConfigName, format)
if err := os.WriteFile(filename, data, 0644); err != nil {
log.Printf("⚠️ 写入配置文件 %s 失败: %v", filename, err)
} else {
log.Printf("✅ 已导出配置文件: %s", filename)
}
log.Printf("📋 当前 %s 配置:\n%s", format, data)
}
// GetConfig 获取当前配置(线程安全)
func GetConfig() *Config {
configMu.RLock()
defer configMu.RUnlock()
if cachedConfig == nil {
return DefaultConfig()
}
conf := *cachedConfig
return &conf
}

116
internal/config/type.go Normal file
View File

@@ -0,0 +1,116 @@
package config
import (
"cs-bridge/internal/consts"
"path/filepath"
"time"
)
type Server struct {
Debug bool `mapstructure:"debug"`
Port int `mapstructure:"port"`
}
type Log struct {
Level string `mapstructure:"level" yaml:"level"`
Filepath string `mapstructure:"filepath" yaml:"filepath"`
MaxSizeMB int `mapstructure:"max_size_mb" yaml:"max_size_mb"` // 单个日志文件最大(MB)
MaxAgeDay int `mapstructure:"max_age_day" yaml:"max_age_day"` // 日志文件最大保存天数
Backups int `mapstructure:"backups" yaml:"backups"` // 保留的旧文件个数
Compress bool `mapstructure:"compress" yaml:"compress"` // 是否压缩
}
type Database struct {
SqliteDbPath string `mapstructure:"sqlite_db_path" yaml:"sqlite_db_path"`
}
type Secret struct {
TokenTTL time.Duration `mapstructure:"token_ttl" yaml:"token_ttl"`
WSTTL time.Duration `mapstructure:"ws_ttl" yaml:"ws_ttl"`
}
type Provider struct {
Name string `mapstructure:"name" yaml:"name"`
Type string `mapstructure:"type" yaml:"type"`
ClientID string `mapstructure:"client_id" yaml:"client_id"`
ClientSecret string `mapstructure:"client_secret" yaml:"client_secret"`
BaseURL string `mapstructure:"base_url" yaml:"base_url"`
AuthorizeURL string `mapstructure:"authorize_url" yaml:"authorize_url"`
TokenURL string `mapstructure:"token_url" yaml:"token_url"`
UserURL string `mapstructure:"user_url" yaml:"user_url"`
}
type OAuth struct {
BaseURL string `mapstructure:"base_url" yaml:"base_url"`
Providers []Provider `mapstructure:"providers" yaml:"providers"`
}
type CodeServer struct {
BaseURL string `mapstructure:"base_url" yaml:"base_url"`
WorkspaceRoot string `mapstructure:"workspace_root" yaml:"workspace_root"` // 容器内路径,传递给code-server
// SSH配置 - 用于远程执行git操作
SSHHost string `mapstructure:"ssh_host" yaml:"ssh_host"` // SSH服务器地址
SSHPort int `mapstructure:"ssh_port" yaml:"ssh_port"` // SSH端口,默认22
SSHUser string `mapstructure:"ssh_user" yaml:"ssh_user"` // SSH用户名(专用账号)
SSHKeyPath string `mapstructure:"ssh_key_path" yaml:"ssh_key_path"` // SSH私钥路径
SSHWorkspaceRoot string `mapstructure:"ssh_workspace_root" yaml:"ssh_workspace_root"` // SSH服务器上的workspace路径(容器映射到宿主机的路径)
}
type Config struct {
Server Server `mapstructure:"server" yaml:"server"`
Log Log `mapstructure:"log" yaml:"log"`
Database Database `mapstructure:"database" yaml:"database"`
Secret Secret `mapstructure:"secret" yaml:"secret"`
OAuth OAuth `mapstructure:"oauth" yaml:"oauth"`
CodeServer CodeServer `mapstructure:"code_server" yaml:"code_server"`
}
func DefaultConfig() *Config {
logPath := filepath.Join(consts.DataDir, "log.log")
dbPath := filepath.Join(consts.DataDir, "sqlite.db")
return &Config{
Server: Server{
Debug: true,
Port: 8080,
},
Log: Log{
Level: "debug",
Filepath: logPath,
MaxSizeMB: 10,
MaxAgeDay: 7,
Backups: 3,
Compress: true,
},
Database: Database{
SqliteDbPath: dbPath,
},
Secret: Secret{
TokenTTL: time.Millisecond * 600,
WSTTL: time.Millisecond * 3600,
},
OAuth: OAuth{
BaseURL: "http://localhost:8080",
Providers: []Provider{
{
Name: "gitea",
Type: "gitea",
ClientID: "xxx",
ClientSecret: "xxx",
BaseURL: "https://xxx",
AuthorizeURL: "/login/oauth/authorize",
TokenURL: "/login/oauth/access_token",
UserURL: "/api/v1/user",
},
},
},
CodeServer: CodeServer{
BaseURL: "xxx",
WorkspaceRoot: "/config/workspace", // 容器内路径
SSHHost: "",
SSHPort: 22,
SSHUser: "git",
SSHKeyPath: "",
SSHWorkspaceRoot: "/root/code-server/data/workspace", // SSH服务器实际路径
},
}
}

41
internal/consts/const.go Normal file
View File

@@ -0,0 +1,41 @@
package consts
import (
"fmt"
)
// 通用系统级常量
const (
AppName = "cs-bridge"
AppAuthor = "zhilv666"
AppVersion = "0.0.1"
)
var (
BuildTime string
GitCommit string
)
const DataDir = "data"
// 默认服务端口
const DefaultPort = 8080
// 通用时间格式
const (
TimeFormatDate = "2006-01-02"
TimeFormatDateTime = "2006-01-02 15:04:05"
)
func init() {
fmt.Printf("🚀 启动 %s v%s by %s\n",
AppName,
AppVersion,
AppAuthor,
)
}
// 项目路径与文件定义
var (
ConfigName = "config"
)

10
internal/db/connect.go Normal file
View File

@@ -0,0 +1,10 @@
package db
import (
"github.com/glebarez/sqlite"
"gorm.io/gorm"
)
func connectSQLite(filepath string) gorm.Dialector {
return sqlite.Open(filepath + "?cache=shared&_fk=1&_driver=modernc.org/sqlite")
}

50
internal/db/db.go Normal file
View File

@@ -0,0 +1,50 @@
package db
import (
"cs-bridge/internal/config"
"fmt"
"os"
"go.uber.org/zap"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
var db *gorm.DB
func init() {
if _, err := os.Stat("./data"); os.IsNotExist(err) {
_ = os.Mkdir("./data", os.ModePerm)
}
}
func GetDB() *gorm.DB {
if db == nil {
panic("数据库未初始化,请先调用 db.InitDB()")
}
return db
}
func InitDB(cfg config.Database, log *zap.Logger) {
go func() {
if err := recover(); err != nil {
panic(fmt.Sprintf("Init DB Error: %v", err))
}
}()
fmt.Println(cfg.SqliteDbPath)
dialector := connectSQLite(cfg.SqliteDbPath)
var err error
db, err = gorm.Open(dialector, &gorm.Config{
Logger: NewZapGormLogger(log).LogMode(logger.Info),
})
if err != nil {
panic(err)
}
// 自动迁移数据库模型
if err := db.AutoMigrate(&WorkspaceToken{}); err != nil {
panic(fmt.Sprintf("Failed to migrate WorkspaceToken model: %v", err))
}
}

View File

@@ -0,0 +1,81 @@
package db
import (
"context"
"time"
"go.uber.org/zap"
"gorm.io/gorm/logger"
"gorm.io/gorm/utils"
)
type ZapGormLogger struct {
ZapLogger *zap.Logger
LogLevel logger.LogLevel
SlowThreshold time.Duration
}
func NewZapGormLogger(zapLogger *zap.Logger) *ZapGormLogger {
return &ZapGormLogger{
ZapLogger: zapLogger,
LogLevel: logger.Info,
SlowThreshold: time.Second, // 1s 慢查询阈值
}
}
func (l *ZapGormLogger) LogMode(level logger.LogLevel) logger.Interface {
newlogger := *l
newlogger.LogLevel = level
return &newlogger
}
func (l *ZapGormLogger) Info(ctx context.Context, msg string, data ...interface{}) {
if l.LogLevel >= logger.Info {
l.ZapLogger.Sugar().Infof(msg, data...)
}
}
func (l *ZapGormLogger) Warn(ctx context.Context, msg string, data ...interface{}) {
if l.LogLevel >= logger.Warn {
l.ZapLogger.Sugar().Warnf(msg, data...)
}
}
func (l *ZapGormLogger) Error(ctx context.Context, msg string, data ...interface{}) {
if l.LogLevel >= logger.Error {
l.ZapLogger.Sugar().Errorf(msg, data...)
}
}
func (l *ZapGormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
if l.LogLevel <= logger.Silent {
return
}
elapsed := time.Since(begin)
sql, rows := fc()
switch {
case err != nil && l.LogLevel >= logger.Error:
l.ZapLogger.Error("SQL Error",
zap.Error(err),
zap.String("sql", sql),
zap.Int64("rows", rows),
zap.Duration("elapsed", elapsed),
zap.String("file", utils.FileWithLineNum()),
)
case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= logger.Warn:
l.ZapLogger.Warn("Slow SQL",
zap.Duration("elapsed", elapsed),
zap.String("sql", sql),
zap.Int64("rows", rows),
zap.String("file", utils.FileWithLineNum()),
)
case l.LogLevel >= logger.Info:
l.ZapLogger.Info("SQL",
zap.String("sql", sql),
zap.Int64("rows", rows),
zap.Duration("elapsed", elapsed),
zap.String("file", utils.FileWithLineNum()),
)
}
}

View File

@@ -0,0 +1,16 @@
package db
import (
"time"
)
// WorkspaceToken 工作区访问令牌模型
// 用于存储一次性/限时的workspace访问token
type WorkspaceToken struct {
ID uint `gorm:"primarykey"`
Token string `gorm:"uniqueIndex;not null"` // Token哈希值
WorkspacePath string `gorm:"not null"` // 工作区路径
CreatedAt time.Time // 创建时间
ExpiresAt time.Time `gorm:"index"` // 过期时间
Used bool `gorm:"default:false;index"` // 是否已使用
}

View File

@@ -0,0 +1,85 @@
package handlers
import (
"cs-bridge/internal/auth"
"cs-bridge/pkg/logger"
"encoding/json"
"fmt"
"net/http"
"go.uber.org/zap"
)
// ValidateTokenResponse Token验证响应结构
type ValidateTokenResponse struct {
Success bool `json:"success"`
Workspace string `json:"workspace,omitempty"`
Error string `json:"error,omitempty"`
}
// ValidateWorkspaceToken Token验证处理器(供nginx调用)
// nginx通过此接口验证token并获取workspace路径
func ValidateWorkspaceToken() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log := logger.GetLogger()
// 获取token参数 - 优先从query获取,否则从header获取(nginx auth_request场景)
token := r.URL.Query().Get("token")
if token == "" {
token = r.Header.Get("X-Auth-Token")
}
log.Info("[Auth] 收到验证请求",
zap.String("url", r.URL.String()),
zap.Bool("has_token", token != ""))
if token == "" {
// 无token时返回200,允许请求通过(不设置X-Workspace)
// 这样静态资源等请求可以正常访问
log.Debug("[Auth] 无token, 允许通过")
w.WriteHeader(http.StatusOK)
return
}
// 验证token (可多次使用,直到过期)
log.Info(fmt.Sprintf("[Auth] 开始验证token: %s...", token[:min(16, len(token))]))
workspacePath, err := auth.ValidateAndConsumeToken(token)
if err != nil {
log.Error(fmt.Sprintf("[Auth] Token验证失败: %v", err))
w.Header().Set("Content-Type", "application/json")
// 根据错误类型返回不同的状态码
switch err {
case auth.ErrTokenNotFound:
w.WriteHeader(http.StatusNotFound)
case auth.ErrTokenExpired:
w.WriteHeader(http.StatusGone)
default:
w.WriteHeader(http.StatusInternalServerError)
}
json.NewEncoder(w).Encode(ValidateTokenResponse{
Success: false,
Error: err.Error(),
})
return
}
log.Info(fmt.Sprintf("[Auth] Token验证成功, Workspace: %s", workspacePath))
// 返回成功响应
w.Header().Set("X-Workspace", workspacePath)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ValidateTokenResponse{
Success: true,
Workspace: workspacePath,
})
}
}
func min(a, b int) int {
if a < b {
return a
}
return b
}

View File

@@ -0,0 +1,25 @@
package handlers
import (
"cs-bridge/internal/config"
"net/http"
"net/url"
"path"
"github.com/google/uuid"
)
func Entry(cfg *config.CodeServer) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
workspaceID := uuid.NewString()
workspacePath := path.Join(cfg.WorkspaceRoot, workspaceID)
redirectURL, _ := url.Parse(cfg.BaseURL)
q := redirectURL.Query()
q.Set("folder", workspacePath)
redirectURL.RawQuery = q.Encode()
http.Redirect(w, r, redirectURL.String(), http.StatusFound)
}
}

View File

@@ -0,0 +1,84 @@
package handlers
import (
"cs-bridge/internal/http/middleware"
"cs-bridge/internal/oauth"
"net/http"
"github.com/go-chi/chi/v5"
)
func OauthLogin(mgr *oauth.Manager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "provider")
p, err := mgr.Get(name)
if err != nil {
http.Error(w, err.Error(), 404)
return
}
state := oauth.NewState()
session, err := middleware.GetSession(r)
session.Values["oauth_state"] = state
session.Values["oauth_provider"] = name
session.Save(r, w)
redirectURL, _ := p.AuthURL(state)
http.Redirect(w, r, redirectURL, http.StatusFound)
}
}
func OauthCallBack(mgr *oauth.Manager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "provider")
p, err := mgr.Get(name)
if err != nil {
http.Error(w, err.Error(), 404)
return
}
session, _ := middleware.GetSession(r)
expectedState, ok := session.Values["oauth_state"].(string)
if !ok {
http.Error(w, "missing oauth state", 400)
return
}
goState := r.URL.Query().Get("state")
if goState != expectedState {
http.Error(w, "invaild oauth state2", 400)
return
}
delete(session.Values, "oauth_state")
code := r.URL.Query().Get("code")
token, err := p.Exchange(code)
if err != nil {
http.Error(w, err.Error(), 404)
return
}
userInfo, err := p.UserInfo(token)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// 只保存用户ID避免session过大
session.Values["uid"] = userInfo.UserId
session.Values["username"] = userInfo.Username
// 获取登录前保存的URL
redirectURL := "/"
if savedURL, ok := session.Values["redirect_after_login"].(string); ok && savedURL != "" {
redirectURL = savedURL
delete(session.Values, "redirect_after_login") // 使用后删除
}
session.Save(r, w)
http.Redirect(w, r, redirectURL, http.StatusFound)
}
}

View File

@@ -0,0 +1,630 @@
package handlers
import (
"crypto/sha1"
"cs-bridge/internal/config"
gitpkg "cs-bridge/pkg/git"
"cs-bridge/pkg/logger"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"path"
"strings"
)
// GitProgressPage 显示git进度页面
func GitProgressPage() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 获取repo参数
repo := r.URL.Query().Get("repo")
if repo == "" {
http.Error(w, "Missing repo parameter", http.StatusBadRequest)
return
}
// 返回HTML页面
w.Header().Set("Content-Type", "text/html; charset=utf-8")
logger.GetLogger().Info(fmt.Sprintf("[GitProgressPage] Repo参数: %s", repo))
// 使用字符串替换避免fmt格式化问题
html := strings.Replace(gitProgressHTML, "{{REPO_URL}}", repo, 1)
w.Write([]byte(html))
}
}
// ExecuteGitRequest 执行git操作的请求结构
type ExecuteGitRequest struct {
RepoURL string `json:"repo_url"`
}
// ExecuteGitResponse 执行git操作的响应结构
type ExecuteGitResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
RedirectURL string `json:"redirect_url,omitempty"`
Error string `json:"error,omitempty"`
}
// ExecuteGitOperations 执行git操作(克隆或更新)
func ExecuteGitOperations(cfg *config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// 解析请求
var req ExecuteGitRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
SendProgressJSON(w, "error", "Invalid request", 0)
return
}
if req.RepoURL == "" {
SendProgressJSON(w, "error", "Missing repo_url", 0)
return
}
log := logger.GetLogger()
log.Info(fmt.Sprintf("[ExecuteGit] 开始执行Git操作, RepoURL: %s, ClientIP: %s", req.RepoURL, r.RemoteAddr))
// 生成workspace路径 - 使用客户端IP和仓库URL的SHA1哈希作为workspaceID
repoName := gitpkg.GetRepoName(req.RepoURL)
// 基于客户端IP和仓库URL生成稳定的workspaceID
// hashInput := r.RemoteAddr + ":" + req.RepoURL
hashInput := req.RepoURL
hasher := sha1.New()
hasher.Write([]byte(hashInput))
workspaceID := hex.EncodeToString(hasher.Sum(nil))[:16] // 取前16位
log.Info(fmt.Sprintf("[ExecuteGit] 生成workspaceID: %s (基于: %s)", workspaceID, hashInput))
// 容器内路径(传递给code-server) - 使用path.Join确保Linux风格路径
containerWorkspacePath := path.Join(cfg.CodeServer.WorkspaceRoot, workspaceID, repoName)
// SSH服务器上的实际路径(用于git操作) - 使用path.Join确保Linux风格路径
sshWorkspacePath := containerWorkspacePath
if cfg.CodeServer.SSHWorkspaceRoot != "" {
sshWorkspacePath = path.Join(cfg.CodeServer.SSHWorkspaceRoot, workspaceID, repoName)
}
log.Info(fmt.Sprintf("[ExecuteGit] 路径配置 - Container: %s, SSH: %s", containerWorkspacePath, sshWorkspacePath))
// 进度回调函数
progressCallback := func(message string, percent int) {
SendProgressToClients("processing", message, percent)
}
// 检查是否使用SSH远程执行
useSSH := cfg.CodeServer.SSHHost != ""
var sshCfg gitpkg.SSHConfig
if useSSH {
sshCfg = gitpkg.SSHConfig{
Host: cfg.CodeServer.SSHHost,
Port: cfg.CodeServer.SSHPort,
User: cfg.CodeServer.SSHUser,
KeyPath: cfg.CodeServer.SSHKeyPath,
}
}
// 检查仓库是否存在
SendProgressToClients("checking", "正在检查仓库...", 5)
var err error
var repoExists bool
if useSSH {
repoExists = gitpkg.CheckRepoExistsRemote(sshCfg, sshWorkspacePath)
} else {
repoExists = gitpkg.CheckRepoExists(containerWorkspacePath)
}
if repoExists {
// 仓库存在,执行pull
SendProgressToClients("pulling", "仓库已存在,正在更新...", 20)
if useSSH {
err = gitpkg.PullRepoRemote(sshCfg, sshWorkspacePath, progressCallback)
} else {
err = gitpkg.PullRepo(containerWorkspacePath, progressCallback)
}
} else {
// 仓库不存在,执行clone
SendProgressToClients("cloning", "仓库不存在,正在克隆...", 20)
if useSSH {
err = gitpkg.CloneRepoRemote(sshCfg, req.RepoURL, sshWorkspacePath, progressCallback)
} else {
err = gitpkg.CloneRepo(req.RepoURL, containerWorkspacePath, progressCallback)
}
}
if err != nil {
SendProgressToClients("error", fmt.Sprintf("Git操作失败: %v", err), 0)
json.NewEncoder(w).Encode(ExecuteGitResponse{
Success: false,
Error: err.Error(),
})
return
}
// Git操作成功,发送100%进度
SendProgressToClients("success", "操作完成,即将跳转...", 100)
// 直接重定向到code-server,带folder参数
redirectURL := fmt.Sprintf("%s?folder=%s", cfg.CodeServer.BaseURL, containerWorkspacePath)
log.Info(fmt.Sprintf("[ExecuteGit] 准备重定向到: %s", redirectURL))
// 返回成功响应
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ExecuteGitResponse{
Success: true,
Message: "Git操作完成",
RedirectURL: redirectURL,
})
}
}
// gitProgressHTML 是git进度页面的HTML模板
const gitProgressHTML = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>准备工作区 - Loading...</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
}
.container {
max-width: 700px;
width: 90%;
background: rgba(255, 255, 255, 0.15);
backdrop-filter: blur(20px);
border-radius: 25px;
padding: 50px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4), 0 0 100px rgba(255, 255, 255, 0.1) inset;
border: 1px solid rgba(255, 255, 255, 0.2);
animation: slideUp 0.6s ease-out;
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
h1 {
text-align: center;
margin-bottom: 35px;
font-size: 32px;
font-weight: 700;
text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
letter-spacing: -0.5px;
}
.progress-container {
background: rgba(0, 0, 0, 0.25);
border-radius: 50px;
height: 24px;
overflow: hidden;
margin-bottom: 25px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2) inset;
}
.progress-bar {
background: linear-gradient(90deg, #4CAF50 0%, #8BC34A 50%, #CDDC39 100%);
height: 100%;
width: 0%;
transition: width 0.4s cubic-bezier(0.4, 0, 0.2, 1);
border-radius: 50px;
position: relative;
overflow: hidden;
}
.progress-bar::after {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
animation: shimmer 2s infinite;
}
@keyframes shimmer {
to {
left: 100%;
}
}
.status {
text-align: center;
font-size: 18px;
margin-bottom: 25px;
min-height: 30px;
font-weight: 500;
}
.log-container {
background: rgba(0, 0, 0, 0.35);
border-radius: 15px;
padding: 25px;
max-height: 350px;
overflow-y: auto;
font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Courier New', monospace;
font-size: 13px;
line-height: 1.6;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.log-container::-webkit-scrollbar {
width: 8px;
}
.log-container::-webkit-scrollbar-track {
background: rgba(0, 0, 0, 0.2);
border-radius: 4px;
}
.log-container::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
border-radius: 4px;
}
.log-container::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.5);
}
.log-entry {
margin-bottom: 10px;
opacity: 0;
animation: fadeIn 0.4s ease-out forwards;
padding-left: 8px;
border-left: 2px solid transparent;
transition: all 0.3s ease;
}
.log-entry:hover {
background: rgba(255, 255, 255, 0.05);
border-left-color: rgba(255, 255, 255, 0.4);
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(-5px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.spinner {
display: inline-block;
width: 18px;
height: 18px;
border: 3px solid rgba(255, 255, 255, 0.3);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.8s linear infinite;
vertical-align: middle;
margin-right: 8px;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.error {
color: #ff5252;
font-weight: 600;
}
.success {
color: #4CAF50;
font-weight: 600;
}
/* Tab导航 */
.tab-navigation {
display: flex;
gap: 10px;
margin-bottom: 30px;
border-bottom: 2px solid rgba(255, 255, 255, 0.2);
}
.tab-button {
flex: 1;
padding: 15px 20px;
background: transparent;
border: none;
color: rgba(255, 255, 255, 0.6);
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
border-bottom: 3px solid transparent;
position: relative;
bottom: -2px;
}
.tab-button:hover {
color: rgba(255, 255, 255, 0.9);
}
.tab-button.active {
color: #fff;
border-bottom-color: #4CAF50;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
animation: fadeIn 0.4s ease-out;
}
/* 完成区域 */
.completion-section {
display: none;
margin-top: 30px;
padding-top: 30px;
border-top: 1px solid rgba(255, 255, 255, 0.2);
text-align: center;
}
.countdown-text {
font-size: 20px;
margin-bottom: 20px;
opacity: 0.9;
}
.countdown-number {
font-size: 64px;
font-weight: 700;
color: #4CAF50;
margin: 20px 0;
text-shadow: 0 2px 20px rgba(76, 175, 80, 0.4);
}
.redirect-button {
background: linear-gradient(135deg, #4CAF50 0%, #8BC34A 100%);
color: white;
border: none;
padding: 16px 48px;
font-size: 18px;
font-weight: 600;
border-radius: 50px;
cursor: pointer;
box-shadow: 0 4px 20px rgba(76, 175, 80, 0.4);
transition: all 0.3s ease;
}
.redirect-button:hover {
transform: translateY(-2px);
box-shadow: 0 6px 30px rgba(76, 175, 80, 0.6);
}
.redirect-button:active {
transform: translateY(0);
}
</style>
</head>
<body>
<div class="container">
<h1>🚀 准备工作区</h1>
<!-- Tab导航 -->
<div class="tab-navigation">
<button class="tab-button active" onclick="switchTab('progress')" id="tabProgress">
📊 进行中
</button>
<button class="tab-button" onclick="switchTab('complete')" id="tabComplete">
✅ 已完成
</button>
</div>
<!-- 进行中Tab -->
<div class="tab-content active" id="progressTab">
<div class="progress-container">
<div class="progress-bar" id="progressBar"></div>
</div>
<div class="status" id="status">
<span class="spinner"></span>
<span>正在连接...</span>
</div>
<div class="log-container" id="logContainer">
<div class="log-entry">等待服务器响应...</div>
</div>
</div>
<!-- 已完成Tab -->
<div class="tab-content" id="completeTab">
<div class="completion-section" style="display: block; margin-top: 0; padding-top: 0; border-top: none;">
<div style="font-size: 48px; margin-bottom: 20px;">✅</div>
<div style="font-size: 24px; margin-bottom: 30px; font-weight: 600;">工作区准备完成!</div>
<div class="countdown-text">即将跳转到 Code Server...</div>
<div class="countdown-number" id="countdown">3</div>
<button class="redirect-button" onclick="redirectNow()">
立即跳转 →
</button>
</div>
</div>
</div>
<script>
const repoURL = '{{REPO_URL}}';
const progressBar = document.getElementById('progressBar');
const status = document.getElementById('status');
const logContainer = document.getElementById('logContainer');
let ws;
let isCompleted = false;
function addLog(message, isError = false) {
const entry = document.createElement('div');
entry.className = 'log-entry' + (isError ? ' error' : '');
entry.textContent = '> ' + message;
logContainer.appendChild(entry);
logContainer.scrollTop = logContainer.scrollHeight;
}
function updateProgress(percent) {
progressBar.style.width = percent + '%';
}
function updateStatus(message, showSpinner = true) {
if (showSpinner) {
status.innerHTML = '<span class="spinner"></span><span>' + message + '</span>';
} else {
status.innerHTML = '<span>' + message + '</span>';
}
}
function connectWebSocket() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsURL = protocol + '//' + window.location.host + '/ws/git-progress';
ws = new WebSocket(wsURL);
ws.onopen = function() {
addLog('WebSocket连接已建立');
// 连接建立后,开始执行git操作
executeGitOperation();
};
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
addLog(data.message);
updateProgress(data.percent);
if (data.status === 'error') {
updateStatus('❌ ' + data.message, false);
status.className = 'status error';
} else if (data.status === 'success') {
updateStatus('✅ ' + data.message, false);
status.className = 'status success';
isCompleted = true;
} else {
updateStatus(data.message, true);
}
};
ws.onerror = function() {
addLog('WebSocket连接错误', true);
};
ws.onclose = function() {
addLog('WebSocket连接已关闭');
};
}
function executeGitOperation() {
updateStatus('正在执行Git操作...', true);
addLog('开始Git操作: ' + repoURL);
fetch('/api/git/execute', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
repo_url: repoURL
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
addLog('✓ 操作成功完成');
// 显示跳转页面
showRedirectPage(data.redirect_url);
} else {
addLog('✗ 操作失败: ' + data.error, true);
updateStatus('操作失败', false);
}
})
.catch(err => {
addLog('✗ 请求失败: ' + err.message, true);
updateStatus('请求失败', false);
});
}
// Tab切换函数
function switchTab(tabName) {
// 更新按钮状态
document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
if (tabName === 'progress') {
document.getElementById('tabProgress').classList.add('active');
document.getElementById('progressTab').classList.add('active');
} else {
document.getElementById('tabComplete').classList.add('active');
document.getElementById('completeTab').classList.add('active');
}
}
// 显示完成页面并启动倒计时
let redirectUrl = '';
let countdownTimer = null;
function showRedirectPage(url) {
redirectUrl = url;
// 等待1秒让进度条停留在100%
setTimeout(() => {
// 切换到已完成tab
switchTab('complete');
// 启动3秒倒计时
let count = 3;
const countdownElement = document.getElementById('countdown');
countdownTimer = setInterval(() => {
count--;
if (count > 0) {
countdownElement.textContent = count;
} else {
clearInterval(countdownTimer);
redirectNow();
}
}, 1000);
}, 1000);
}
// 立即跳转
function redirectNow() {
if (countdownTimer) {
clearInterval(countdownTimer);
}
window.location.href = redirectUrl;
}
// 启动
connectWebSocket();
</script>
</body>
</html>`

View File

@@ -0,0 +1,149 @@
package handlers
import (
"encoding/json"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
// 允许所有来源(生产环境应该做更严格的检查)
return true
},
}
// ProgressMessage WebSocket进度消息结构
type ProgressMessage struct {
Status string `json:"status"` // 状态: checking, cloning, pulling, success, error
Message string `json:"message"` // 消息文本
Percent int `json:"percent"` // 进度百分比 (0-100)
}
// ProgressHub 进度广播中心
type ProgressHub struct {
clients map[string]*websocket.Conn
clientsMux sync.RWMutex
broadcast chan ProgressMessage
}
var (
hub *ProgressHub
hubOnce sync.Once
)
// GetProgressHub 获取进度广播中心单例
func GetProgressHub() *ProgressHub {
hubOnce.Do(func() {
hub = &ProgressHub{
clients: make(map[string]*websocket.Conn),
broadcast: make(chan ProgressMessage, 10),
}
go hub.run()
})
return hub
}
// run 运行广播循环
func (h *ProgressHub) run() {
for msg := range h.broadcast {
h.clientsMux.RLock()
for clientID, conn := range h.clients {
err := conn.WriteJSON(msg)
if err != nil {
// 写入失败,移除客户端
conn.Close()
h.clientsMux.RUnlock()
h.removeClient(clientID)
h.clientsMux.RLock()
}
}
h.clientsMux.RUnlock()
}
}
// addClient 添加客户端
func (h *ProgressHub) addClient(clientID string, conn *websocket.Conn) {
h.clientsMux.Lock()
defer h.clientsMux.Unlock()
h.clients[clientID] = conn
}
// removeClient 移除客户端
func (h *ProgressHub) removeClient(clientID string) {
h.clientsMux.Lock()
defer h.clientsMux.Unlock()
delete(h.clients, clientID)
}
// SendProgress 发送进度消息
func (h *ProgressHub) SendProgress(msg ProgressMessage) {
select {
case h.broadcast <- msg:
case <-time.After(1 * time.Second):
// 超时,丢弃消息
}
}
// GitProgressWS WebSocket处理器
func GitProgressWS() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 升级HTTP连接到WebSocket
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
http.Error(w, "Failed to upgrade to WebSocket", http.StatusInternalServerError)
return
}
defer conn.Close()
// 生成客户端ID
clientID := r.RemoteAddr + "-" + time.Now().Format("20060102150405")
// 添加到hub
hub := GetProgressHub()
hub.addClient(clientID, conn)
defer hub.removeClient(clientID)
// 发送欢迎消息
welcomeMsg := ProgressMessage{
Status: "connected",
Message: "WebSocket连接已建立",
Percent: 0,
}
if err := conn.WriteJSON(welcomeMsg); err != nil {
return
}
// 保持连接,读取客户端消息(主要用于心跳)
for {
_, _, err := conn.ReadMessage()
if err != nil {
// 连接断开
break
}
}
}
}
// SendProgressToClients 辅助函数:向所有客户端发送进度
func SendProgressToClients(status, message string, percent int) {
hub := GetProgressHub()
hub.SendProgress(ProgressMessage{
Status: status,
Message: message,
Percent: percent,
})
}
// SendProgressJSON 辅助函数:发送JSON格式的进度消息
func SendProgressJSON(w http.ResponseWriter, status, message string, percent int) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ProgressMessage{
Status: status,
Message: message,
Percent: percent,
})
}

View File

@@ -0,0 +1,42 @@
package middleware
import (
"net/http"
"github.com/gorilla/sessions"
)
var store = sessions.NewCookieStore([]byte("123456"))
func GetSession(r *http.Request) (*sessions.Session, error) {
return store.Get(r, "transit")
}
// RequireLogin 登录验证中间件
// 检查用户是否已登录,未登录则重定向到OAuth登录页面
func RequireLogin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, err := GetSession(r)
if err != nil {
// Session读取失败,保存原始URL后重定向到登录
session, _ = store.New(r, "transit")
session.Values["redirect_after_login"] = r.URL.RequestURI()
session.Save(r, w)
http.Redirect(w, r, "/oauth/gitea", http.StatusFound)
return
}
// 检查session中是否有用户信息
userID := session.Values["uid"]
if userID == nil {
// 未登录,保存原始URL后重定向到OAuth登录
session.Values["redirect_after_login"] = r.URL.RequestURI()
session.Save(r, w)
http.Redirect(w, r, "/oauth/gitea", http.StatusFound)
return
}
// 已登录,继续处理请求
next.ServeHTTP(w, r)
})
}

45
internal/http/router.go Normal file
View File

@@ -0,0 +1,45 @@
package http
import (
"cs-bridge/internal/config"
"cs-bridge/internal/http/handlers"
"cs-bridge/internal/http/middleware"
"cs-bridge/internal/oauth"
"cs-bridge/pkg/logger"
"fmt"
"net/http"
"github.com/go-chi/chi/v5"
)
type Router struct {
r http.Handler
cfg config.Server
}
func NewRouter(cfg *config.Config, mgr *oauth.Manager) *Router {
r := chi.NewRouter()
r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})
r.Get("/", handlers.Entry(&cfg.CodeServer))
r.Get("/oauth/{provider}", handlers.OauthLogin(mgr))
r.Get("/oauth/{provider}/callback", handlers.OauthCallBack(mgr))
// Git准备相关路由 - 需要登录
r.With(middleware.RequireLogin).Get("/tz", handlers.GitProgressPage())
r.Get("/ws/git-progress", handlers.GitProgressWS())
r.Post("/api/git/execute", handlers.ExecuteGitOperations(cfg))
return &Router{
r: r,
cfg: cfg.Server,
}
}
func (r *Router) ListenAndServe() {
logger.GetLogger().Info(fmt.Sprintf("server is running as: http://localhost:%d", r.cfg.Port))
http.ListenAndServe(fmt.Sprintf(":%d", r.cfg.Port), r.r)
}

111
internal/oauth/gitea.go Normal file
View File

@@ -0,0 +1,111 @@
package oauth
import (
"cs-bridge/internal/auth"
"cs-bridge/internal/config"
"cs-bridge/pkg/httpclient"
"encoding/json"
"fmt"
"net/url"
"time"
)
type Gitea struct {
cfg config.Provider
redirectURI string
}
// Name implements [Provider].
func (g Gitea) Name() string {
return "gitea"
}
// AuthURL implements [Provider].
func (g Gitea) AuthURL(state string) (string, error) {
u, _ := url.Parse(g.cfg.BaseURL + g.cfg.AuthorizeURL)
q := u.Query()
q.Set("client_id", g.cfg.ClientID)
q.Set("redirect_uri", g.redirectURI)
q.Set("response_type", "code")
q.Set("scope", "read:user")
q.Set("state", state)
u.RawQuery = q.Encode()
return u.String(), nil
}
// Exchange implements [Provider].
func (g Gitea) Exchange(code string) (string, error) {
resp, err := httpclient.Default.R().
SetHeader("Accept", "application/json").
SetFormData(map[string]string{
"client_id": g.cfg.ClientID,
"client_secret": g.cfg.ClientSecret,
"code": code,
"grant_type": "authorization_code",
"redirect_uri": g.redirectURI,
}).
Post(fmt.Sprintf("%s%s", g.cfg.BaseURL, g.cfg.TokenURL))
if err != nil {
return "", err
}
var out struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn string `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
}
json.NewDecoder(resp.Body).Decode(&out)
return out.AccessToken, nil
}
// UserInfo implements [Provider].
func (g Gitea) UserInfo(token string) (auth.Identify, error) {
resp, err := httpclient.Default.R().
SetHeader("Authorization", fmt.Sprintf("bearer %s", token)).
Get(fmt.Sprintf("%s%s", g.cfg.BaseURL, g.cfg.UserURL))
if err != nil {
return auth.Identify{}, err
}
var raw raw
json.NewDecoder(resp.Body).Decode(&raw)
return auth.Identify{
Provider: g.Name(),
UserId: fmt.Sprint(raw.ID),
Username: raw.Login,
Avatar: raw.AvatarURL,
}, nil
}
func NewGitea(cfg config.Provider, redirectURI string) Gitea {
return Gitea{
cfg: cfg,
redirectURI: redirectURI,
}
}
type raw struct {
ID int `json:"id"`
Login string `json:"login"`
LoginName string `json:"login_name"`
SourceID int `json:"source_id"`
FullName string `json:"full_name"`
Email string `json:"email"`
AvatarURL string `json:"avatar_url"`
HTMLURL string `json:"html_url"`
Language string `json:"language"`
IsAdmin bool `json:"is_admin"`
LastLogin time.Time `json:"last_login"`
Created time.Time `json:"created"`
Restricted bool `json:"restricted"`
Active bool `json:"active"`
ProhibitLogin bool `json:"prohibit_login"`
Location string `json:"location"`
Website string `json:"website"`
Description string `json:"description"`
Visibility string `json:"visibility"`
FollowersCount int `json:"followers_count"`
FollowingCount int `json:"following_count"`
StarredReposCount int `json:"starred_repos_count"`
Username string `json:"username"`
}

View File

@@ -0,0 +1,86 @@
package oauth
import (
"cs-bridge/internal/auth"
"cs-bridge/pkg/lua"
"fmt"
lua2 "github.com/yuin/gopher-lua"
)
type LuaProvider struct {
model ProviderModel
engine *lua.Engine
redirectURI string
}
// NewLuaProvider creates a new Lua-based provider
func NewLuaProvider(model ProviderModel, redirectURI, scriptPath string) (*LuaProvider, error) {
engine := lua.New()
// Register all API modules (http, json, log, util)
engine.RegisterAPI()
// Load the Lua script
if err := engine.LoadFile(scriptPath); err != nil {
engine.Close()
return nil, err
}
return &LuaProvider{
model: model,
engine: engine,
redirectURI: redirectURI,
}, nil
}
// Close cleans up the Lua engine
func (p *LuaProvider) Close() {
p.engine.Close()
}
// Name implements [Provider].
func (p *LuaProvider) Name() string {
return p.model.Name
}
// luaConfig constructs the config table passed to Lua functions
func (p *LuaProvider) luaConfig() *lua2.LTable {
L := p.engine.L
config := L.NewTable()
config.RawSetString("client_id", lua2.LString(p.model.ClientID))
config.RawSetString("client_secret", lua2.LString(p.model.ClientSecret))
config.RawSetString("base_url", lua2.LString(p.model.BaseURL))
config.RawSetString("authorize_url", lua2.LString(p.model.AuthorizeURL))
config.RawSetString("token_url", lua2.LString(p.model.TokenURL))
config.RawSetString("user_url", lua2.LString(p.model.UserURL))
config.RawSetString("redirect_uri", lua2.LString(p.redirectURI))
return config
}
// AuthURL implements [Provider].
func (p *LuaProvider) AuthURL(state string) (string, error) {
cfg := p.luaConfig()
return p.engine.CallString("auth_url", cfg, lua2.LString(state))
}
// Exchange implements [Provider].
func (p *LuaProvider) Exchange(code string) (string, error) {
cfg := p.luaConfig()
return p.engine.CallString("exchange", cfg, lua2.LString(code))
}
// UserInfo implements [Provider].
func (p *LuaProvider) UserInfo(token string) (auth.Identify, error) {
cfg := p.luaConfig()
var userInfo auth.Identify
if err := p.engine.CallStruct("user_info", &userInfo, cfg, lua2.LString(token)); err != nil {
return auth.Identify{}, fmt.Errorf("failed to get user info: %w", err)
}
// Set the provider name
userInfo.Provider = p.model.Name
return userInfo, nil
}

25
internal/oauth/manager.go Normal file
View File

@@ -0,0 +1,25 @@
package oauth
import "fmt"
type Manager struct {
provider map[string]Provider
}
func NewManager() *Manager {
return &Manager{
provider: map[string]Provider{},
}
}
func (m *Manager) Register(p Provider) {
m.provider[p.Name()] = p
}
func (m *Manager) Get(name string) (Provider, error) {
p, ok := m.provider[name]
if !ok {
return nil, fmt.Errorf("oauth provider not found: %s", name)
}
return p, nil
}

22
internal/oauth/model.go Normal file
View File

@@ -0,0 +1,22 @@
package oauth
import "time"
type ProviderModel struct {
ID uint `gorm:"primaryKey"`
Name string `gorm:"uniqueIndex"`
Type string
BaseURL string
ClientID string
ClientSecret string
AuthorizeURL string
TokenURL string
UserURL string
LuaScript string
Enabled bool
CreatedAt time.Time
UpdatedAt time.Time
}

View File

@@ -0,0 +1,16 @@
package oauth
import "cs-bridge/internal/auth"
type UserInfo struct {
ID string `json:"id"`
Username string `json:"username"`
Avatar string `json:"avatar_url"`
}
type Provider interface {
Name() string
AuthURL(state string) (string, error)
Exchange(code string) (string, error)
UserInfo(token string) (auth.Identify, error)
}

12
internal/oauth/state.go Normal file
View File

@@ -0,0 +1,12 @@
package oauth
import (
"crypto/rand"
"encoding/hex"
)
func NewState() string {
b := make([]byte, 16)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}