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
|
package pages
import (
"context"
"fmt"
"gosten/csrf"
"gosten/form"
"gosten/model"
"net/http"
"github.com/go-chi/chi/v5"
"golang.org/x/crypto/bcrypt"
)
type chpw struct {
Password string `form:"type=password;options=required"`
NewPw1 string `form:"label=Neues Password;type=password;options=required"`
NewPw2 string `form:"label=Wiederholung;type=password;options=required"`
Success bool `form:"-"`
form.FormErrors
csrf.CsrfField
}
func ChangePassword() Page {
r := chi.NewRouter()
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
c := chpw{}
c.SetCsrfField(r)
render(changePassword(c))(w, r)
})
r.Post("/", handleChPw)
return r
}
func handleChPw(w http.ResponseWriter, r *http.Request) {
c := chpw{}
form.Parse(r, &c)
ctx := r.Context()
userId := getUser(ctx).ID
dbPwd, err := Q.GetPwdById(ctx, userId)
if err != nil {
panic(fmt.Sprintf("Q.GetPwdById: %v", err))
}
if c.NewPw1 != c.NewPw2 {
c.AddError("NewPw2", "Neues Passwort stimmt nicht überein!")
}
if !validatePwd(dbPwd, c.Password) {
c.AddError("Password", "Passwort falsch!")
}
if !c.HasError() {
updatePwd(ctx, userId, c.NewPw1)
// update context
ctx, _ = setUserInContext(ctx, userId)
r = r.WithContext(ctx)
// reset form
c = chpw{Success: true}
}
c.SetCsrfField(r)
render(changePassword(c))(w, r)
}
func updatePwd(ctx context.Context, userId int32, pwd string) {
hash, err := bcrypt.GenerateFromPassword([]byte(pwd), -1)
if err != nil {
panic(fmt.Sprintf("Generating password hash: %v", err))
}
err = Q.UpdatePwd(ctx, model.UpdatePwdParams{
Pwd: string(hash),
ID: userId})
if err != nil {
panic(fmt.Sprintf("Updating password: %v", err))
}
}
|