/
profile.go
259 lines (228 loc) · 7.81 KB
/
profile.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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/*
*
* Copyright 2022 puzzleweb authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package puzzleweb
import (
"io"
"mime/multipart"
"net/http"
"strconv"
"strings"
"github.com/dvaumoron/puzzleweb/common"
"github.com/dvaumoron/puzzleweb/common/config"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
type profileWidget struct {
defaultHandler gin.HandlerFunc
viewHandler gin.HandlerFunc
linkHandler gin.HandlerFunc
editHandler gin.HandlerFunc
saveHandler gin.HandlerFunc
changeLoginHandler gin.HandlerFunc
changePasswordHandler gin.HandlerFunc
pictureHandler gin.HandlerFunc
}
func defaultRedirecter(c *gin.Context) string {
userId := GetSessionUserId(c)
if userId == 0 {
return common.DefaultErrorRedirect(GetLogger(c), unknownUserKey)
}
return profileUrlBuilder(userId).String()
}
func (w profileWidget) LoadInto(router gin.IRouter) {
router.GET("/", w.defaultHandler)
router.GET("/view/:UserId", w.viewHandler)
router.GET("/link/*Login", w.linkHandler)
router.GET("/edit", w.editHandler)
router.POST("/save", w.saveHandler)
router.POST("/changeLogin", w.changeLoginHandler)
router.POST("/changePassword", w.changePasswordHandler)
router.GET("/picture/:UserId", w.pictureHandler)
}
func newProfilePage(profileConfig config.ProfileConfig) Page {
profileService := profileConfig.Service
adminService := profileConfig.AdminService
loginService := profileConfig.LoginService
p := MakeHiddenPage("profile")
p.Widget = profileWidget{
defaultHandler: common.CreateRedirect(defaultRedirecter),
viewHandler: CreateTemplate(func(data gin.H, c *gin.Context) (string, string) {
logger := GetLogger(c)
ctx := c.Request.Context()
viewedUserId := GetRequestedUserId(c)
if viewedUserId == 0 {
return "", common.DefaultErrorRedirect(logger, common.ErrorTechnicalKey)
}
currentUserId, _ := data[common.UserIdName].(uint64)
updateRight := viewedUserId == currentUserId
if !updateRight {
if err := profileService.ViewRight(ctx, currentUserId); err != nil {
return "", common.DefaultErrorRedirect(logger, err.Error())
}
}
profiles, err := profileService.GetProfiles(ctx, []uint64{viewedUserId})
if err != nil {
return "", common.DefaultErrorRedirect(logger, err.Error())
}
userRoles, err := adminService.GetUserRoles(ctx, currentUserId, viewedUserId)
// ignore ErrNotAuthorized
if err == common.ErrTechnical {
return "", common.DefaultErrorRedirect(logger, common.ErrorTechnicalKey)
}
if err == nil {
data["UserRight"] = displayGroups(userRoles)
}
userProfile := profiles[viewedUserId]
data[common.AllowedToUpdateName] = updateRight
data[common.ViewedUserName] = userProfile
return "profile/view", ""
}),
linkHandler: CreateTemplate(func(data gin.H, c *gin.Context) (string, string) {
if viewedUserLogin := c.Param(loginName); viewedUserLogin != "" {
// use 0, 1 because we just need the first result
nb, list, err := loginService.ListUsers(c.Request.Context(), 0, 1, viewedUserLogin)
if err == nil && nb != 0 {
data[common.ViewedUserName] = list[0]
}
}
return "profile/link", ""
}),
editHandler: CreateTemplate(func(data gin.H, c *gin.Context) (string, string) {
logger := GetLogger(c)
userId, _ := data[common.UserIdName].(uint64)
if userId == 0 {
return "", common.DefaultErrorRedirect(logger, unknownUserKey)
}
profiles, err := profileService.GetProfiles(c.Request.Context(), []uint64{userId})
if err != nil {
return "", common.DefaultErrorRedirect(logger, err.Error())
}
userProfile := profiles[userId]
data[common.ViewedUserName] = userProfile
return "profile/edit", ""
}),
saveHandler: common.CreateRedirect(func(c *gin.Context) string {
logger := GetLogger(c)
userId := GetSessionUserId(c)
if userId == 0 {
return common.DefaultErrorRedirect(logger, unknownUserKey)
}
desc := c.PostForm("userDesc")
info := c.PostFormMap("userInfo")
picture, err := c.FormFile("picture")
if err != nil {
logger.Error("Failed to retrieve picture file", zap.Error(err))
return common.DefaultErrorRedirect(logger, common.ErrorTechnicalKey)
}
ctx := c.Request.Context()
if picture != nil {
var pictureFile multipart.File
pictureFile, err = picture.Open()
if err != nil {
logger.Error("Failed to open retrieve picture file ", zap.Error(err))
return common.DefaultErrorRedirect(logger, common.ErrorTechnicalKey)
}
defer pictureFile.Close()
var pictureData []byte
pictureData, err = io.ReadAll(pictureFile)
if err != nil {
logger.Error("Failed to read picture file ", zap.Error(err))
return common.DefaultErrorRedirect(logger, common.ErrorTechnicalKey)
}
err = profileService.UpdatePicture(ctx, userId, pictureData)
}
if err == nil {
err = profileService.UpdateProfile(ctx, userId, desc, info)
}
targetBuilder := profileUrlBuilder(userId)
if err != nil {
common.WriteError(targetBuilder, logger, err.Error())
}
return targetBuilder.String()
}),
changeLoginHandler: common.CreateRedirect(func(c *gin.Context) string {
logger := GetLogger(c)
session := GetSession(c)
userId := GetSessionUserId(c)
if userId == 0 {
return common.DefaultErrorRedirect(logger, unknownUserKey)
}
oldLogin := session.Load(loginName)
newLogin := c.PostForm(loginName)
password := c.PostForm(passwordName)
err := common.ErrEmptyLogin
if newLogin != "" {
err = loginService.ChangeLogin(c.Request.Context(), userId, oldLogin, newLogin, password)
}
targetBuilder := profileUrlBuilder(userId)
if err == nil {
session.Store(loginName, newLogin)
} else {
common.WriteError(targetBuilder, logger, err.Error())
}
return targetBuilder.String()
}),
changePasswordHandler: common.CreateRedirect(func(c *gin.Context) string {
logger := GetLogger(c)
session := GetSession(c)
userId := GetSessionUserId(c)
if userId == 0 {
return common.DefaultErrorRedirect(logger, unknownUserKey)
}
login := session.Load(loginName)
oldPassword := c.PostForm("oldPassword")
newPassword := c.PostForm("newPassword")
confirmPassword := c.PostForm(confirmPasswordName)
err := common.ErrEmptyPassword
if newPassword != "" {
err = common.ErrWrongConfirm
if newPassword == confirmPassword {
err = loginService.ChangePassword(c.Request.Context(), userId, login, oldPassword, newPassword)
}
}
targetBuilder := profileUrlBuilder(userId)
if err != nil {
common.WriteError(targetBuilder, logger, err.Error())
}
return targetBuilder.String()
}),
pictureHandler: func(c *gin.Context) {
userId := GetRequestedUserId(c)
if userId == 0 {
c.AbortWithStatus(http.StatusNotFound)
return
}
data := profileService.GetPicture(c.Request.Context(), userId)
c.Data(http.StatusOK, http.DetectContentType(data), data)
},
}
return p
}
func GetRequestedUserId(c *gin.Context) uint64 {
userId, err := strconv.ParseUint(c.Param(userIdName), 10, 64)
if err != nil {
GetLogger(c).Warn("Failed to parse userId from request", zap.Error(err))
}
return userId
}
func profileUrlBuilder(userId uint64) *strings.Builder {
targetBuilder := new(strings.Builder)
targetBuilder.WriteString("/profile/view/")
targetBuilder.WriteString(strconv.FormatUint(userId, 10))
return targetBuilder
}