all repos

onasty @ 40bb8b9

a one-time notes service

onasty/internal/transport/http/apiv1/response.go(view raw)

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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package apiv1

import (
	"errors"
	"log/slog"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/olexsmir/onasty/internal/jwtutil"
	"github.com/olexsmir/onasty/internal/models"
	"github.com/olexsmir/onasty/internal/service/notesrv"
	"github.com/olexsmir/onasty/internal/service/usersrv"
)

var ErrUnauthorized = errors.New("unauthorized")

type response struct {
	Message string `json:"message"`
}

func errorResponse(c *gin.Context, err error) {
	if errors.Is(err, usersrv.ErrProviderNotSupported) ||
		errors.Is(err, models.ErrResetPasswordTokenAlreadyUsed) ||
		errors.Is(err, models.ErrResetPasswordTokenExpired) ||
		errors.Is(err, models.ErrUserEmailIsAlreadyInUse) ||
		errors.Is(err, models.ErrUserIsAlreadyVerified) ||
		errors.Is(err, models.ErrUserIsNotActivated) ||
		errors.Is(err, models.ErrUserInvalidEmail) ||
		errors.Is(err, models.ErrUserInvalidPassword) ||
		errors.Is(err, models.ErrUserNotFound) ||
		// notes
		errors.Is(err, notesrv.ErrNotePasswordNotProvided) ||
		errors.Is(err, models.ErrNoteContentIsEmpty) ||
		errors.Is(err, models.ErrNoteSlugIsAlreadyInUse) {
		newError(c, http.StatusBadRequest, err.Error())
		return
	}

	if errors.Is(err, models.ErrNoteExpired) {
		newError(c, http.StatusGone, err.Error())
		return
	}

	if errors.Is(err, models.ErrNoteNotFound) ||
		errors.Is(err, models.ErrVerificationTokenNotFound) {
		newErrorStatus(c, http.StatusNotFound, err.Error())
		return
	}

	if errors.Is(err, ErrUnauthorized) ||
		errors.Is(err, jwtutil.ErrTokenExpired) ||
		errors.Is(err, models.ErrUserWrongCredentials) {
		newErrorStatus(c, http.StatusUnauthorized, err.Error())
		return
	}

	newInternalError(c, err)
}

func newError(c *gin.Context, status int, msg string) {
	slog.ErrorContext(c.Request.Context(), msg, "status", status)
	c.AbortWithStatusJSON(status, response{msg})
}

func newErrorStatus(c *gin.Context, status int, msg string) {
	slog.ErrorContext(c.Request.Context(), msg, "status", status)
	c.AbortWithStatus(status)
}

func newInternalError(c *gin.Context, err error, msg ...string) {
	slog.ErrorContext(c.Request.Context(), err.Error(), "status", "internal error")

	if len(msg) != 0 {
		c.AbortWithStatusJSON(http.StatusInternalServerError, response{
			Message: msg[0],
		})
		return
	}

	c.AbortWithStatusJSON(http.StatusInternalServerError, response{
		Message: "internal error",
	})
}