Skip to content

Commit 9de41bf

Browse files
committed
add custom context and refactor
1 parent 94e9462 commit 9de41bf

File tree

10 files changed

+146
-148
lines changed

10 files changed

+146
-148
lines changed

internal/handlers/_template.go

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

internal/handlers/handlers.go

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

internal/handlers/session.go

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package handlers
22

33
import (
4-
"context"
54
"net/http"
5+
"sandbox-go-api-sqlboiler-rest-auth/internal/middleware"
66
"sandbox-go-api-sqlboiler-rest-auth/models"
77
"time"
88

@@ -19,22 +19,23 @@ type CreateSessionRequest struct {
1919
Password string `json:"password"`
2020
}
2121

22-
func (h *Handlers) CreateSession(c echo.Context) error {
23-
ctx := context.Background()
22+
func CreateSession(c echo.Context) error {
23+
cc := c.(*middleware.CustomContext)
24+
ctx := cc.Request().Context()
2425
req := new(CreateUserRequest)
2526
if err := c.Bind(req); err != nil {
2627
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
2728
}
2829

29-
ok, _ := models.Users(qm.Where("email = ?", req.Email)).Exists(ctx, h.db)
30+
ok, _ := models.Users(qm.Where("email = ?", req.Email)).Exists(ctx, cc.DB)
3031
if !ok {
3132
return echo.NewHTTPError(http.StatusNotFound, http.StatusText(http.StatusNotFound))
3233
}
33-
u, err := models.Users(qm.Where("email = ?", req.Email)).One(ctx, h.db)
34+
u, err := models.Users(qm.Where("email = ?", req.Email)).One(ctx, cc.DB)
3435
if err != nil {
3536
return echo.NewHTTPError(http.StatusInternalServerError)
3637
}
37-
h.logger.Info(u)
38+
cc.ZapLogger.Info(u)
3839
if u.HashedPassword != req.Password {
3940
return echo.NewHTTPError(http.StatusBadRequest)
4041
}
@@ -44,12 +45,12 @@ func (h *Handlers) CreateSession(c echo.Context) error {
4445
s.ID = uid.String()
4546
s.UserID = u.ID
4647
s.ExpiresAt = time.Now().Add(time.Hour * 24 * 30)
47-
err = s.Insert(ctx, h.db, boil.Infer())
48+
err = s.Insert(ctx, cc.DB, boil.Infer())
4849
if err != nil {
4950
return echo.NewHTTPError(http.StatusInternalServerError)
5051
}
5152

52-
encoded, err := h.secureCookie.Encode("session", s.ID)
53+
encoded, err := cc.SecureCookie.Encode("session", s.ID)
5354
if err != nil {
5455
return echo.NewHTTPError(http.StatusInternalServerError)
5556
}
@@ -58,14 +59,16 @@ func (h *Handlers) CreateSession(c echo.Context) error {
5859
Value: encoded,
5960
Path: "/",
6061
Expires: time.Now().Add(time.Hour * 24 * 30),
61-
Secure: !h.cfg.IsDev,
62+
Secure: !cc.Config.IsDev,
6263
HttpOnly: true,
6364
SameSite: 2,
6465
}
6566
c.SetCookie(cookie)
6667
return c.NoContent(http.StatusNoContent)
6768
}
6869

69-
func (h *Handlers) DeleteSession(c echo.Context) error {
70+
func DeleteSession(c echo.Context) error {
71+
//cc := c.(*customcontext.CustomContext)
72+
//ctx := cc.Request().Context()
7073
return c.NoContent(http.StatusNoContent)
7174
}

internal/handlers/status.go

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,19 @@ package handlers
22

33
import (
44
"net/http"
5-
"sandbox-go-api-sqlboiler-rest-auth/models"
5+
"sandbox-go-api-sqlboiler-rest-auth/internal/middleware"
66

77
"github.com/labstack/echo/v4"
88
)
99

10-
type CookieValue struct {
11-
UserID int
12-
Name string
13-
}
10+
func GetStatus(c echo.Context) error {
11+
cc := c.(*middleware.CustomContext)
1412

15-
func (h *Handlers) GetStatus(c echo.Context) error {
16-
var u *models.User
17-
uv := c.Get("user")
18-
if uv != nil {
19-
u = uv.(*models.User)
20-
h.logger.Debug("user data?", u)
13+
u := cc.CurrentUser
14+
if u != nil {
15+
cc.ZapLogger.Debug("user data?", u)
2116
} else {
22-
h.logger.Debug("not set user session")
17+
cc.ZapLogger.Debug("not set user session")
2318
}
2419
return c.String(http.StatusOK, "server is running")
2520
}

internal/handlers/user.go

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
package handlers
22

33
import (
4-
"context"
54
"errors"
65
"net/http"
6+
"sandbox-go-api-sqlboiler-rest-auth/internal/middleware"
77
"sandbox-go-api-sqlboiler-rest-auth/models"
88
"time"
99

@@ -25,13 +25,14 @@ type UsersData struct {
2525
Users *[]PublicUser `json:"users"`
2626
}
2727

28-
func (h *Handlers) GetUsers(c echo.Context) error {
29-
ctx := context.Background()
28+
func GetUsers(c echo.Context) error {
29+
cc := c.(*middleware.CustomContext)
30+
ctx := cc.Request().Context()
3031
var users []PublicUser
3132
res := SuccessResponse{
3233
Data: UsersData{Users: &users},
3334
}
34-
err := models.Users().Bind(ctx, h.db, &users)
35+
err := models.Users().Bind(ctx, cc.DB, &users)
3536
if err != nil {
3637
c.Error(err)
3738
return err
@@ -43,8 +44,9 @@ type UserData struct {
4344
User *PublicUser `json:"user"`
4445
}
4546

46-
func (h *Handlers) GetUser(c echo.Context) error {
47-
ctx := context.Background()
47+
func GetUser(c echo.Context) error {
48+
cc := c.(*middleware.CustomContext)
49+
ctx := cc.Request().Context()
4850
res := SuccessResponse{
4951
Data: UserData{},
5052
}
@@ -56,7 +58,7 @@ func (h *Handlers) GetUser(c echo.Context) error {
5658
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
5759
}
5860

59-
exists, err := models.UserExists(ctx, h.db, id)
61+
exists, err := models.UserExists(ctx, cc.DB, id)
6062
if !exists {
6163
return echo.NewHTTPError(http.StatusNotFound, http.StatusText(http.StatusNotFound))
6264
}
@@ -65,7 +67,7 @@ func (h *Handlers) GetUser(c echo.Context) error {
6567
}
6668

6769
var users []*PublicUser
68-
err = models.Users(qm.Where("id = ?", id)).Bind(ctx, h.db, &users)
70+
err = models.Users(qm.Where("id = ?", id)).Bind(ctx, cc.DB, &users)
6971
if err != nil {
7072
c.Error(err)
7173
return err
@@ -80,8 +82,9 @@ type CreateUserRequest struct {
8082
Password string `json:"password"`
8183
}
8284

83-
func (h *Handlers) CreateUser(c echo.Context) error {
84-
ctx := context.Background()
85+
func CreateUser(c echo.Context) error {
86+
cc := c.(*middleware.CustomContext)
87+
ctx := cc.Request().Context()
8588
res := SuccessResponse{
8689
Data: UserData{},
8790
}
@@ -93,7 +96,7 @@ func (h *Handlers) CreateUser(c echo.Context) error {
9396
Email: req.Email,
9497
HashedPassword: req.Password,
9598
}
96-
err := u.Insert(ctx, h.db, boil.Infer())
99+
err := u.Insert(ctx, cc.DB, boil.Infer())
97100
if err != nil {
98101
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
99102
}
@@ -110,32 +113,33 @@ func (h *Handlers) CreateUser(c echo.Context) error {
110113
return c.JSON(http.StatusOK, res)
111114
}
112115

113-
func (h *Handlers) PatchUser(c echo.Context) error {
116+
func PatchUser(c echo.Context) error {
114117
return errors.New("not implemented")
115118
}
116119

117-
func (h *Handlers) DeleteUser(c echo.Context) error {
118-
ctx := context.Background()
120+
func DeleteUser(c echo.Context) error {
121+
cc := c.(*middleware.CustomContext)
122+
ctx := cc.Request().Context()
119123
var id int
120124
err := echo.PathParamsBinder(c).
121125
Int("id", &id).
122126
BindError()
123127
if err != nil {
124128
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
125129
}
126-
exists, err := models.UserExists(ctx, h.db, id)
130+
exists, err := models.UserExists(ctx, cc.DB, id)
127131
if !exists {
128132
return echo.NewHTTPError(http.StatusNotFound, http.StatusText(http.StatusNotFound))
129133
}
130134
if err != nil {
131135
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
132136
}
133-
u, err := models.FindUser(ctx, h.db, id)
137+
u, err := models.FindUser(ctx, cc.DB, id)
134138
if err != nil {
135139
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
136140
}
137141

138-
_, err = u.Delete(ctx, h.db)
142+
_, err = u.Delete(ctx, cc.DB)
139143
if err != nil {
140144
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
141145
}

internal/middleware/context.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package middleware
2+
3+
import (
4+
"database/sql"
5+
"sandbox-go-api-sqlboiler-rest-auth/internal/config"
6+
"sandbox-go-api-sqlboiler-rest-auth/models"
7+
8+
"github.com/gorilla/securecookie"
9+
"github.com/labstack/echo/v4"
10+
"go.uber.org/zap"
11+
)
12+
13+
type CustomContext struct {
14+
echo.Context
15+
Config *config.Config
16+
ZapLogger *zap.SugaredLogger
17+
DB *sql.DB
18+
SecureCookie *securecookie.SecureCookie
19+
CurrentUser *models.User
20+
}
21+
22+
func NewCustomContext(c echo.Context, cfg *config.Config, l *zap.SugaredLogger, db *sql.DB, sc *securecookie.SecureCookie) *CustomContext {
23+
return &CustomContext{
24+
Context: c,
25+
Config: cfg,
26+
ZapLogger: l,
27+
DB: db,
28+
SecureCookie: sc,
29+
CurrentUser: nil,
30+
}
31+
}

internal/server/middlewares.go renamed to internal/middleware/middleware.go

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
package server
1+
package middleware
22

33
import (
44
"database/sql"
55
"fmt"
6+
"sandbox-go-api-sqlboiler-rest-auth/internal/config"
67
"sandbox-go-api-sqlboiler-rest-auth/models"
78
"time"
89

@@ -14,9 +15,19 @@ import (
1415
"github.com/labstack/echo/v4"
1516
)
1617

18+
func SetCustomContext(cfg *config.Config, l *zap.SugaredLogger, db *sql.DB, sc *securecookie.SecureCookie) echo.MiddlewareFunc {
19+
return func(next echo.HandlerFunc) echo.HandlerFunc {
20+
return func(c echo.Context) error {
21+
cc := NewCustomContext(c, cfg, l, db, sc)
22+
return next(cc)
23+
}
24+
}
25+
}
26+
1727
func SessionRestorer(db *sql.DB, logger *zap.SugaredLogger, sc *securecookie.SecureCookie) echo.MiddlewareFunc {
1828
return func(next echo.HandlerFunc) echo.HandlerFunc {
1929
return func(c echo.Context) error {
30+
cc := c.(*CustomContext)
2031
cv, err := c.Cookie("session")
2132
if err != nil {
2233
return next(c)
@@ -39,13 +50,13 @@ func SessionRestorer(db *sql.DB, logger *zap.SugaredLogger, sc *securecookie.Sec
3950
return echo.NewHTTPError(500, "cannod find user from session relation", dv, err)
4051
}
4152
logger.Debug("got user in middleware", user)
42-
c.Set("user", user)
53+
cc.CurrentUser = user
4354
return next(c)
4455
}
4556
}
4657
}
4758

48-
func ZapLogger(log *zap.Logger) echo.MiddlewareFunc {
59+
func RequestZapLogger(log *zap.Logger) echo.MiddlewareFunc {
4960
return func(next echo.HandlerFunc) echo.HandlerFunc {
5061
return func(c echo.Context) error {
5162
start := time.Now()

0 commit comments

Comments
 (0)