-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.go
165 lines (149 loc) · 4.46 KB
/
controller.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package auth
import (
"fmt"
"net/http"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/wenzzyx/go-ushort/app/common/constants/emsgs"
db_utils "github.com/wenzzyx/go-ushort/app/common/db-utils"
"github.com/wenzzyx/go-ushort/app/common/utils"
"github.com/wenzzyx/go-ushort/app/config"
"github.com/wenzzyx/go-ushort/app/models"
)
// Registration godoc
//
// @Summary User registration
// @Schemes
// @Tags Auth
// @Accept json
// @Produce json
// @Success 200 {object} AuthResponse
// @Failure 422 {object} utils.CommonValidationError
// @Param request body RegisterValidator true "Request Body"
// @Router /auth/registration [post]
func Registration(c *gin.Context) {
validator := NewRegisterValidator()
if err := validator.Bind(c); err != nil {
c.JSON(http.StatusUnprocessableEntity, utils.NewValidatorError(err))
return
}
if err := db_utils.SaveOne(&validator.UserModel, "user"); err != nil {
c.JSON(err.H())
return
}
c.Set("userModel", validator.UserModel)
sz := AuthSerializer{c}
res := sz.Response()
if err := SetRefreshToContext(c, res.RefreshToken); err != nil {
c.JSON(utils.NewError(http.StatusInternalServerError, emsgs.Internal, "Can't set refresh token").H())
return
}
c.JSON(http.StatusCreated, res)
}
// Login godoc
//
// @Summary User login
// @Schemes
// @Tags Auth
// @Accept json
// @Produce json
// @Success 200 {object} AuthResponse
// @Failure 400 {object} utils.CommonError
// @Failure 422 {object} utils.CommonValidationError
// @Param request body LoginValidator true "Request Body"
// @Router /auth/login [post]
func Login(c *gin.Context) {
validator := NewLoginValidator()
if err := validator.Bind(c); err != nil {
c.JSON(http.StatusUnprocessableEntity, utils.NewValidatorError(err))
return
}
user, err := models.FindOneUser(&models.UserModel{Email: validator.Email})
if err != nil {
c.JSON(utils.NewError(http.StatusBadRequest, emsgs.WrongCredentials).H())
return
}
if user.ComparePassword(validator.Password) != nil {
c.JSON(utils.NewError(http.StatusBadRequest, emsgs.WrongCredentials).H())
return
}
c.Set("userModel", user)
sz := AuthSerializer{c}
res := sz.Response()
if err := SetRefreshToContext(c, res.RefreshToken); err != nil {
c.JSON(utils.NewError(http.StatusInternalServerError, emsgs.Internal, "Can't set refresh token").H())
return
}
c.JSON(http.StatusCreated, res)
}
// Refresh godoc
//
// @Summary Refresh token pair
// @Schemes
// @Tags Auth
// @Accept json
// @Produce json
// @Success 200 {object} AuthResponse
// @Failure 401 {object} utils.CommonError
// @Param cookie header string true "Cookie" default(refresh_token="...")
// @Router /auth/refresh [get]
func Refresh(c *gin.Context) {
refreshTokenCookie, err := c.Request.Cookie("refreshToken")
refreshToken := ""
validator := NewRefreshValidator()
_ = validator.Bind(c)
if err != nil {
refreshToken = validator.Token
} else {
refreshToken = refreshTokenCookie.Value
}
if refreshToken == "" {
c.JSON(utils.NewError(http.StatusUnauthorized, emsgs.Unauthorized).H())
return
}
token, err := jwt.Parse(refreshToken, func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
cfg := config.GetCfg()
return []byte(cfg.Server.JwtRefreshSecret), nil
})
if err != nil {
fmt.Println(err)
c.JSON(utils.NewError(http.StatusUnauthorized, emsgs.Unauthorized).H())
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || !token.Valid {
c.JSON(utils.NewError(http.StatusUnauthorized, emsgs.Unauthorized).H())
return
}
userId := uint(claims["id"].(float64))
user, cerr := models.FindOneUser(&models.UserModel{ID: userId})
if cerr != nil {
c.JSON(utils.NewError(http.StatusBadRequest, emsgs.WrongCredentials).H())
return
}
c.Set("userModel", user)
sz := AuthSerializer{c}
res := sz.Response()
if err := SetRefreshToContext(c, res.RefreshToken); err != nil {
c.JSON(utils.NewError(http.StatusInternalServerError, emsgs.Internal, "Can't set refresh token").H())
return
}
c.JSON(http.StatusCreated, res)
}
// Logout godoc
//
// @Summary Logout (clear refresh token from cookies)
// @Schemes
// @Tags Auth
// @Accept json
// @Produce json
// @Success 204 "Empty response"
// @Param cookie header string false "Required Cookie" default(refresh_token="...")
// @Router /auth/logout [delete]
func Logout(c *gin.Context) {
ClearRefreshInContext(c)
c.Status(http.StatusNoContent)
}