-
Notifications
You must be signed in to change notification settings - Fork 0
/
note.go
66 lines (58 loc) · 1.92 KB
/
note.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package handlers
import (
"errors"
"net/http"
"github.com/addetz/secure-code-go/demo4/data"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
)
// GetUserNotes returns all the notes of a given user.
func (authService *UserAuthService) GetUserNotes(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(*JWTCustomClaims)
name := claims.Username
if err := authService.userService.ValidateUser(name); err != nil {
return echo.NewHTTPError(http.StatusUnauthorized, err)
}
paramName := c.Param("id")
if name != paramName {
return echo.NewHTTPError(http.StatusUnauthorized, errors.New("not logged in as notes owner"))
}
secretNotes, err := authService.secretNotesService.GetAll(paramName)
if err != nil {
return echo.NewHTTPError(http.StatusNotFound, err)
}
return c.JSON(http.StatusOK, echo.Map{
"username": name,
"notes": secretNotes,
})
}
// AddUserNote adds a note belonging to the given user
func (authService *UserAuthService) AddUserNote(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(*JWTCustomClaims)
name := claims.Username
if err := authService.userService.ValidateUser(name); err != nil {
return echo.NewHTTPError(http.StatusUnauthorized, err)
}
paramName := c.Param("id")
if name != paramName {
return echo.NewHTTPError(http.StatusUnauthorized, errors.New("not logged in as notes owner"))
}
newNote := new(data.SecretNote)
if err := c.Bind(newNote); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err)
}
// add the note
if err := authService.secretNotesService.Add(paramName, *newNote); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err)
}
secretNotes, err := authService.secretNotesService.GetAll(paramName)
if err != nil {
return echo.NewHTTPError(http.StatusNotFound, err)
}
return c.JSON(http.StatusCreated, echo.Map{
"username": name,
"notes": secretNotes,
})
}