all repos

onasty @ 7236f0cad88cebacb9801d31c8f707fec0cb6978

a one-time notes service

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

Smirnov Oleksandr Smirnov Oleksandr
ss2316544@gmail.com
feat: reset password (#110)..., 1 year ago
1
package apiv1
2
3
import (
4
	"errors"
5
	"log/slog"
6
	"net/http"
7
8
	"github.com/gin-gonic/gin"
9
	"github.com/olexsmir/onasty/internal/models"
10
	"github.com/olexsmir/onasty/internal/service/usersrv"
11
)
12
13
var ErrUnauthorized = errors.New("unauthorized")
14
15
type response struct {
16
	Message string `json:"message"`
17
}
18
19
func errorResponse(c *gin.Context, err error) {
20
	if errors.Is(err, usersrv.ErrProviderNotSupported) ||
21
		errors.Is(err, models.ErrResetPasswordTokenAlreadyUsed) ||
22
		errors.Is(err, models.ErrResetPasswordTokenExpired) ||
23
		errors.Is(err, models.ErrUserEmailIsAlreadyInUse) ||
24
		errors.Is(err, models.ErrUsernameIsAlreadyInUse) ||
25
		errors.Is(err, models.ErrUserIsAlreadyVerified) ||
26
		errors.Is(err, models.ErrUserIsNotActivated) ||
27
		errors.Is(err, models.ErrUserInvalidEmail) ||
28
		errors.Is(err, models.ErrUserInvalidPassword) ||
29
		errors.Is(err, models.ErrUserInvalidUsername) ||
30
		// notes
31
		errors.Is(err, models.ErrNoteContentIsEmpty) ||
32
		errors.Is(err, models.ErrNoteSlugIsAlreadyInUse) {
33
		newError(c, http.StatusBadRequest, err.Error())
34
		return
35
	}
36
37
	if errors.Is(err, models.ErrNoteExpired) {
38
		newError(c, http.StatusGone, err.Error())
39
		return
40
	}
41
42
	if errors.Is(err, models.ErrNoteNotFound) ||
43
		errors.Is(err, models.ErrVerificationTokenNotFound) {
44
		newErrorStatus(c, http.StatusNotFound, err.Error())
45
		return
46
	}
47
48
	if errors.Is(err, models.ErrUserNotFound) {
49
		newErrorStatus(c, http.StatusBadRequest, err.Error())
50
		return
51
	}
52
53
	if errors.Is(err, ErrUnauthorized) ||
54
		errors.Is(err, models.ErrUserWrongCredentials) {
55
		newErrorStatus(c, http.StatusUnauthorized, err.Error())
56
		return
57
	}
58
59
	newInternalError(c, err)
60
}
61
62
func newError(c *gin.Context, status int, msg string) {
63
	slog.ErrorContext(c.Request.Context(), msg, "status", status)
64
	c.AbortWithStatusJSON(status, response{msg})
65
}
66
67
func newErrorStatus(c *gin.Context, status int, msg string) {
68
	slog.ErrorContext(c.Request.Context(), msg, "status", status)
69
	c.AbortWithStatus(status)
70
}
71
72
func newInternalError(c *gin.Context, err error, msg ...string) {
73
	slog.ErrorContext(c.Request.Context(), err.Error(), "status", "internal error")
74
75
	if len(msg) != 0 {
76
		c.AbortWithStatusJSON(http.StatusInternalServerError, response{
77
			Message: msg[0],
78
		})
79
		return
80
	}
81
82
	c.AbortWithStatusJSON(http.StatusInternalServerError, response{
83
		Message: "internal error",
84
	})
85
}