all repos

onasty @ 5495cb456caa00f4564d1c1eed06a766811debaf

a one-time notes service

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

Smirnov Oleksandr Smirnov Oleksandr
ss2316544@gmail.com
feat: add oauth2 login for google and github (#109)..., 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.ErrUserEmailIsAlreadyInUse) ||
22
		errors.Is(err, models.ErrUsernameIsAlreadyInUse) ||
23
		errors.Is(err, models.ErrUserIsAlreadyVerified) ||
24
		errors.Is(err, models.ErrUserIsNotActivated) ||
25
		errors.Is(err, models.ErrUserInvalidEmail) ||
26
		errors.Is(err, models.ErrUserInvalidPassword) ||
27
		errors.Is(err, models.ErrUserInvalidUsername) ||
28
		// notes
29
		errors.Is(err, models.ErrNoteContentIsEmpty) ||
30
		errors.Is(err, models.ErrNoteSlugIsAlreadyInUse) {
31
		newError(c, http.StatusBadRequest, err.Error())
32
		return
33
	}
34
35
	if errors.Is(err, models.ErrNoteExpired) {
36
		newError(c, http.StatusGone, err.Error())
37
		return
38
	}
39
40
	if errors.Is(err, models.ErrNoteNotFound) ||
41
		errors.Is(err, models.ErrVerificationTokenNotFound) {
42
		newErrorStatus(c, http.StatusNotFound, err.Error())
43
		return
44
	}
45
46
	if errors.Is(err, models.ErrUserNotFound) {
47
		newErrorStatus(c, http.StatusBadRequest, err.Error())
48
		return
49
	}
50
51
	if errors.Is(err, ErrUnauthorized) ||
52
		errors.Is(err, models.ErrUserWrongCredentials) {
53
		newErrorStatus(c, http.StatusUnauthorized, err.Error())
54
		return
55
	}
56
57
	newInternalError(c, err)
58
}
59
60
func newError(c *gin.Context, status int, msg string) {
61
	slog.ErrorContext(c.Request.Context(), msg, "status", status)
62
	c.AbortWithStatusJSON(status, response{msg})
63
}
64
65
func newErrorStatus(c *gin.Context, status int, msg string) {
66
	slog.ErrorContext(c.Request.Context(), msg, "status", status)
67
	c.AbortWithStatus(status)
68
}
69
70
func newInternalError(c *gin.Context, err error, msg ...string) {
71
	slog.ErrorContext(c.Request.Context(), err.Error(), "status", "internal error")
72
73
	if len(msg) != 0 {
74
		c.AbortWithStatusJSON(http.StatusInternalServerError, response{
75
			Message: msg[0],
76
		})
77
		return
78
	}
79
80
	c.AbortWithStatusJSON(http.StatusInternalServerError, response{
81
		Message: "internal error",
82
	})
83
}