-
Notifications
You must be signed in to change notification settings - Fork 0
/
user_passwd.go
132 lines (112 loc) · 4.11 KB
/
user_passwd.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
/*
Copyright © 2022 Miguel Ángel Álvarez Cabrerizo <mcabrerizo@arrakis.ovh>
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 handlers
import (
"errors"
"net/http"
"strconv"
"time"
"github.com/doncicuto/glim/models"
"github.com/golang-jwt/jwt"
"github.com/labstack/echo/v4"
"gorm.io/gorm"
)
//Passwd - TODO comment
// @Summary Change user account password
// @Description Change user account password
// @Tags users
// @Accept json
// @Produce json
// @Param id path int true "User Account ID"
// @Param password body models.JSONPasswdBody true "Password body"
// @Success 200 {object} models.UserInfo
// @Failure 400 {object} types.ErrorResponse
// @Failure 401 {object} types.ErrorResponse
// @Failure 403 {object} types.ErrorResponse
// @Failure 406 {object} types.ErrorResponse
// @Router /users/passwd [post]
// @Security Bearer
func (h *Handler) Passwd(c echo.Context) error {
var dbUser models.User
var newUser = make(map[string]interface{})
// Get idparam
uid := c.Param("uid")
// User id cannot be empty
if uid == "" {
return &echo.HTTPError{Code: http.StatusNotAcceptable, Message: "required user uid"}
}
// Bind body
body := new(models.JSONPasswdBody)
if err := c.Bind(body); err != nil {
return err
}
// Get uid and manager status from JWT token
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
tokenUID, ok := claims["uid"].(float64)
if !ok {
return &echo.HTTPError{Code: http.StatusNotAcceptable, Message: "wrong token or missing info in token claims"}
}
id, err := strconv.Atoi(uid)
if err != nil {
return &echo.HTTPError{Code: http.StatusBadRequest, Message: "uid param should be a valid integer"}
}
manager, ok := claims["manager"].(bool)
if !ok {
return &echo.HTTPError{Code: http.StatusNotAcceptable, Message: "wrong token or missing info in token claims"}
}
// If token uid is not the same as requested uid
// only managers can change the password without knowing the old password
if int(tokenUID) != id && !manager {
return &echo.HTTPError{Code: http.StatusForbidden, Message: "only managers can change other users passwords"}
}
if int(tokenUID) == id && body.OldPassword == "" {
return &echo.HTTPError{Code: http.StatusForbidden, Message: "the old password must be provided"}
}
// Check if user exists
err = h.DB.Where("id = ?", uid).First(&dbUser).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return &echo.HTTPError{Code: http.StatusUnauthorized, Message: "wrong username or password"}
}
// Check if passwords match
if int(tokenUID) == id {
if err := models.VerifyPassword(*dbUser.Password, body.OldPassword); err != nil {
return &echo.HTTPError{Code: http.StatusUnauthorized, Message: "wrong old password"}
}
}
// New password
hashedPassword, err := models.Hash(body.Password)
if err != nil {
return err
}
newUser["password"] = string(hashedPassword)
// Update date
newUser["updated_at"] = time.Now()
// Update user
err = h.DB.Model(&models.User{}).Where("id = ?", uid).Updates(newUser).Error
if err != nil {
// Does user exist?
if errors.Is(err, gorm.ErrRecordNotFound) {
return &echo.HTTPError{Code: http.StatusNotFound, Message: "user not found"}
}
return &echo.HTTPError{Code: http.StatusInternalServerError, Message: err.Error()}
}
// Get updated user
err = h.DB.Preload("MemberOf").Model(&models.User{}).Where("id = ?", uid).First(&dbUser).Error
if err != nil {
return &echo.HTTPError{Code: http.StatusInternalServerError, Message: err.Error()}
}
// Return user
showMemberOf := true
return c.JSON(http.StatusOK, models.GetUserInfo(dbUser, showMemberOf))
}