Skip to content

Commit 73e9790

Browse files
authored
Merge pull request #6 from pangolin-do-golang/fix/auth
Correção no envio da mensagem ao SQS e no middleware de autenticação
2 parents 0b3d8f0 + 1e842bc commit 73e9790

File tree

9 files changed

+103
-88
lines changed

9 files changed

+103
-88
lines changed

internal/adapters/db/thumb_repository.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ type PostgresThumbRepository struct {
2525

2626
func (r *PostgresThumbRepository) Create(process *entity.ThumbProcess) error {
2727
record := &ThumbPostgres{
28+
BaseModel: BaseModel{
29+
ID: process.ID,
30+
},
2831
VideoPath: process.Video.Path,
2932
ThumbnailPath: process.Thumbnail.Path,
3033
Status: process.Status,

internal/adapters/rest/handler/thumb_handler.go

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
package handler
22

33
import (
4-
"net/http"
5-
"time"
6-
74
"github.com/gin-gonic/gin"
85
"github.com/google/uuid"
6+
"github.com/pangolin-do-golang/thumb-processor-api/internal/adapters/rest/middleware"
97
"github.com/pangolin-do-golang/thumb-processor-api/internal/core/ports"
108
"github.com/pangolin-do-golang/thumb-processor-api/internal/core/thumb"
9+
"github.com/pangolin-do-golang/thumb-processor-api/internal/core/users"
10+
"net/http"
1111
)
1212

1313
type ThumbHandler struct {
@@ -22,9 +22,9 @@ func NewThumbHandler(service thumb.IThumbService) *ThumbHandler {
2222

2323
func (h *ThumbHandler) RegisterRoutes(router *gin.RouterGroup) {
2424
thumbGroup := router.Group("/thumbs")
25-
thumbGroup.POST("", h.CreateProcess)
25+
thumbGroup.POST("", middleware.AuthMiddleware(users.GetAllowedUsers), h.CreateProcess)
2626
thumbGroup.PUT("/:id", h.UpdateProcess)
27-
thumbGroup.GET("", h.ListProcesses)
27+
thumbGroup.GET("", middleware.AuthMiddleware(users.GetAllowedUsers), h.ListProcesses)
2828
}
2929

3030
// @Summary Create a new thumbnail process
@@ -53,8 +53,14 @@ func (h *ThumbHandler) CreateProcess(c *gin.Context) {
5353
return
5454
}
5555

56+
var userEmail string
57+
ctxUser, ok := c.Get("user")
58+
if ok {
59+
userEmail = ctxUser.(string)
60+
}
5661
err := h.thumbService.CreateProcessAsync(&ports.CreateProcessRequest{
57-
Url: request.URL,
62+
UserEmail: userEmail,
63+
Url: request.URL,
5864
})
5965
if err != nil {
6066
c.JSON(http.StatusInternalServerError, ErrorResponse{
@@ -153,12 +159,10 @@ type UpdateProcessRequest struct {
153159
}
154160

155161
type ThumbProcessResponse struct {
156-
ID string `json:"id"`
157-
Status string `json:"status"`
158-
Error string `json:"error,omitempty"`
159-
ThumbnailPath string `json:"thumbnail_path,omitempty"`
160-
CreatedAt time.Time `json:"created_at"`
161-
UpdatedAt time.Time `json:"updated_at"`
162+
ID string `json:"id"`
163+
Status string `json:"status"`
164+
Error string `json:"error,omitempty"`
165+
ThumbnailPath string `json:"thumbnail_path,omitempty"`
162166
}
163167

164168
type ErrorResponse struct {

internal/adapters/rest/handler/thumb_handler_test.go

Lines changed: 72 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -26,60 +26,61 @@ func setupTest() (*gin.Engine, *servicemocks.IThumbService) {
2626
return router, mockService
2727
}
2828

29-
func TestCreateProcess(t *testing.T) {
29+
func TestUpdateProcess(t *testing.T) {
3030
router, mockService := setupTest()
31+
mockedUUID, _ := uuid.NewV7()
3132

32-
t.Run("successful creation", func(t *testing.T) {
33-
mockService.On("CreateProcessAsync", mock.AnythingOfType("*ports.CreateProcessRequest")).Return(nil).Once()
34-
35-
body := CreateProcessRequest{URL: "https://example.com/video.mp4"}
36-
jsonBody, _ := json.Marshal(body)
37-
38-
w := httptest.NewRecorder()
39-
req, _ := http.NewRequest("POST", "/thumbs", bytes.NewBuffer(jsonBody))
40-
req.Header.Set("Content-Type", "application/json")
41-
router.ServeHTTP(w, req)
33+
t.Run("successful update", func(t *testing.T) {
34+
updatedProcess := &entity.ThumbProcess{
35+
ID: mockedUUID,
36+
Status: "completed",
37+
Thumbnail: entity.ThumbProcessThumb{
38+
Path: "path/to/thumbnail.jpg",
39+
},
40+
}
4241

43-
assert.Equal(t, http.StatusAccepted, w.Code)
44-
})
42+
mockService.On("UpdateProcess", mock.AnythingOfType("*ports.UpdateProcessRequest")).Return(updatedProcess, nil).Once()
4543

46-
t.Run("invalid request", func(t *testing.T) {
47-
body := CreateProcessRequest{URL: ""} // Empty URL
44+
body := UpdateProcessRequest{
45+
Status: "completed",
46+
ThumbnailPath: "path/to/thumbnail.jpg",
47+
}
4848
jsonBody, _ := json.Marshal(body)
4949

5050
w := httptest.NewRecorder()
51-
req, _ := http.NewRequest("POST", "/thumbs", bytes.NewBuffer(jsonBody))
51+
req, _ := http.NewRequest("PUT", "/thumbs/"+mockedUUID.String(), bytes.NewBuffer(jsonBody))
5252
req.Header.Set("Content-Type", "application/json")
5353
router.ServeHTTP(w, req)
5454

55-
assert.Equal(t, http.StatusBadRequest, w.Code)
55+
assert.Equal(t, http.StatusOK, w.Code)
5656
})
5757

58-
t.Run("service error", func(t *testing.T) {
59-
mockService.On("CreateProcessAsync", mock.AnythingOfType("*ports.CreateProcessRequest")).
60-
Return(errors.New("service error")).Once()
61-
62-
body := CreateProcessRequest{URL: "https://example.com/video.mp4"}
58+
t.Run("api bind ID param error", func(t *testing.T) {
59+
body := UpdateProcessRequest{
60+
Status: "completed",
61+
ThumbnailPath: "path/to/thumbnail.jpg",
62+
}
6363
jsonBody, _ := json.Marshal(body)
6464

6565
w := httptest.NewRecorder()
66-
req, _ := http.NewRequest("POST", "/thumbs", bytes.NewBuffer(jsonBody))
66+
67+
req, _ := http.NewRequest("PUT", "/thumbs/invalid-uuid", bytes.NewBuffer(jsonBody))
6768
req.Header.Set("Content-Type", "application/json")
6869
router.ServeHTTP(w, req)
6970

70-
assert.Equal(t, http.StatusInternalServerError, w.Code)
71+
assert.Equal(t, http.StatusBadRequest, w.Code)
7172

7273
var response ErrorResponse
7374
err := json.Unmarshal(w.Body.Bytes(), &response)
7475
assert.NoError(t, err)
75-
assert.Equal(t, "service error", response.Error)
76+
assert.Equal(t, "Process ID is required", response.Error)
7677
})
7778

7879
t.Run("api bind json error", func(t *testing.T) {
79-
invalidJSON := []byte(`{"url": invalid-json}`)
80+
invalidJSON := []byte(`{"status": invalid-json}`)
8081

8182
w := httptest.NewRecorder()
82-
req, _ := http.NewRequest("POST", "/thumbs", bytes.NewBuffer(invalidJSON))
83+
req, _ := http.NewRequest("PUT", "/thumbs/"+mockedUUID.String(), bytes.NewBuffer(invalidJSON))
8384
req.Header.Set("Content-Type", "application/json")
8485
router.ServeHTTP(w, req)
8586

@@ -90,22 +91,10 @@ func TestCreateProcess(t *testing.T) {
9091
assert.NoError(t, err)
9192
assert.Equal(t, "Invalid request format", response.Error)
9293
})
93-
}
94-
95-
func TestUpdateProcess(t *testing.T) {
96-
router, mockService := setupTest()
97-
mockedUUID, _ := uuid.NewV7()
9894

99-
t.Run("successful update", func(t *testing.T) {
100-
updatedProcess := &entity.ThumbProcess{
101-
ID: mockedUUID,
102-
Status: "completed",
103-
Thumbnail: entity.ThumbProcessThumb{
104-
Path: "path/to/thumbnail.jpg",
105-
},
106-
}
107-
108-
mockService.On("UpdateProcess", mock.AnythingOfType("*ports.UpdateProcessRequest")).Return(updatedProcess, nil).Once()
95+
t.Run("service error", func(t *testing.T) {
96+
mockService.On("UpdateProcess", mock.AnythingOfType("*ports.UpdateProcessRequest")).
97+
Return(nil, errors.New("service error")).Once()
10998

11099
body := UpdateProcessRequest{
111100
Status: "completed",
@@ -118,63 +107,83 @@ func TestUpdateProcess(t *testing.T) {
118107
req.Header.Set("Content-Type", "application/json")
119108
router.ServeHTTP(w, req)
120109

121-
assert.Equal(t, http.StatusOK, w.Code)
110+
assert.Equal(t, http.StatusInternalServerError, w.Code)
111+
112+
var response ErrorResponse
113+
err := json.Unmarshal(w.Body.Bytes(), &response)
114+
assert.NoError(t, err)
115+
assert.Equal(t, "service error", response.Error)
122116
})
117+
}
123118

124-
t.Run("api bind ID param error", func(t *testing.T) {
125-
body := UpdateProcessRequest{
126-
Status: "completed",
127-
ThumbnailPath: "path/to/thumbnail.jpg",
119+
func TestCreateProcess(t *testing.T) {
120+
router, mockService := setupTest()
121+
122+
t.Run("successful create", func(t *testing.T) {
123+
body := CreateProcessRequest{
124+
URL: "http://example.com/video.mp4",
128125
}
129126
jsonBody, _ := json.Marshal(body)
130127

128+
mockService.On("CreateProcessAsync", mock.AnythingOfType("*ports.CreateProcessRequest")).Return(nil).Once()
129+
131130
w := httptest.NewRecorder()
131+
req, _ := http.NewRequest("POST", "/thumbs", bytes.NewBuffer(jsonBody))
132+
req.Header.Set("Content-Type", "application/json")
133+
req.SetBasicAuth("test", "test")
134+
router.ServeHTTP(w, req)
132135

133-
req, _ := http.NewRequest("PUT", "/thumbs/invalid-uuid", bytes.NewBuffer(jsonBody))
136+
assert.Equal(t, http.StatusAccepted, w.Code)
137+
})
138+
139+
t.Run("invalid request format", func(t *testing.T) {
140+
invalidJSON := []byte(`{"url": 123}`)
141+
142+
w := httptest.NewRecorder()
143+
req, _ := http.NewRequest("POST", "/thumbs", bytes.NewBuffer(invalidJSON))
134144
req.Header.Set("Content-Type", "application/json")
145+
req.SetBasicAuth("test", "test")
135146
router.ServeHTTP(w, req)
136147

137148
assert.Equal(t, http.StatusBadRequest, w.Code)
138-
139149
var response ErrorResponse
140150
err := json.Unmarshal(w.Body.Bytes(), &response)
141151
assert.NoError(t, err)
142-
assert.Equal(t, "Process ID is required", response.Error)
152+
assert.Equal(t, "Invalid request format", response.Error)
143153
})
144154

145-
t.Run("api bind json error", func(t *testing.T) {
146-
invalidJSON := []byte(`{"status": invalid-json}`)
155+
t.Run("missing URL", func(t *testing.T) {
156+
body := CreateProcessRequest{}
157+
jsonBody, _ := json.Marshal(body)
147158

148159
w := httptest.NewRecorder()
149-
req, _ := http.NewRequest("PUT", "/thumbs/"+mockedUUID.String(), bytes.NewBuffer(invalidJSON))
160+
req, _ := http.NewRequest("POST", "/thumbs", bytes.NewBuffer(jsonBody))
150161
req.Header.Set("Content-Type", "application/json")
162+
req.SetBasicAuth("test", "test")
151163
router.ServeHTTP(w, req)
152164

153165
assert.Equal(t, http.StatusBadRequest, w.Code)
154-
155166
var response ErrorResponse
156167
err := json.Unmarshal(w.Body.Bytes(), &response)
157168
assert.NoError(t, err)
158169
assert.Equal(t, "Invalid request format", response.Error)
159170
})
160171

161172
t.Run("service error", func(t *testing.T) {
162-
mockService.On("UpdateProcess", mock.AnythingOfType("*ports.UpdateProcessRequest")).
163-
Return(nil, errors.New("service error")).Once()
164-
165-
body := UpdateProcessRequest{
166-
Status: "completed",
167-
ThumbnailPath: "path/to/thumbnail.jpg",
173+
body := CreateProcessRequest{
174+
URL: "http://example.com/video.mp4",
168175
}
169176
jsonBody, _ := json.Marshal(body)
170177

178+
mockService.On("CreateProcessAsync", mock.AnythingOfType("*ports.CreateProcessRequest")).Return(errors.New("service error")).Once()
179+
171180
w := httptest.NewRecorder()
172-
req, _ := http.NewRequest("PUT", "/thumbs/"+mockedUUID.String(), bytes.NewBuffer(jsonBody))
181+
req, _ := http.NewRequest("POST", "/thumbs", bytes.NewBuffer(jsonBody))
173182
req.Header.Set("Content-Type", "application/json")
183+
req.SetBasicAuth("test", "test")
174184
router.ServeHTTP(w, req)
175185

176186
assert.Equal(t, http.StatusInternalServerError, w.Code)
177-
178187
var response ErrorResponse
179188
err := json.Unmarshal(w.Body.Bytes(), &response)
180189
assert.NoError(t, err)
@@ -204,6 +213,7 @@ func TestListProcesses(t *testing.T) {
204213

205214
w := httptest.NewRecorder()
206215
req, _ := http.NewRequest("GET", "/thumbs", nil)
216+
req.SetBasicAuth("test", "test")
207217
router.ServeHTTP(w, req)
208218

209219
assert.Equal(t, http.StatusOK, w.Code)

internal/adapters/rest/middleware/authmiddleware.go

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package middleware
22

33
import (
44
"github.com/gin-gonic/gin"
5-
"github.com/pangolin-do-golang/thumb-processor-api/internal/core/users"
65
"net/http"
76
)
87

@@ -22,9 +21,7 @@ func AuthMiddleware(allowedUsersFunc func() gin.Accounts) gin.HandlerFunc {
2221
return
2322
}
2423

25-
loggedUser := users.GetUserByNickname(username)
26-
27-
c.Set("logged_user_id", loggedUser.ID)
24+
c.Set("user", username)
2825

2926
c.Next() // Continue to the handler
3027
}

internal/adapters/rest/server/server.go

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"github.com/pangolin-do-golang/thumb-processor-api/internal/adapters/rest/handler"
66
"github.com/pangolin-do-golang/thumb-processor-api/internal/adapters/rest/middleware"
77
"github.com/pangolin-do-golang/thumb-processor-api/internal/core/thumb"
8-
"github.com/pangolin-do-golang/thumb-processor-api/internal/core/users"
98
)
109

1110
type RestServer struct {
@@ -33,11 +32,9 @@ func (rs RestServer) Serve() {
3332
handler.RegisterUserRoutes(r)
3433

3534
// Rotes that need authentication
36-
authorizedGroup := r.Group("/", middleware.AuthMiddleware(users.GetAllowedUsers))
35+
handler.RegisterLoginHandlers(r.Group("/"))
3736

38-
handler.RegisterLoginHandlers(authorizedGroup)
39-
40-
handler.NewThumbHandler(rs.thumbService).RegisterRoutes(authorizedGroup)
37+
handler.NewThumbHandler(rs.thumbService).RegisterRoutes(r.Group("/"))
4138

4239
err := r.Run("0.0.0.0:8080")
4340
if err != nil {

internal/core/domain/entity/thumb_process.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ var AllowedProcessStatus = map[string]bool{
1616

1717
type ThumbProcess struct {
1818
ID uuid.UUID `json:"id"`
19+
UserEmail string `json:"user_email"`
1920
Video ThumbProcessVideo `json:"video"`
2021
Status string `json:"status"`
2122
Error string `json:"error,omitempty"`
@@ -30,8 +31,10 @@ type ThumbProcessThumb struct {
3031
Path string `json:"url"`
3132
}
3233

33-
func NewThumbProcess(url string) *ThumbProcess {
34+
func NewThumbProcess(url, email string) *ThumbProcess {
3435
return &ThumbProcess{
36+
ID: uuid.New(),
37+
UserEmail: email,
3538
Video: ThumbProcessVideo{
3639
Path: url,
3740
},

internal/core/ports/thumb_ports.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ package ports
33
import "github.com/google/uuid"
44

55
type CreateProcessRequest struct {
6-
Url string `json:"url"`
6+
UserEmail string `json:"user_email"`
7+
Url string `json:"url"`
78
}
89

910
type UpdateProcessRequest struct {

internal/core/thumb/thumb_service.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ func NewThumbService(repo contracts.IThumbRepositoryAdapter, q contracts.IThumbQ
2222
}
2323

2424
func (s *Service) CreateProcessAsync(request *ports.CreateProcessRequest) error {
25-
thumbProcess := entity.NewThumbProcess(request.Url)
25+
thumbProcess := entity.NewThumbProcess(request.Url, request.UserEmail)
2626

2727
if err := s.processRepository.Create(thumbProcess); err != nil {
2828
return err

internal/core/thumb/thumb_service_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,8 @@ func TestListProcess(t *testing.T) {
5252
service := NewThumbService(mockRepo, mockQueue)
5353

5454
expectedList := &[]entity.ThumbProcess{
55-
*entity.NewThumbProcess("https://example.com/video1.mp4"),
56-
*entity.NewThumbProcess("https://example.com/video2.mp4"),
55+
*entity.NewThumbProcess("https://example.com/video1.mp4", "[email protected]"),
56+
*entity.NewThumbProcess("https://example.com/video2.mp4", "[email protected]"),
5757
}
5858

5959
mockRepo.On("List").Return(expectedList)

0 commit comments

Comments
 (0)