Skip to content

Commit 48634bc

Browse files
committed
Add password to the list of fields to update
1 parent 9853e97 commit 48634bc

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

api/models/User.go

+21-3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package models
33
import (
44
"errors"
55
"html"
6+
"log"
67
"strings"
78
"time"
89

@@ -38,6 +39,15 @@ func (u *User) BeforeSave() error {
3839
return nil
3940
}
4041

42+
// func (u *User) BeforeUpdate() (err error) {
43+
// hashedPassword, err := Hash(u.Password)
44+
// if err != nil {
45+
// return err
46+
// }
47+
// u.Password = string(hashedPassword)
48+
// return nil
49+
// }
50+
4151
func (u *User) Prepare() {
4252
u.ID = 0
4353
u.Nickname = html.EscapeString(strings.TrimSpace(u.Nickname))
@@ -52,9 +62,9 @@ func (u *User) Validate(action string) error {
5262
if u.Nickname == "" {
5363
return errors.New("Required Nickname")
5464
}
55-
// if u.Password == "" {
56-
// return errors.New("Required Password")
57-
// }
65+
if u.Password == "" {
66+
return errors.New("Required Password")
67+
}
5868
if u.Email == "" {
5969
return errors.New("Required Email")
6070
}
@@ -154,11 +164,19 @@ func (u *User) FindUserByID(db *gorm.DB, uid uint32) (*User, error) {
154164
}
155165

156166
func (u *User) UpdateAUser(db *gorm.DB, uid uint32) (*User, error) {
167+
168+
// TO hash the password
169+
err := u.BeforeSave()
170+
if err != nil {
171+
log.Fatal(err)
172+
}
173+
157174
done := make(chan bool)
158175
go func(ch chan<- bool) {
159176
defer close(ch)
160177
db = db.Debug().Model(&User{}).Where("id = ?", uid).Take(&User{}).UpdateColumns(
161178
map[string]interface{}{
179+
"password": u.Password,
162180
"nickname": u.Nickname,
163181
"email": u.Email,
164182
"update_at": time.Now(),

tests/controllertests/user_controller_test.go

+9-1
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,14 @@ func TestUpdateUser(t *testing.T) {
222222
tokenGiven: tokenString,
223223
errorMessage: "",
224224
},
225+
{
226+
// When password field is empty
227+
id: strconv.Itoa(int(AuthID)),
228+
updateJSON: `{"nickname":"Woman", "email": "woman@gmail.com", "password": ""}`,
229+
statusCode: 422,
230+
tokenGiven: tokenString,
231+
errorMessage: "Required Password",
232+
},
225233
{
226234
// When no token was passed
227235
id: strconv.Itoa(int(AuthID)),
@@ -308,7 +316,7 @@ func TestUpdateUser(t *testing.T) {
308316
responseMap := make(map[string]interface{})
309317
err = json.Unmarshal([]byte(rr.Body.String()), &responseMap)
310318
if err != nil {
311-
fmt.Printf("Cannot convert to json: %v", err)
319+
t.Errorf("Cannot convert to json: %v", err)
312320
}
313321
assert.Equal(t, rr.Code, v.statusCode)
314322
if v.statusCode == 200 {

0 commit comments

Comments
 (0)