~gitpocket/gitpocket

4
a04296ca62d86bf7f502e0afb3e22dbef8af4e94
mainfeed-discovery
gitpocket/account.go -rw-r--r--7.5 KiB ViewLogBlameView rawPermalink e8ffab4e14 feat(basin): mail, totp, issues, stars, blame and feeds 1 months ago
  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
package main

import (
	"encoding/base64"
	"fmt"
	"html/template"
	"net/http"
	"net/url"
	"strings"

	qrcode "github.com/skip2/go-qrcode"
)

func (s *Server) setEmail(w http.ResponseWriter, r *http.Request) {
	u := s.require(w, r)
	if u == nil {
		return
	}
	email := strings.TrimSpace(strings.ToLower(r.FormValue("email")))
	if err := s.store.SetEmail(u.ID, email); err != nil {
		http.Redirect(w, r, "/settings?error="+template.URLQueryEscaper(err.Error()), http.StatusSeeOther)
		return
	}
	if email == "" {
		http.Redirect(w, r, "/settings", http.StatusSeeOther)
		return
	}
	if s.mailer == nil {
		http.Redirect(w, r, "/settings?error=Mail+is+not+configured+on+this+server", http.StatusSeeOther)
		return
	}
	token, err := s.store.CreateMailToken(u.ID, "verify", email)
	if err != nil {
		http.Redirect(w, r, "/settings?error="+template.URLQueryEscaper(err.Error()), http.StatusSeeOther)
		return
	}
	link := fmt.Sprintf("https://%s/verify/%s", s.host, token)
	if err := s.mailer.Send(email, "Verify your email for "+s.host, fmt.Sprintf("Hello ~%s,\n\nOpen this link to confirm your email address:\n\n%s\n\nThe link is valid for 24 hours. If you did not ask for this, ignore it.\n", u.Name, link)); err != nil {
		http.Redirect(w, r, "/settings?error="+template.URLQueryEscaper("Could not send mail: "+err.Error()), http.StatusSeeOther)
		return
	}
	http.Redirect(w, r, "/settings?sent=1", http.StatusSeeOther)
}

func (s *Server) verifyEmail(w http.ResponseWriter, r *http.Request) {
	user, email, ok := s.store.UseMailToken(r.PathValue("token"), "verify")
	if !ok {
		s.fail(w, r, 400, "That verification link is invalid or has expired")
		return
	}
	s.store.MarkVerified(user, email)
	s.render(w, r, "message", page{Title: "Email verified", Data: map[string]any{"Heading": "Email verified", "Text": "Thanks, " + email + " is now confirmed. Password resets and notifications will go there."}})
}

func (s *Server) setNotify(w http.ResponseWriter, r *http.Request) {
	u := s.require(w, r)
	if u == nil {
		return
	}
	s.store.SetNotify(u.ID, r.FormValue("notify") == "on")
	http.Redirect(w, r, "/settings", http.StatusSeeOther)
}

func (s *Server) resetForm(w http.ResponseWriter, r *http.Request) {
	s.render(w, r, "reset", page{Title: "Reset password", Data: map[string]any{"Mail": s.mailer != nil, "Sent": r.URL.Query().Get("sent")}})
}

func (s *Server) resetRequest(w http.ResponseWriter, r *http.Request) {
	ip := clientIP(r)
	if s.limiter.blocked(ip) {
		s.fail(w, r, 429, "Too many attempts, try again in a few minutes")
		return
	}
	s.limiter.fail(ip)
	who := strings.TrimSpace(r.FormValue("who"))
	u, err := s.store.UserByName(who)
	if err != nil {
		u, err = s.store.UserByEmail(who)
	}
	if err == nil && s.mailer != nil {
		if email := s.store.Account(u.ID).Email; email != "" && s.store.Account(u.ID).Verified {
			token, _ := s.store.CreateMailToken(u.ID, "reset", email)
			link := fmt.Sprintf("https://%s/reset/%s", s.host, token)
			s.mailer.Send(email, "Password reset for "+s.host, fmt.Sprintf("Hello ~%s,\n\nSomeone asked to reset the password for your account. Open this link to choose a new one:\n\n%s\n\nThe link is valid for 24 hours. If that was not you, ignore this message and nothing changes.\n", u.Name, link))
		}
	}
	http.Redirect(w, r, "/reset?sent=1", http.StatusSeeOther)
}

func (s *Server) resetTokenForm(w http.ResponseWriter, r *http.Request) {
	s.render(w, r, "resetpassword", page{Title: "Choose a new password", Data: map[string]any{"Token": r.PathValue("token")}})
}

func (s *Server) resetPassword(w http.ResponseWriter, r *http.Request) {
	user, _, ok := s.store.UseMailToken(r.PathValue("token"), "reset")
	if !ok {
		s.fail(w, r, 400, "That reset link is invalid or has expired")
		return
	}
	if err := s.store.SetPassword(user, r.FormValue("password")); err != nil {
		w.WriteHeader(400)
		s.render(w, r, "resetpassword", page{Title: "Choose a new password", Error: err.Error(), Data: map[string]any{"Token": r.PathValue("token")}})
		return
	}
	s.store.DeleteSessions(user)
	http.Redirect(w, r, "/login", http.StatusSeeOther)
}

func (s *Server) pendingUser(r *http.Request) (User, bool) {
	c, err := r.Cookie("pending")
	if err != nil {
		return User{}, false
	}
	var user int64
	var created int64
	err = s.store.db.QueryRow(`select user, created from mailtokens where token = ? and kind = 'totp'`, c.Value).Scan(&user, &created)
	if err != nil {
		return User{}, false
	}
	u, err := s.store.userByID(user)
	return u, err == nil
}

func (s *Server) totpForm(w http.ResponseWriter, r *http.Request) {
	if _, ok := s.pendingUser(r); !ok {
		http.Redirect(w, r, "/login", http.StatusSeeOther)
		return
	}
	s.render(w, r, "totp", page{Title: "Two factor"})
}

func (s *Server) totpLogin(w http.ResponseWriter, r *http.Request) {
	u, ok := s.pendingUser(r)
	if !ok {
		http.Redirect(w, r, "/login", http.StatusSeeOther)
		return
	}
	ip := clientIP(r)
	if s.limiter.blocked(ip) {
		s.fail(w, r, 429, "Too many attempts, try again in a few minutes")
		return
	}
	a := s.store.Account(u.ID)
	code := r.FormValue("code")
	if !totpValid(a.TOTP, code) {
		if left, used := useRecovery(a.Recovery, code); used {
			s.store.SetTOTP(u.ID, a.TOTP, left)
		} else {
			s.limiter.fail(ip)
			w.WriteHeader(401)
			s.render(w, r, "totp", page{Title: "Two factor", Error: "Wrong code"})
			return
		}
	}
	if c, err := r.Cookie("pending"); err == nil {
		s.store.db.Exec(`delete from mailtokens where token = ?`, c.Value)
	}
	http.SetCookie(w, &http.Cookie{Name: "pending", Value: "", Path: "/", MaxAge: -1})
	s.startSession(w, u)
	http.Redirect(w, r, "/", http.StatusSeeOther)
}

func (s *Server) setupTOTP(w http.ResponseWriter, r *http.Request) {
	u := s.require(w, r)
	if u == nil {
		return
	}
	if _, ok := s.store.CheckPassword(u.Name, r.FormValue("password")); !ok {
		http.Redirect(w, r, "/settings/security?error=Wrong+password", http.StatusSeeOther)
		return
	}
	secret := newSecret()
	token, _ := s.store.CreateMailToken(u.ID, "totpsetup", secret)
	uri := fmt.Sprintf("otpauth://totp/%s:%s?secret=%s&issuer=%s", url.PathEscape(s.host), url.PathEscape(u.Name), secret, url.QueryEscape(s.host))
	png, _ := qrcode.Encode(uri, qrcode.Medium, 200)
	s.render(w, r, "totpsetup", page{Title: "Enable two factor", User: u, Data: map[string]any{"Settings": "security", "Secret": secret, "Token": token, "QR": template.URL("data:image/png;base64," + base64.StdEncoding.EncodeToString(png)), "URI": uri}})
}

func (s *Server) enableTOTP(w http.ResponseWriter, r *http.Request) {
	u := s.require(w, r)
	if u == nil {
		return
	}
	var secret string
	var created int64
	err := s.store.db.QueryRow(`select email, created from mailtokens where token = ? and kind = 'totpsetup' and user = ?`, r.FormValue("token"), u.ID).Scan(&secret, &created)
	if err != nil || !totpValid(secret, r.FormValue("code")) {
		http.Redirect(w, r, "/settings/security?error=That+code+did+not+match%2C+start+again", http.StatusSeeOther)
		return
	}
	s.store.db.Exec(`delete from mailtokens where token = ?`, r.FormValue("token"))
	codes, hashes := newRecoveryCodes()
	s.store.SetTOTP(u.ID, secret, hashes)
	s.render(w, r, "recovery", page{Title: "Recovery codes", User: u, Data: map[string]any{"Settings": "security", "Codes": codes}})
}

func (s *Server) disableTOTP(w http.ResponseWriter, r *http.Request) {
	u := s.require(w, r)
	if u == nil {
		return
	}
	if _, ok := s.store.CheckPassword(u.Name, r.FormValue("password")); !ok {
		http.Redirect(w, r, "/settings/security?error=Wrong+password", http.StatusSeeOther)
		return
	}
	s.store.SetTOTP(u.ID, "", "")
	http.Redirect(w, r, "/settings/security", http.StatusSeeOther)
}