Skip to content

Commit

Permalink
feat: middleware and secrets
Browse files Browse the repository at this point in the history
Signed-off-by: Jad Chahed <[email protected]>
  • Loading branch information
Jad31 committed Aug 26, 2024
1 parent d0a4527 commit 279a061
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 12 deletions.
2 changes: 1 addition & 1 deletion .air.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[build]
bin = "./main api --config ./config/dev/config.yaml --secrets ./config/dev/secrets.yaml --web-port=9090 --web-vitess-path=../"
bin = "./main admin --config ./config/dev/config.yaml --secrets ./config/dev/secrets.yaml --web-port=9090 --web-vitess-path=../"
cmd = "go build ./go/main.go"
main = "main.go"
include_ext = ["go", "html"]
Expand Down
4 changes: 4 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ require (
github.com/fatih/color v1.17.0 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.4 // indirect
github.com/gin-contrib/sessions v1.0.1 // 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
Expand All @@ -60,6 +61,9 @@ require (
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/go-github/v62 v62.0.0 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/gorilla/context v1.1.2 // indirect
github.com/gorilla/securecookie v1.1.2 // indirect
github.com/gorilla/sessions v1.2.2 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/hashicorp/golang-lru v1.0.2 // indirect
github.com/hashicorp/hcl v1.0.1-vault-5 // indirect
Expand Down
8 changes: 8 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ github.com/gabriel-vasile/mimetype v1.4.4 h1:QjV6pZ7/XZ7ryI2KuyeEDE8wnh7fHP9YnQy
github.com/gabriel-vasile/mimetype v1.4.4/go.mod h1:JwLei5XPtWdGiMFB5Pjle1oEeoSeEuJfJE+TtfvdB/s=
github.com/gin-contrib/cors v1.7.2 h1:oLDHxdg8W/XDoN/8zamqk/Drgt4oVZDvaV0YmvVICQw=
github.com/gin-contrib/cors v1.7.2/go.mod h1:SUJVARKgQ40dmrzgXEVxj2m7Ig1v1qIboQkPDTQ9t2E=
github.com/gin-contrib/sessions v1.0.1 h1:3hsJyNs7v7N8OtelFmYXFrulAf6zSR7nW/putcPEHxI=
github.com/gin-contrib/sessions v1.0.1/go.mod h1:ouxSFM24/OgIud5MJYQJLpy6AwxQ5EYO9yLhbtObGkM=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
Expand Down Expand Up @@ -83,6 +85,12 @@ github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o=
github.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM=
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
github.com/gorilla/sessions v1.2.2 h1:lqzMYz6bOfvn2WriPUjNByzeXIlVzURcPmgMczkmTjY=
github.com/gorilla/sessions v1.2.2/go.mod h1:ePLdVu+jbEgHH+KWw8I1z2wqd0BAdAQh/8LRvBeoNcQ=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
Expand Down
24 changes: 19 additions & 5 deletions go/admin/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import (
"time"

"github.com/gin-contrib/cors"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/spf13/cobra"
"github.com/spf13/viper"
Expand All @@ -35,9 +37,11 @@ import (
const (
ErrorIncorrectConfiguration = "incorrect configuration"

flagPort = "web-port"
flagVitessPath = "web-vitess-path"
flagMode = "web-mode"
flagPort = "web-port"
flagVitessPath = "web-vitess-path"
flagMode = "web-mode"
flagAdminAppId = "gh-admin-app-id"
flagAdminAppSecret = "gh-admin-app-secret"
)

type Admin struct {
Expand All @@ -46,6 +50,9 @@ type Admin struct {

localVitessPath string

ghAppId string
ghAppSecret string

dbCfg *psdb.Config
dbClient *psdb.Client

Expand All @@ -56,10 +63,14 @@ func (a *Admin) AddToCommand(cmd *cobra.Command) {
cmd.Flags().StringVar(&a.port, flagPort, "8080", "Port used for the HTTP server")
cmd.Flags().StringVar(&a.localVitessPath, flagVitessPath, "/", "Absolute path where the vitess directory is located or where it should be cloned")
cmd.Flags().Var(&a.Mode, flagMode, "Specify the mode on which the server will run")
cmd.Flags().StringVar(&a.ghAppId, flagAdminAppId, "", "The ID of the GitHub App")
cmd.Flags().StringVar(&a.ghAppSecret, flagAdminAppSecret, "", "The secret of the GitHub App")

_ = viper.BindPFlag(flagPort, cmd.Flags().Lookup(flagPort))
_ = viper.BindPFlag(flagVitessPath, cmd.Flags().Lookup(flagVitessPath))
_ = viper.BindPFlag(flagMode, cmd.Flags().Lookup(flagMode))
_ = viper.BindPFlag(flagAdminAppId, cmd.Flags().Lookup(flagAdminAppId))
_ = viper.BindPFlag(flagAdminAppSecret, cmd.Flags().Lookup(flagAdminAppSecret))

if a.dbCfg == nil {
a.dbCfg = &psdb.Config{}
Expand All @@ -68,7 +79,7 @@ func (a *Admin) AddToCommand(cmd *cobra.Command) {
}

func (a *Admin) isReady() bool {
return a.port != "" && a.localVitessPath != ""
return a.port != "" && a.localVitessPath != "" && a.ghAppId != "" && a.ghAppSecret != ""
}

func (a *Admin) Init() error {
Expand Down Expand Up @@ -112,6 +123,9 @@ func (a *Admin) Run() error {
a.prepareGin()
a.router = gin.Default()

store := cookie.NewStore([]byte("secret"))
a.router.Use(sessions.Sessions("mysession", store))

a.router.Static("/assets", filepath.Join(basepath, "assets"))

a.router.LoadHTMLGlob(filepath.Join(basepath, "templates/*"))
Expand All @@ -129,7 +143,7 @@ func (a *Admin) Run() error {
a.router.GET("/", a.login)
a.router.GET("/login", a.handleGitHubLogin)
a.router.GET("/auth/callback", a.handleGitHubCallback)
a.router.GET("/dashboard", a.dashboard)
a.router.GET("/dashboard", a.authMiddleware(), a.dashboard)

return a.router.Run(":" + a.port)
}
Expand Down
32 changes: 26 additions & 6 deletions go/admin/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ import (
"context"
"log"
"net/http"
"os"
"strings"

"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
goGithub "github.com/google/go-github/github"
"golang.org/x/oauth2"
Expand All @@ -33,8 +33,8 @@ import (

var (
oauthConf = &oauth2.Config{
ClientID: os.Getenv("GITHUB_CLIENT_ID"),
ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
ClientID: "",
ClientSecret: "",
Scopes: []string{"read:org"}, // Request access to read organization membership
Endpoint: github.Endpoint,
RedirectURL: "http://localhost:9090/auth/callback",
Expand All @@ -50,11 +50,28 @@ func (a *Admin) dashboard(c *gin.Context) {
a.render(c, gin.H{}, "base.html")
}

func (a *Admin) authMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
user := session.Get("user")
if user == nil {
// User not authenticated, redirect to login
c.Redirect(http.StatusSeeOther, "/login")
c.Abort()
return
}

// User is authenticated, proceed to the next handler
c.Next()
}
}

func (a *Admin) handleGitHubLogin(c *gin.Context) {
oauthConf.ClientID = a.ghAppId
oauthConf.ClientSecret = a.ghAppSecret
url := oauthConf.AuthCodeURL(oauthStateString, oauth2.AccessTypeOnline)
c.Redirect(http.StatusTemporaryRedirect, url)
}

func (a *Admin) handleGitHubCallback(c *gin.Context) {
state := c.Query("state")
if state != oauthStateString {
Expand Down Expand Up @@ -91,13 +108,16 @@ func (a *Admin) handleGitHubCallback(c *gin.Context) {
}

if isMaintainer {
session := sessions.Default(c)
session.Set("user", user.GetLogin())
session.Save()

c.Redirect(http.StatusSeeOther, "/dashboard")
} else {
log.Printf("User %s is not a maintainer in %s organization", user.GetLogin(), orgName)
c.String(http.StatusForbidden, "You must be a maintainer in the %s organization to access this page.", orgName)
}
}

func (a *Admin) checkUserOrgMembership(client *goGithub.Client, username, orgName string) (bool, error) {
teams, _, err := client.Teams.ListTeams(context.Background(), orgName, nil)
if err != nil {
Expand All @@ -108,7 +128,7 @@ func (a *Admin) checkUserOrgMembership(client *goGithub.Client, username, orgNam
membership, _, err := client.Teams.GetTeamMembership(context.Background(), team.GetID(), username)
log.Println(membership)
if err != nil {
log.Println(err.Error())
log.Println(err.Error())
if strings.Contains(err.Error(), "404 Not Found") {
return false, nil
}
Expand Down

0 comments on commit 279a061

Please sign in to comment.