Skip to content

feat: add server-side oauth for frontend #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions .env
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
GITHUB_WEBHOOK_SECRET=
GITHUB_POLLING_INTERVAL=
GITHUB_POLLING_TIMEOUT=
GITHUB_CLIENT_ID=your_client_id
GITHUB_CLIENT_SECRET=your_client_secret
JWT_SECRET=your_jwt_secret
FRONTEND_URL=http://localhost:3000
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001,https://your-prod-domain.com
4 changes: 4 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,20 @@ require (
github.com/ProtonMail/go-crypto v0.0.0-20230217124315-7d5c6f04bbb8 // indirect
github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/cloudflare/circl v1.1.0 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/golang-jwt/jwt/v5 v5.2.1 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
Expand All @@ -46,6 +49,7 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/redis/go-redis/v9 v9.7.0 // indirect
github.com/sagikazarmark/locafero v0.4.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
Expand Down
8 changes: 8 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cloudflare/circl v1.1.0 h1:bZgT/A+cikZnKIwn7xL2OBj012Bmvho/o6RpRvv3GKY=
github.com/cloudflare/circl v1.1.0/go.mod h1:prBCrKB9DV4poKZY1l9zBXg2QJY7mvgRvtMxxK7fi4I=
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
Expand All @@ -15,6 +17,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
Expand All @@ -35,6 +39,8 @@ github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBEx
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
Expand Down Expand Up @@ -85,6 +91,8 @@ github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E=
github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ=
Expand Down
173 changes: 173 additions & 0 deletions pkg/api/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
package api

import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"time"

"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/moosh3/github-actions-aggregator/pkg/config"
"github.com/moosh3/github-actions-aggregator/pkg/db"
"github.com/moosh3/github-actions-aggregator/pkg/db/models"
"github.com/redis/go-redis/v9"
"golang.org/x/oauth2"
"golang.org/x/oauth2/github"
)

type OAuthState struct {
State string
TenantID string
ReturnTo string
}

// Redis client for storing state
var redisClient = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})

func generateState() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(b), nil
}

func getGithubOAuthConfig(cfg *config.Config) *oauth2.Config {
return &oauth2.Config{
ClientID: cfg.GitHub.ClientID,
ClientSecret: cfg.GitHub.ClientSecret,
Scopes: []string{"user:email", "read:user"},
Endpoint: github.Endpoint,
RedirectURL: fmt.Sprintf("%s/auth/github/callback", cfg.APIURL),
}
}

func handleGithubLogin(c *gin.Context, cfg *config.Config) {
// Generate random state
state, err := generateState()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate state"})
return
}

// Store state with tenant info in Redis
oauthState := OAuthState{
State: state,
ReturnTo: c.Query("returnTo"), // Optional return URL
}

stateJSON, err := json.Marshal(oauthState)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to marshal state"})
return
}

// Store state in Redis with 15-minute expiration
err = redisClient.Set(context.Background(),
fmt.Sprintf("oauth_state:%s", state),
string(stateJSON),
15*time.Minute,
).Err()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to store state"})
return
}

oauthConfig := getGithubOAuthConfig(cfg)

// Generate authorization URL
authURL := oauthConfig.AuthCodeURL(
state,
oauth2.AccessTypeOnline,
)

// Redirect to GitHub
c.Redirect(http.StatusTemporaryRedirect, authURL)
}

func handleGithubCallback(c *gin.Context, cfg *config.Config) {
code := c.Query("code")
state := c.Query("state")

// Validate state
stateKey := fmt.Sprintf("oauth_state:%s", state)
stateJSON, err := redisClient.Get(context.Background(), stateKey).Result()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid or expired state"})
return
}

// Parse stored state
var oauthState OAuthState
if err := json.Unmarshal([]byte(stateJSON), &oauthState); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid state data"})
return
}

// Delete used state
redisClient.Del(context.Background(), stateKey)

oauthConfig := getGithubOAuthConfig(cfg)

token, err := oauthConfig.Exchange(c, code)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to exchange token"})
return
}

// Get GitHub user info
client := oauthConfig.Client(c, token)
resp, err := client.Get("https://api.github.com/user")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to get user info"})
return
}
defer resp.Body.Close()

var githubUser models.GitHubUser
if err := json.NewDecoder(resp.Body).Decode(&githubUser); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to decode user info"})
return
}

// Create or update user in your database
user, err := db.UpdateUser(models.GitHubUser{
Email: githubUser.Email,
Username: githubUser.Login,
Name: githubUser.Name,
AvatarURL: githubUser.AvatarURL,
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create/update user"})
return
}

// Generate JWT
jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": user.ID,
"email": user.Email,
"username": user.Username,
"exp": time.Now().Add(24 * time.Hour).Unix(),
})

tokenString, err := jwtToken.SignedString([]byte(cfg.GitHub.JWTSecret))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create token"})
return
}

// Determine redirect URL
redirectURL := fmt.Sprintf("https://%s/auth/callback?token=%s", tenant.Domain, tokenString)
if oauthState.ReturnTo != "" {
// Validate and sanitize ReturnTo URL here
redirectURL = fmt.Sprintf("%s&returnTo=%s", redirectURL, oauthState.ReturnTo)
}

c.Redirect(http.StatusTemporaryRedirect, redirectURL)
}
84 changes: 84 additions & 0 deletions pkg/api/middleware.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,87 @@
package api

import (
"net/http"
"os"
"strings"

"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/moosh3/github-actions-aggregator/pkg/config"
)

// Middleware functions for request logging, authentication checks, etc.
func corsMiddleware() gin.HandlerFunc {
allowedOrigins := strings.Split(os.Getenv("ALLOWED_ORIGINS"), ",")
return func(c *gin.Context) {
origin := c.Request.Header.Get("Origin")
for _, allowedOrigin := range allowedOrigins {
if origin == allowedOrigin {
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
break
}
}
c.Writer.Header().Set("Access-Control-Allow-Origin", os.Getenv("FRONTEND_URL"))
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}

c.Next()
}
}

func authMiddleware(config *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
tokenString := c.GetHeader("Authorization")
if tokenString == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "No authorization header"})
c.Abort()
return
}

// Remove "Bearer " prefix if present
if len(tokenString) > 7 && tokenString[:7] == "Bearer " {
tokenString = tokenString[7:]
}

token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte(config.GitHub.JWTSecret), nil
})

if err != nil || !token.Valid {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
c.Abort()
return
}

claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token claims"})
c.Abort()
return
}

c.Set("userId", claims["userId"])
c.Set("email", claims["email"])
c.Set("username", claims["username"])

c.Next()
}
}

func getCurrentUser(c *gin.Context) {
userId, _ := c.Get("userId")
email, _ := c.Get("email")
username, _ := c.Get("username")

c.JSON(http.StatusOK, gin.H{
"id": userId,
"email": email,
"username": username,
})
}
12 changes: 11 additions & 1 deletion pkg/api/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import (
func StartServer(cfg *config.Config, db *db.Database, githubClient *github.Client, worker *worker.WorkerPool) {
r := gin.Default()

// Enable CORS
r.Use(corsMiddleware())

// Public routes for Github OAuth
r.GET("/login", auth.GitHubLogin)
r.GET("/callback", auth.GitHubCallback)
Expand All @@ -20,8 +23,15 @@ func StartServer(cfg *config.Config, db *db.Database, githubClient *github.Clien
webhookHandler := github.NewWebhookHandler(db, githubClient, cfg.GitHub.WebhookSecret, worker)
r.POST("/webhook", webhookHandler.HandleWebhook)

auth := r.Group("/auth")
{
auth.GET("/github/login", handleGithubLogin(cfg))
auth.GET("/github/callback", handleGithubCallback(cfg))
auth.GET("/user", authMiddleware(cfg), getCurrentUser)
}

// Require authentication for all repository routes
protected := r.Group("/repositories", auth.AuthMiddleware())
protected := r.Group("/repositories", authMiddleware(cfg))
{
protected.GET("", GetRepositories)
protected.GET("/:repoId", GetRepository)
Expand Down
6 changes: 6 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
type GitHubConfig struct {
ClientID string
ClientSecret string
JWTSecret string
AccessToken string
WebhookSecret string
}
Expand All @@ -23,6 +24,8 @@ type DatabaseConfig struct {
type Config struct {
ServerPort string
LogLevel string
FrontendURL string
APIURL string
GitHub GitHubConfig
Database DatabaseConfig
PollingWorkerPoolSize int
Expand All @@ -42,11 +45,14 @@ func LoadConfig() *Config {
return &Config{
ServerPort: viper.GetString("server.port"),
LogLevel: viper.GetString("log.level"),
FrontendURL: viper.GetString("frontend.url"),
APIURL: viper.GetString("api.url"),
PollingWorkerPoolSize: viper.GetInt("polling_worker_pool_size"),
WebhookWorkerPoolSize: viper.GetInt("webhook_worker_pool_size"),
GitHub: GitHubConfig{
ClientID: viper.GetString("github.client_id"),
ClientSecret: viper.GetString("github.client_secret"),
JWTSecret: viper.GetString("github.jwt_secret"),
AccessToken: viper.GetString("github.access_token"),
WebhookSecret: viper.GetString("github.webhook_secret"),
},
Expand Down
Loading
Loading