-
Notifications
You must be signed in to change notification settings - Fork 0
/
user_handler.go
175 lines (163 loc) · 4.86 KB
/
user_handler.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
166
167
168
169
170
171
172
173
174
175
package userhandler
import (
"encoding/json"
"fmt"
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/jwtauth/v5"
"github.com/go-playground/validator/v10"
"github.com/ducanng/3mclass_backend/config"
"github.com/ducanng/3mclass_backend/handler"
"github.com/ducanng/3mclass_backend/helper"
"github.com/ducanng/3mclass_backend/internal/service/userservice"
"github.com/ducanng/3mclass_backend/pkg/httputil"
"github.com/ducanng/3mclass_backend/pkg/logutil"
)
type userHandler struct {
userservice.UserService
cfg *config.Config
validate *validator.Validate
jwtHelper helper.JWTHelper
}
func NewUserHandler(cfg *config.Config, service userservice.UserService, jwtHelper helper.JWTHelper) handler.Handler {
return &userHandler{
UserService: service,
cfg: cfg,
validate: validator.New(),
jwtHelper: jwtHelper,
}
}
func (h *userHandler) Register(r chi.Router) {
r.Post("/logout", h.logoutUser)
r.Post("/change_password", h.changePassword)
r.Post("/update_profile", h.updateProfile)
r.Get("/profile", h.userProfile)
}
// logoutUser godoc
//
// @Summary Logout user
// @Description Logout user
// @Tags Public/User
// @Accept json
// @Produce json
// @Success 200 {string} string "Logout ok!"
// @Router /v1/public/u/user/logout [post]
func (h *userHandler) logoutUser(w http.ResponseWriter, r *http.Request) {
_, claims, _ := jwtauth.FromContext(r.Context())
// handle logout
var domain = h.cfg.AccessTokenCookie.Domain
// TODO: check domain
deleteAccessToken(w, []string{h.cfg.AccessTokenCookie.CookieName}, domain, false)
httputil.WriteJSONMessage(w, http.StatusOK, fmt.Sprintf("logout OK! %v", claims["user_id"]))
}
func (h *userHandler) changePassword(w http.ResponseWriter, r *http.Request) {
}
// updateProfile godoc
//
// @Summary Update user profile
// @Description Update user profile
// @Tags Public/User
// @Accept json
// @Produce json
// @Param UserProfile body UpdateUserProfileRequest true "Request"
// @Success 200 {string} string "Update profile ok!"
// @Router /v1/public/u/user/update_profile [post]
func (h *userHandler) updateProfile(w http.ResponseWriter, r *http.Request) {
var (
_, claims, _ = jwtauth.FromContext(r.Context())
logger = logutil.GetLogger()
req UpdateUserProfileRequest
userId = uint64(claims["user_id"].(float64))
)
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
logger.Errorf("Failed to decode request body, err=%s", err.Error())
httputil.WriteJSONMessage(w, http.StatusBadRequest, err.Error())
return
}
err = h.validate.Struct(&req)
if err != nil {
logger.Errorf("Failed to validate request, err=%s", err.Error())
httputil.WriteJSONMessage(w, http.StatusBadRequest, err.Error())
return
}
err = h.UserService.UpdateUserProfile(r.Context(), userId, &userservice.UpdateUserProfileRequest{
Email: req.Email,
FirstName: req.FirstName,
LastName: req.LastName,
PhoneNumber: req.PhoneNumber,
})
if err != nil {
logger.Errorf("Failed to update user profile, err=%s", err.Error())
httputil.WriteJSONMessage(w, http.StatusInternalServerError, err.Error())
return
}
httputil.WriteJSONMessage(w, http.StatusOK, "Update profile ok!")
}
// userProfile godoc
//
// @Summary Get user profile
// @Description Get user profile
// @Tags Public/User
// @Accept json
// @Produce json
// @Success 200 {object} UserProfile
// @Router /v1/public/u/user/profile [get]
func (h *userHandler) userProfile(w http.ResponseWriter, r *http.Request) {
var (
_, claims, _ = jwtauth.FromContext(r.Context())
logger = logutil.GetLogger()
userID = uint64(claims["user_id"].(float64))
)
logger.Info("claims", claims)
userProfile, err := h.UserService.GetUserInfo(r.Context(), userID)
if err != nil {
logger.Errorf("error while getting user profile, err: %s", err.Error())
httputil.WriteJSONMessage(w, http.StatusInternalServerError, err.Error())
return
}
httputil.WriteJSONResponse(w, UserProfile{
UserID: userProfile.UserID,
Email: userProfile.Email,
PhoneNumber: userProfile.PhoneNumber,
FirstName: userProfile.FirstName,
LastName: userProfile.LastName,
})
}
func deleteAccessToken(w http.ResponseWriter, cookieNames []string, domain string, skipAuthenticated bool) {
for _, cookieName := range cookieNames {
http.SetCookie(w, &http.Cookie{
Name: cookieName,
Value: "",
HttpOnly: true,
Path: "/",
MaxAge: -1,
Domain: domain,
})
}
if skipAuthenticated {
return
}
http.SetCookie(w, &http.Cookie{
Name: "jwt",
Value: "",
HttpOnly: true,
Path: "/",
MaxAge: -1,
})
http.SetCookie(w, &http.Cookie{
Name: "authenticated",
Value: "0",
HttpOnly: false,
Path: "/",
Domain: domain,
MaxAge: -1,
})
http.SetCookie(w, &http.Cookie{
Name: "authenticated",
Value: "0",
HttpOnly: false,
Path: "/",
MaxAge: -1,
})
}