Skip to content

Commit 0895126

Browse files
committed
simplify router structure
1 parent 1cc3468 commit 0895126

File tree

15 files changed

+248
-208
lines changed

15 files changed

+248
-208
lines changed

cmd/server/main.go

Lines changed: 2 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,11 @@ import (
1010
"time"
1111

1212
"github.com/getsentry/sentry-go"
13-
sentrygin "github.com/getsentry/sentry-go/gin"
1413

15-
"github.com/gin-gonic/gin"
1614
"github.com/gitznik/robswebhub/internal/auth"
1715
"github.com/gitznik/robswebhub/internal/config"
1816
"github.com/gitznik/robswebhub/internal/database"
19-
"github.com/gitznik/robswebhub/internal/handlers"
20-
"github.com/gitznik/robswebhub/internal/middleware"
21-
"github.com/gitznik/robswebhub/internal/sessions"
17+
"github.com/gitznik/robswebhub/internal/router"
2218
)
2319

2420
func main() {
@@ -66,7 +62,7 @@ func main() {
6662
if err != nil {
6763
log.Fatalf("Could not setup authenticator: %v", err)
6864
}
69-
router := setupRouter(cfg, queries, auth)
65+
router := router.SetupRouter(cfg, queries, auth)
7066

7167
// Create HTTP server
7268
srv := &http.Server{
@@ -97,58 +93,3 @@ func main() {
9793

9894
log.Print("Server exiting")
9995
}
100-
101-
func setupRouter(cfg *config.Config, queries *database.Queries, authenticator *auth.Authenticator) *gin.Engine {
102-
// Set Gin mode based on environment
103-
if os.Getenv("APP_ENVIRONMENT") == "production" {
104-
gin.SetMode(gin.ReleaseMode)
105-
}
106-
107-
router := gin.Default()
108-
router.Use(sentrygin.New(sentrygin.Options{Repanic: true}))
109-
router.Use(middleware.ErrorHandler)
110-
111-
sessionMiddleware, err := sessions.SetupSessionMiddleware(cfg.Auth.CookieAuthKey, cfg.Auth.CookieEncryptionKey)
112-
if err != nil {
113-
log.Fatalf("Could not attach session information: %v", err)
114-
}
115-
router.Use(sessionMiddleware)
116-
router.Use(middleware.LoginStatus)
117-
118-
// Serve static files
119-
router.Static("/static", "./static")
120-
router.Static("/images", "./static/images")
121-
router.StaticFile("/favicon.ico", "./static/images/favicon.ico")
122-
123-
// Create handlers
124-
h := handlers.New(queries, cfg)
125-
126-
// Routes
127-
router.GET("/", h.Home)
128-
router.HEAD("/", h.HomeHead)
129-
router.GET("/about", h.About)
130-
131-
// Scores routes
132-
scores := router.Group("/scores")
133-
{
134-
scores.GET("", h.ScoresIndex)
135-
scores.POST("/single", h.ScoresSingle)
136-
scores.POST("/batch", h.ScoresBatch)
137-
scores.GET("/single-form", h.SingleScoreForm)
138-
scores.GET("/batch-form", h.BatchScoreForm)
139-
scores.GET("/chart/:id", h.ScoresChart)
140-
}
141-
142-
router.GET("/login", h.MakeLogin(authenticator))
143-
router.GET("/logout", h.Logout)
144-
router.GET("/callback", h.MakeCallback(authenticator))
145-
gamekeeper := router.Group("/gamekeeper")
146-
gamekeeper.Use(middleware.IsAuthenticated)
147-
{
148-
gamekeeper.GET("", h.GamesIndex)
149-
gamekeeper.GET("/signup", h.SignUp)
150-
gamekeeper.POST("/signup", h.DoSignUp)
151-
}
152-
153-
return router
154-
}

internal/handlers/about.go

Lines changed: 0 additions & 17 deletions
This file was deleted.

internal/handlers/auth/callback.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package auth
2+
3+
import (
4+
"errors"
5+
"net/http"
6+
7+
"github.com/gin-contrib/sessions"
8+
"github.com/gin-gonic/gin"
9+
"github.com/gitznik/robswebhub/internal/auth"
10+
)
11+
12+
func (h *Handler) Callback(c *gin.Context) {
13+
session := sessions.Default(c)
14+
if c.Query("state") != session.Get("state") {
15+
c.String(http.StatusBadRequest, "Invalid state parameter.")
16+
return
17+
}
18+
19+
// Exchange an authorization code for a token.
20+
token, err := h.authenticator.Exchange(c.Request.Context(), c.Query("code"))
21+
if err != nil {
22+
c.String(http.StatusUnauthorized, "Failed to convert an authorization code into a token.")
23+
return
24+
}
25+
26+
idToken, err := h.authenticator.VerifyIDToken(c.Request.Context(), token)
27+
if err != nil {
28+
_ = c.Error(errors.New("Failed to verify ID Token."))
29+
return
30+
}
31+
32+
var profile auth.UserProfile
33+
if err := idToken.Claims(&profile); err != nil {
34+
c.String(http.StatusInternalServerError, err.Error())
35+
return
36+
}
37+
38+
session.Set("access_token", token.AccessToken)
39+
session.Set("profile", profile)
40+
if err := session.Save(); err != nil {
41+
_ = c.Error(err)
42+
return
43+
}
44+
45+
// Redirect to logged in page.
46+
c.Redirect(http.StatusTemporaryRedirect, "/")
47+
}

internal/handlers/auth/handler.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package auth
2+
3+
import (
4+
"github.com/gin-gonic/gin"
5+
"github.com/gitznik/robswebhub/internal/auth"
6+
"github.com/gitznik/robswebhub/internal/config"
7+
)
8+
9+
type Handler struct {
10+
cfg *config.Config
11+
authenticator *auth.Authenticator
12+
}
13+
14+
func New(cfg *config.Config, authenticator *auth.Authenticator) *Handler {
15+
return &Handler{
16+
cfg: cfg,
17+
authenticator: authenticator,
18+
}
19+
}
20+
21+
func (h *Handler) RegisterRoute(rg *gin.RouterGroup) {
22+
rg.GET("/login", h.Login)
23+
rg.GET("/logout", h.Logout)
24+
rg.GET("/callback", h.Callback)
25+
}

internal/handlers/auth/login.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package auth
2+
3+
import (
4+
"crypto/rand"
5+
"encoding/base64"
6+
"net/http"
7+
8+
"github.com/gin-contrib/sessions"
9+
"github.com/gin-gonic/gin"
10+
)
11+
12+
func (h *Handler) Login(c *gin.Context) {
13+
state, err := generateRandomState()
14+
if err != nil {
15+
_ = c.Error(err)
16+
return
17+
}
18+
19+
// Save the state inside the session.
20+
session := sessions.Default(c)
21+
session.Set("state", state)
22+
if err := session.Save(); err != nil {
23+
_ = c.Error(err)
24+
return
25+
}
26+
27+
c.Redirect(http.StatusTemporaryRedirect, h.authenticator.AuthCodeURL(state))
28+
}
29+
30+
func generateRandomState() (string, error) {
31+
b := make([]byte, 32)
32+
_, err := rand.Read(b)
33+
if err != nil {
34+
return "", err
35+
}
36+
37+
state := base64.StdEncoding.EncodeToString(b)
38+
39+
return state, nil
40+
}

internal/handlers/logout.go renamed to internal/handlers/auth/logout.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package handlers
1+
package auth
22

33
import (
44
"net/http"

internal/handlers/callback.go

Lines changed: 0 additions & 49 deletions
This file was deleted.

internal/handlers/games.go renamed to internal/handlers/games/games.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package handlers
1+
package games
22

33
import (
44
"errors"

internal/handlers/games/handler.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package games
2+
3+
import (
4+
"github.com/gin-gonic/gin"
5+
"github.com/gitznik/robswebhub/internal/database"
6+
"github.com/gitznik/robswebhub/internal/middleware"
7+
)
8+
9+
type Handler struct {
10+
queries *database.Queries
11+
}
12+
13+
func New(queries *database.Queries) *Handler {
14+
return &Handler{
15+
queries: queries,
16+
}
17+
}
18+
19+
func (h *Handler) RegisterRoute(rg *gin.RouterGroup) {
20+
rg.Use(middleware.IsAuthenticated)
21+
{
22+
rg.GET("", h.GamesIndex)
23+
rg.GET("/signup", h.SignUp)
24+
rg.POST("/signup", h.DoSignUp)
25+
}
26+
}

internal/handlers/home.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,12 @@ func New(queries *database.Queries, cfg *config.Config) *Handler {
2323
}
2424
}
2525

26+
func (h *Handler) RegisterRoute(rg *gin.RouterGroup) {
27+
rg.GET("/", h.Home)
28+
rg.HEAD("/", h.HomeHead)
29+
rg.GET("/about", h.About)
30+
}
31+
2632
func (h *Handler) Home(c *gin.Context) {
2733
redirectError := c.Query("error")
2834
component := pages.Home(redirectError, c.GetBool(middleware.LoginKey))
@@ -35,3 +41,11 @@ func (h *Handler) Home(c *gin.Context) {
3541
func (h *Handler) HomeHead(c *gin.Context) {
3642
c.Status(http.StatusOK)
3743
}
44+
45+
func (h *Handler) About(c *gin.Context) {
46+
component := pages.About(c.GetBool(middleware.LoginKey))
47+
if err := component.Render(c.Request.Context(), c.Writer); err != nil {
48+
_ = c.Error(errors.New("Failed to render page"))
49+
return
50+
}
51+
}

0 commit comments

Comments
 (0)