| 1 |
package server |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/json" |
| 5 |
"errors" |
| 6 |
"net/http" |
| 7 |
"net/netip" |
| 8 |
"strings" |
| 9 |
"time" |
| 10 |
|
| 11 |
"heckel.io/ntfy/v2/log" |
| 12 |
"heckel.io/ntfy/v2/model" |
| 13 |
"heckel.io/ntfy/v2/twilio" |
| 14 |
"heckel.io/ntfy/v2/user" |
| 15 |
"heckel.io/ntfy/v2/util" |
| 16 |
) |
| 17 |
|
| 18 |
const ( |
| 19 |
syncTopicAccountSyncEvent = "sync" |
| 20 |
tokenExpiryDuration = 72 * time.Hour // Extend tokens by this much |
| 21 |
emailVerificationTokenExpiry = 24 * time.Hour // Magic-link lifetime for email verification |
| 22 |
passwordResetTokenExpiry = time.Hour // Magic-link lifetime for password reset (higher-privilege -> shorter) |
| 23 |
) |
| 24 |
|
| 25 |
func (s *Server) handleAccountCreate(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 26 |
u := v.User() |
| 27 |
if !u.IsAdmin() { // u may be nil, but that's fine |
| 28 |
if !s.config.EnableSignup { |
| 29 |
return errHTTPBadRequestSignupNotEnabled |
| 30 |
} else if u != nil { |
| 31 |
return errHTTPUnauthorized // Cannot create account from user context |
| 32 |
} |
| 33 |
if !v.AccountActionAllowed() { |
| 34 |
return errHTTPTooManyRequestsLimitAccountActions |
| 35 |
} |
| 36 |
} |
| 37 |
newAccount, err := readJSONWithLimit[apiAccountCreateRequest](r.Body, jsonBodyBytesLimit, false) |
| 38 |
if err != nil { |
| 39 |
return err |
| 40 |
} |
| 41 |
if newAccount.Email != "" && !emailAddressRegex.MatchString(newAccount.Email) { |
| 42 |
return errHTTPBadRequestEmailAddressInvalid |
| 43 |
} |
| 44 |
if existingUser, _ := s.userManager.User(newAccount.Username); existingUser != nil { |
| 45 |
return errHTTPConflictUserExists |
| 46 |
} |
| 47 |
logvr(v, r).Tag(tagAccount).Field("user_name", newAccount.Username).Info("Creating user %s", newAccount.Username) |
| 48 |
if err := s.userManager.AddUser(newAccount.Username, newAccount.Password, user.RoleUser, false); err != nil { |
| 49 |
if errors.Is(err, user.ErrInvalidArgument) { |
| 50 |
return errHTTPBadRequestInvalidUsername |
| 51 |
} |
| 52 |
return err |
| 53 |
} |
| 54 |
v.AccountActionPerformed() |
| 55 |
// If an email was provided and email sending is configured, start verification (best-effort). |
| 56 |
// The address becomes the primary email on verify (the new account has no primary yet); a |
| 57 |
// failure to send must not fail signup, so we only log it. |
| 58 |
if newAccount.Email != "" && s.mailer != nil { |
| 59 |
if u, err := s.userManager.User(newAccount.Username); err != nil { |
| 60 |
logvr(v, r).Tag(tagAccount).Err(err).Warn("Failed to load new user for email verification") |
| 61 |
} else if err := s.enqueueEmailVerification(u.ID, newAccount.Email); err != nil { |
| 62 |
logvr(v, r).Tag(tagAccount).Err(err).Warn("Failed to send signup email verification") |
| 63 |
} |
| 64 |
} |
| 65 |
return s.writeJSON(w, newSuccessResponse()) |
| 66 |
} |
| 67 |
|
| 68 |
func (s *Server) handleAccountGet(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 69 |
info, err := v.Info() |
| 70 |
if err != nil { |
| 71 |
return err |
| 72 |
} |
| 73 |
logvr(v, r).Tag(tagAccount).Fields(visitorExtendedInfoContext(info)).Debug("Retrieving account stats") |
| 74 |
limits, stats := info.Limits, info.Stats |
| 75 |
response := &apiAccountResponse{ |
| 76 |
Limits: &apiAccountLimits{ |
| 77 |
Basis: string(limits.Basis), |
| 78 |
Messages: limits.MessageLimit, |
| 79 |
MessagesExpiryDuration: int64(limits.MessageExpiryDuration.Seconds()), |
| 80 |
Emails: limits.EmailLimit, |
| 81 |
Calls: limits.CallLimit, |
| 82 |
Reservations: limits.ReservationsLimit, |
| 83 |
AttachmentTotalSize: limits.AttachmentTotalSizeLimit, |
| 84 |
AttachmentFileSize: limits.AttachmentFileSizeLimit, |
| 85 |
AttachmentExpiryDuration: int64(limits.AttachmentExpiryDuration.Seconds()), |
| 86 |
AttachmentBandwidth: limits.AttachmentBandwidthLimit, |
| 87 |
}, |
| 88 |
Stats: &apiAccountStats{ |
| 89 |
Messages: stats.Messages, |
| 90 |
MessagesRemaining: stats.MessagesRemaining, |
| 91 |
Emails: stats.Emails, |
| 92 |
EmailsRemaining: stats.EmailsRemaining, |
| 93 |
Calls: stats.Calls, |
| 94 |
CallsRemaining: stats.CallsRemaining, |
| 95 |
Reservations: stats.Reservations, |
| 96 |
ReservationsRemaining: stats.ReservationsRemaining, |
| 97 |
AttachmentTotalSize: stats.AttachmentTotalSize, |
| 98 |
AttachmentTotalSizeRemaining: stats.AttachmentTotalSizeRemaining, |
| 99 |
}, |
| 100 |
} |
| 101 |
u := v.User() |
| 102 |
if u != nil { |
| 103 |
response.Username = u.Name |
| 104 |
response.Role = string(u.Role) |
| 105 |
response.SyncTopic = u.SyncTopic |
| 106 |
response.Provisioned = u.Provisioned |
| 107 |
if u.Prefs != nil { |
| 108 |
if u.Prefs.Language != nil { |
| 109 |
response.Language = *u.Prefs.Language |
| 110 |
} |
| 111 |
if u.Prefs.DateFormat != nil { |
| 112 |
response.DateFormat = *u.Prefs.DateFormat |
| 113 |
} |
| 114 |
if u.Prefs.TimeFormat != nil { |
| 115 |
response.TimeFormat = *u.Prefs.TimeFormat |
| 116 |
} |
| 117 |
if u.Prefs.Notification != nil { |
| 118 |
response.Notification = u.Prefs.Notification |
| 119 |
} |
| 120 |
if u.Prefs.Subscriptions != nil { |
| 121 |
response.Subscriptions = u.Prefs.Subscriptions |
| 122 |
} |
| 123 |
} |
| 124 |
if u.Tier != nil { |
| 125 |
response.Tier = &apiAccountTier{ |
| 126 |
Code: u.Tier.Code, |
| 127 |
Name: u.Tier.Name, |
| 128 |
} |
| 129 |
} |
| 130 |
if u.Billing.StripeCustomerID != "" { |
| 131 |
response.Billing = &apiAccountBilling{ |
| 132 |
Customer: true, |
| 133 |
Subscription: u.Billing.StripeSubscriptionID != "", |
| 134 |
Status: string(u.Billing.StripeSubscriptionStatus), |
| 135 |
Interval: string(u.Billing.StripeSubscriptionInterval), |
| 136 |
PaidUntil: u.Billing.StripeSubscriptionPaidUntil.Unix(), |
| 137 |
CancelAt: u.Billing.StripeSubscriptionCancelAt.Unix(), |
| 138 |
} |
| 139 |
} |
| 140 |
if s.config.EnableReservations { |
| 141 |
reservations, err := s.userManager.Reservations(u.Name) |
| 142 |
if err != nil { |
| 143 |
return err |
| 144 |
} |
| 145 |
if len(reservations) > 0 { |
| 146 |
response.Reservations = make([]*apiAccountReservation, 0) |
| 147 |
for _, r := range reservations { |
| 148 |
response.Reservations = append(response.Reservations, &apiAccountReservation{ |
| 149 |
Topic: r.Topic, |
| 150 |
Everyone: r.Everyone.String(), |
| 151 |
}) |
| 152 |
} |
| 153 |
} |
| 154 |
} |
| 155 |
tokens, err := s.userManager.Tokens(u.ID) |
| 156 |
if err != nil { |
| 157 |
return err |
| 158 |
} |
| 159 |
if len(tokens) > 0 { |
| 160 |
response.Tokens = make([]*apiAccountTokenResponse, 0) |
| 161 |
for _, t := range tokens { |
| 162 |
var lastOrigin string |
| 163 |
if t.LastOrigin != netip.IPv4Unspecified() { |
| 164 |
lastOrigin = t.LastOrigin.String() |
| 165 |
} |
| 166 |
response.Tokens = append(response.Tokens, &apiAccountTokenResponse{ |
| 167 |
Token: t.Value, |
| 168 |
Label: t.Label, |
| 169 |
LastAccess: t.LastAccess.Unix(), |
| 170 |
LastOrigin: lastOrigin, |
| 171 |
Expires: t.Expires.Unix(), |
| 172 |
Provisioned: t.Provisioned, |
| 173 |
}) |
| 174 |
} |
| 175 |
} |
| 176 |
if s.config.TwilioAccount != "" { |
| 177 |
phoneNumbers, err := s.userManager.PhoneNumbers(u.ID) |
| 178 |
if err != nil { |
| 179 |
return err |
| 180 |
} |
| 181 |
if len(phoneNumbers) > 0 { |
| 182 |
response.PhoneNumbers = phoneNumbers |
| 183 |
} |
| 184 |
} |
| 185 |
if s.mailer != nil { |
| 186 |
emails, err := s.userManager.Emails(u.ID) |
| 187 |
if err != nil { |
| 188 |
return err |
| 189 |
} |
| 190 |
pendingEmails, err := s.userManager.PendingEmails(u.ID) |
| 191 |
if err != nil { |
| 192 |
return err |
| 193 |
} |
| 194 |
// Combine verified (with primary flag) and pending (unverified) into one list |
| 195 |
emailInfos := make([]*apiAccountEmailInfo, 0, len(emails)+len(pendingEmails)) |
| 196 |
for _, email := range emails { |
| 197 |
emailInfos = append(emailInfos, &apiAccountEmailInfo{Address: email.Address, Primary: email.Primary}) |
| 198 |
} |
| 199 |
for _, email := range pendingEmails { |
| 200 |
emailInfos = append(emailInfos, &apiAccountEmailInfo{Address: email, Pending: true}) |
| 201 |
} |
| 202 |
if len(emailInfos) > 0 { |
| 203 |
response.Emails = emailInfos |
| 204 |
} |
| 205 |
} |
| 206 |
} else { |
| 207 |
response.Username = user.Everyone |
| 208 |
response.Role = string(user.RoleAnonymous) |
| 209 |
} |
| 210 |
return s.writeJSON(w, response) |
| 211 |
} |
| 212 |
|
| 213 |
func (s *Server) handleAccountDelete(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 214 |
req, err := readJSONWithLimit[apiAccountDeleteRequest](r.Body, jsonBodyBytesLimit, false) |
| 215 |
if err != nil { |
| 216 |
return err |
| 217 |
} else if req.Password == "" { |
| 218 |
return errHTTPBadRequest |
| 219 |
} |
| 220 |
u := v.User() |
| 221 |
if _, err := s.userManager.Authenticate(u.Name, req.Password); err != nil { |
| 222 |
return errHTTPBadRequestIncorrectPasswordConfirmation |
| 223 |
} |
| 224 |
if err := s.userManager.CanChangeUser(u.Name); err != nil { |
| 225 |
if errors.Is(err, user.ErrProvisionedUserChange) { |
| 226 |
return errHTTPConflictProvisionedUserChange |
| 227 |
} |
| 228 |
return err |
| 229 |
} |
| 230 |
if s.webPush != nil && u.ID != "" { |
| 231 |
if err := s.webPush.RemoveSubscriptionsByUserID(u.ID); err != nil { |
| 232 |
logvr(v, r).Err(err).Warn("Error removing web push subscriptions for %s", u.Name) |
| 233 |
} |
| 234 |
} |
| 235 |
if u.Billing.StripeSubscriptionID != "" { |
| 236 |
logvr(v, r).Tag(tagStripe).Info("Canceling billing subscription for user %s", u.Name) |
| 237 |
if _, err := s.stripe.CancelSubscription(u.Billing.StripeSubscriptionID); err != nil { |
| 238 |
return err |
| 239 |
} |
| 240 |
} |
| 241 |
if err := s.maybeRemoveMessagesAndExcessReservations(r, v, u, 0); err != nil { |
| 242 |
return err |
| 243 |
} |
| 244 |
logvr(v, r).Tag(tagAccount).Info("Marking user %s as deleted", u.Name) |
| 245 |
if err := s.userManager.MarkUserRemoved(u); err != nil { |
| 246 |
return err |
| 247 |
} |
| 248 |
return s.writeJSON(w, newSuccessResponse()) |
| 249 |
} |
| 250 |
|
| 251 |
func (s *Server) handleAccountPasswordChange(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 252 |
req, err := readJSONWithLimit[apiAccountPasswordChangeRequest](r.Body, jsonBodyBytesLimit, false) |
| 253 |
if err != nil { |
| 254 |
return err |
| 255 |
} else if req.Password == "" || req.NewPassword == "" { |
| 256 |
return errHTTPBadRequest |
| 257 |
} |
| 258 |
u := v.User() |
| 259 |
if _, err := s.userManager.Authenticate(u.Name, req.Password); err != nil { |
| 260 |
return errHTTPBadRequestIncorrectPasswordConfirmation |
| 261 |
} |
| 262 |
logvr(v, r).Tag(tagAccount).Debug("Changing password for user %s", u.Name) |
| 263 |
if err := s.userManager.ChangePassword(u.Name, req.NewPassword, false); err != nil { |
| 264 |
if errors.Is(err, user.ErrProvisionedUserChange) { |
| 265 |
return errHTTPConflictProvisionedUserChange |
| 266 |
} |
| 267 |
return err |
| 268 |
} |
| 269 |
return s.writeJSON(w, newSuccessResponse()) |
| 270 |
} |
| 271 |
|
| 272 |
// handleAccountLogin authenticates a username-or-email + password (via the ensureUser wrapper's |
| 273 |
// Basic Auth), mints a session token, and returns it together with the canonical username. Unlike |
| 274 |
// the token endpoint (which exists to mint arbitrary API tokens), this endpoint's job is to log a |
| 275 |
// user in, so it also reports who they are (the identifier they typed may be a primary email). |
| 276 |
func (s *Server) handleAccountLogin(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 277 |
u := v.User() |
| 278 |
logvr(v, r).Tag(tagAccount).Info("Logging in user %s", u.Name) |
| 279 |
token, err := s.userManager.CreateToken(u.ID, "", time.Now().Add(tokenExpiryDuration), v.IP(), false) |
| 280 |
if err != nil { |
| 281 |
return err |
| 282 |
} |
| 283 |
response := &apiAccountLoginResponse{ |
| 284 |
Token: token.Value, |
| 285 |
Username: u.Name, |
| 286 |
} |
| 287 |
return s.writeJSON(w, response) |
| 288 |
} |
| 289 |
|
| 290 |
func (s *Server) handleAccountTokenCreate(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 291 |
req, err := readJSONWithLimit[apiAccountTokenIssueRequest](r.Body, jsonBodyBytesLimit, true) // Allow empty body! |
| 292 |
if err != nil { |
| 293 |
return err |
| 294 |
} |
| 295 |
var label string |
| 296 |
if req.Label != nil { |
| 297 |
label = *req.Label |
| 298 |
} |
| 299 |
expires := time.Now().Add(tokenExpiryDuration) |
| 300 |
if req.Expires != nil { |
| 301 |
expires = time.Unix(*req.Expires, 0) |
| 302 |
} |
| 303 |
u := v.User() |
| 304 |
logvr(v, r). |
| 305 |
Tag(tagAccount). |
| 306 |
Fields(log.Context{ |
| 307 |
"token_label": label, |
| 308 |
"token_expires": expires, |
| 309 |
}). |
| 310 |
Debug("Creating token for user %s", u.Name) |
| 311 |
token, err := s.userManager.CreateToken(u.ID, label, expires, v.IP(), false) |
| 312 |
if err != nil { |
| 313 |
return err |
| 314 |
} |
| 315 |
response := &apiAccountTokenResponse{ |
| 316 |
Token: token.Value, |
| 317 |
Label: token.Label, |
| 318 |
LastAccess: token.LastAccess.Unix(), |
| 319 |
LastOrigin: token.LastOrigin.String(), |
| 320 |
Expires: token.Expires.Unix(), |
| 321 |
} |
| 322 |
return s.writeJSON(w, response) |
| 323 |
} |
| 324 |
|
| 325 |
func (s *Server) handleAccountTokenUpdate(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 326 |
u := v.User() |
| 327 |
req, err := readJSONWithLimit[apiAccountTokenUpdateRequest](r.Body, jsonBodyBytesLimit, true) // Allow empty body! |
| 328 |
if err != nil { |
| 329 |
return err |
| 330 |
} else if req.Token == "" { |
| 331 |
req.Token = u.Token |
| 332 |
if req.Token == "" { |
| 333 |
return errHTTPBadRequestNoTokenProvided |
| 334 |
} |
| 335 |
} |
| 336 |
var expires *time.Time |
| 337 |
if req.Expires != nil { |
| 338 |
expires = util.Time(time.Unix(*req.Expires, 0)) |
| 339 |
} else if req.Label == nil { |
| 340 |
expires = util.Time(time.Now().Add(tokenExpiryDuration)) // If label/expires not set, extend token by 72 hours |
| 341 |
} |
| 342 |
logvr(v, r). |
| 343 |
Tag(tagAccount). |
| 344 |
Fields(log.Context{ |
| 345 |
"token_label": req.Label, |
| 346 |
"token_expires": expires, |
| 347 |
}). |
| 348 |
Debug("Updating token for user %s as deleted", u.Name) |
| 349 |
token, err := s.userManager.ChangeToken(u.ID, req.Token, req.Label, expires) |
| 350 |
if err != nil { |
| 351 |
if errors.Is(err, user.ErrProvisionedTokenChange) { |
| 352 |
return errHTTPConflictProvisionedTokenChange |
| 353 |
} |
| 354 |
return err |
| 355 |
} |
| 356 |
response := &apiAccountTokenResponse{ |
| 357 |
Token: token.Value, |
| 358 |
Label: token.Label, |
| 359 |
LastAccess: token.LastAccess.Unix(), |
| 360 |
LastOrigin: token.LastOrigin.String(), |
| 361 |
Expires: token.Expires.Unix(), |
| 362 |
} |
| 363 |
return s.writeJSON(w, response) |
| 364 |
} |
| 365 |
|
| 366 |
func (s *Server) handleAccountTokenDelete(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 367 |
u := v.User() |
| 368 |
token := readParam(r, "X-Token", "Token") // DELETEs cannot have a body, and we don't want it in the path |
| 369 |
if token == "" { |
| 370 |
token = u.Token |
| 371 |
if token == "" { |
| 372 |
return errHTTPBadRequestNoTokenProvided |
| 373 |
} |
| 374 |
} |
| 375 |
if err := s.userManager.RemoveToken(u.ID, token); err != nil { |
| 376 |
if errors.Is(err, user.ErrProvisionedTokenChange) { |
| 377 |
return errHTTPConflictProvisionedTokenChange |
| 378 |
} |
| 379 |
return err |
| 380 |
} |
| 381 |
logvr(v, r). |
| 382 |
Tag(tagAccount). |
| 383 |
Field("token", token). |
| 384 |
Debug("Deleted token for user %s", u.Name) |
| 385 |
return s.writeJSON(w, newSuccessResponse()) |
| 386 |
} |
| 387 |
|
| 388 |
func (s *Server) handleAccountSettingsChange(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 389 |
newPrefs, err := readJSONWithLimit[user.Prefs](r.Body, jsonBodyBytesLimit, false) |
| 390 |
if err != nil { |
| 391 |
return err |
| 392 |
} |
| 393 |
u := v.User() |
| 394 |
if u.Prefs == nil { |
| 395 |
u.Prefs = &user.Prefs{} |
| 396 |
} |
| 397 |
prefs := u.Prefs |
| 398 |
if newPrefs.Language != nil { |
| 399 |
prefs.Language = newPrefs.Language |
| 400 |
} |
| 401 |
if newPrefs.DateFormat != nil { |
| 402 |
prefs.DateFormat = newPrefs.DateFormat |
| 403 |
} |
| 404 |
if newPrefs.TimeFormat != nil { |
| 405 |
prefs.TimeFormat = newPrefs.TimeFormat |
| 406 |
} |
| 407 |
if newPrefs.Notification != nil { |
| 408 |
if prefs.Notification == nil { |
| 409 |
prefs.Notification = &user.NotificationPrefs{} |
| 410 |
} |
| 411 |
if newPrefs.Notification.DeleteAfter != nil { |
| 412 |
prefs.Notification.DeleteAfter = newPrefs.Notification.DeleteAfter |
| 413 |
} |
| 414 |
if newPrefs.Notification.Sound != nil { |
| 415 |
prefs.Notification.Sound = newPrefs.Notification.Sound |
| 416 |
} |
| 417 |
if newPrefs.Notification.MinPriority != nil { |
| 418 |
prefs.Notification.MinPriority = newPrefs.Notification.MinPriority |
| 419 |
} |
| 420 |
} |
| 421 |
logvr(v, r).Tag(tagAccount).Debug("Changing account settings for user %s", u.Name) |
| 422 |
if err := s.userManager.ChangeSettings(u.ID, prefs); err != nil { |
| 423 |
return err |
| 424 |
} |
| 425 |
return s.writeJSON(w, newSuccessResponse()) |
| 426 |
} |
| 427 |
|
| 428 |
func (s *Server) handleAccountSubscriptionAdd(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 429 |
newSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit, false) |
| 430 |
if err != nil { |
| 431 |
return err |
| 432 |
} |
| 433 |
u := v.User() |
| 434 |
prefs := u.Prefs |
| 435 |
if prefs == nil { |
| 436 |
prefs = &user.Prefs{} |
| 437 |
} |
| 438 |
for _, subscription := range prefs.Subscriptions { |
| 439 |
if newSubscription.BaseURL == subscription.BaseURL && newSubscription.Topic == subscription.Topic { |
| 440 |
return errHTTPConflictSubscriptionExists |
| 441 |
} |
| 442 |
} |
| 443 |
prefs.Subscriptions = append(prefs.Subscriptions, newSubscription) |
| 444 |
logvr(v, r).Tag(tagAccount).With(newSubscription).Debug("Adding subscription for user %s", u.Name) |
| 445 |
if err := s.userManager.ChangeSettings(u.ID, prefs); err != nil { |
| 446 |
return err |
| 447 |
} |
| 448 |
return s.writeJSON(w, newSubscription) |
| 449 |
} |
| 450 |
|
| 451 |
func (s *Server) handleAccountSubscriptionChange(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 452 |
updatedSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit, false) |
| 453 |
if err != nil { |
| 454 |
return err |
| 455 |
} |
| 456 |
u := v.User() |
| 457 |
prefs := u.Prefs |
| 458 |
if prefs == nil || prefs.Subscriptions == nil { |
| 459 |
return errHTTPNotFound |
| 460 |
} |
| 461 |
var subscription *user.Subscription |
| 462 |
for _, sub := range prefs.Subscriptions { |
| 463 |
if sub.BaseURL == updatedSubscription.BaseURL && sub.Topic == updatedSubscription.Topic { |
| 464 |
sub.DisplayName = updatedSubscription.DisplayName |
| 465 |
subscription = sub |
| 466 |
break |
| 467 |
} |
| 468 |
} |
| 469 |
if subscription == nil { |
| 470 |
return errHTTPNotFound |
| 471 |
} |
| 472 |
logvr(v, r).Tag(tagAccount).With(subscription).Debug("Changing subscription for user %s", u.Name) |
| 473 |
if err := s.userManager.ChangeSettings(u.ID, prefs); err != nil { |
| 474 |
return err |
| 475 |
} |
| 476 |
return s.writeJSON(w, subscription) |
| 477 |
} |
| 478 |
|
| 479 |
func (s *Server) handleAccountSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 480 |
// DELETEs cannot have a body, and we don't want it in the path |
| 481 |
deleteBaseURL := readParam(r, "X-BaseURL", "BaseURL") |
| 482 |
deleteTopic := readParam(r, "X-Topic", "Topic") |
| 483 |
u := v.User() |
| 484 |
prefs := u.Prefs |
| 485 |
if prefs == nil || prefs.Subscriptions == nil { |
| 486 |
return nil |
| 487 |
} |
| 488 |
newSubscriptions := make([]*user.Subscription, 0) |
| 489 |
for _, sub := range u.Prefs.Subscriptions { |
| 490 |
if sub.BaseURL == deleteBaseURL && sub.Topic == deleteTopic { |
| 491 |
logvr(v, r).Tag(tagAccount).With(sub).Debug("Removing subscription for user %s", u.Name) |
| 492 |
} else { |
| 493 |
newSubscriptions = append(newSubscriptions, sub) |
| 494 |
} |
| 495 |
} |
| 496 |
if len(newSubscriptions) < len(prefs.Subscriptions) { |
| 497 |
prefs.Subscriptions = newSubscriptions |
| 498 |
if err := s.userManager.ChangeSettings(u.ID, prefs); err != nil { |
| 499 |
return err |
| 500 |
} |
| 501 |
} |
| 502 |
return s.writeJSON(w, newSuccessResponse()) |
| 503 |
} |
| 504 |
|
| 505 |
// handleAccountReservationAdd adds a topic reservation for the logged-in user, but only if the user has a tier |
| 506 |
// with enough remaining reservations left, or if the user is an admin. Admins can always reserve a topic, unless |
| 507 |
// it is already reserved by someone else. |
| 508 |
func (s *Server) handleAccountReservationAdd(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 509 |
u := v.User() |
| 510 |
req, err := readJSONWithLimit[apiAccountReservationRequest](r.Body, jsonBodyBytesLimit, false) |
| 511 |
if err != nil { |
| 512 |
return err |
| 513 |
} |
| 514 |
if !topicRegex.MatchString(req.Topic) { |
| 515 |
return errHTTPBadRequestTopicInvalid |
| 516 |
} |
| 517 |
everyone, err := user.ParsePermission(req.Everyone) |
| 518 |
if err != nil { |
| 519 |
return errHTTPBadRequestPermissionInvalid |
| 520 |
} |
| 521 |
// Check if we are allowed to reserve this topic |
| 522 |
if u.IsUser() && u.Tier == nil { |
| 523 |
return errHTTPUnauthorized |
| 524 |
} else if err := s.userManager.AllowReservation(u.Name, req.Topic); err != nil { |
| 525 |
return errHTTPConflictTopicReserved |
| 526 |
} |
| 527 |
// Actually add the reservation (with limit check inside the transaction to avoid races) |
| 528 |
logvr(v, r). |
| 529 |
Tag(tagAccount). |
| 530 |
Fields(log.Context{ |
| 531 |
"topic": req.Topic, |
| 532 |
"everyone": everyone.String(), |
| 533 |
}). |
| 534 |
Debug("Adding topic reservation") |
| 535 |
var limit int64 |
| 536 |
if u.IsUser() && u.Tier != nil { |
| 537 |
limit = u.Tier.ReservationLimit |
| 538 |
} |
| 539 |
if err := s.userManager.AddReservation(u.Name, req.Topic, everyone, limit); err != nil { |
| 540 |
if errors.Is(err, user.ErrTooManyReservations) { |
| 541 |
return errHTTPTooManyRequestsLimitReservations |
| 542 |
} |
| 543 |
return err |
| 544 |
} |
| 545 |
// Kill existing subscribers |
| 546 |
t, err := s.topicFromID(v, req.Topic) |
| 547 |
if err != nil { |
| 548 |
return err |
| 549 |
} |
| 550 |
t.CancelSubscribersExceptUser(u.ID) |
| 551 |
return s.writeJSON(w, newSuccessResponse()) |
| 552 |
} |
| 553 |
|
| 554 |
// handleAccountReservationDelete deletes a topic reservation if it is owned by the current user |
| 555 |
func (s *Server) handleAccountReservationDelete(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 556 |
matches := apiAccountReservationSingleRegex.FindStringSubmatch(r.URL.Path) |
| 557 |
if len(matches) != 2 { |
| 558 |
return errHTTPInternalErrorInvalidPath |
| 559 |
} |
| 560 |
topic := matches[1] |
| 561 |
if !topicRegex.MatchString(topic) { |
| 562 |
return errHTTPBadRequestTopicInvalid |
| 563 |
} |
| 564 |
u := v.User() |
| 565 |
authorized, err := s.userManager.HasReservation(u.Name, topic) |
| 566 |
if err != nil { |
| 567 |
return err |
| 568 |
} else if !authorized { |
| 569 |
return errHTTPUnauthorized |
| 570 |
} |
| 571 |
deleteMessages := readBoolParam(r, false, "X-Delete-Messages", "Delete-Messages") |
| 572 |
logvr(v, r). |
| 573 |
Tag(tagAccount). |
| 574 |
Fields(log.Context{ |
| 575 |
"topic": topic, |
| 576 |
"delete_messages": deleteMessages, |
| 577 |
}). |
| 578 |
Debug("Removing topic reservation") |
| 579 |
if err := s.userManager.RemoveReservations(u.Name, topic); err != nil { |
| 580 |
return err |
| 581 |
} |
| 582 |
if deleteMessages { |
| 583 |
if err := s.messageCache.ExpireMessages(topic); err != nil { |
| 584 |
return err |
| 585 |
} |
| 586 |
s.pruneMessages() |
| 587 |
} |
| 588 |
return s.writeJSON(w, newSuccessResponse()) |
| 589 |
} |
| 590 |
|
| 591 |
// maybeRemoveMessagesAndExcessReservations deletes topic reservations for the given user (if too many for tier), |
| 592 |
// and marks associated messages for the topics as deleted. This also eventually deletes attachments. |
| 593 |
// The process relies on the manager to perform the actual deletions (see runManager). |
| 594 |
func (s *Server) maybeRemoveMessagesAndExcessReservations(r *http.Request, v *visitor, u *user.User, reservationsLimit int64) error { |
| 595 |
removedTopics, err := s.userManager.RemoveExcessReservations(u.Name, reservationsLimit) |
| 596 |
if err != nil { |
| 597 |
return err |
| 598 |
} else if len(removedTopics) == 0 { |
| 599 |
logvr(v, r).Tag(tagAccount).Debug("No excess reservations to remove") |
| 600 |
return nil |
| 601 |
} |
| 602 |
logvr(v, r).Tag(tagAccount).Info("Removed excess topic reservations, now removing messages for topics %s", strings.Join(removedTopics, ", ")) |
| 603 |
if err := s.messageCache.ExpireMessages(removedTopics...); err != nil { |
| 604 |
return err |
| 605 |
} |
| 606 |
go s.pruneMessages() |
| 607 |
return nil |
| 608 |
} |
| 609 |
|
| 610 |
func (s *Server) handleAccountPhoneNumberVerify(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 611 |
u := v.User() |
| 612 |
req, err := readJSONWithLimit[apiAccountPhoneNumberVerifyRequest](r.Body, jsonBodyBytesLimit, false) |
| 613 |
if err != nil { |
| 614 |
return err |
| 615 |
} else if !phoneNumberRegex.MatchString(req.Number) { |
| 616 |
return errHTTPBadRequestPhoneNumberInvalid |
| 617 |
} else if req.Channel != "sms" && req.Channel != "call" { |
| 618 |
return errHTTPBadRequestPhoneNumberVerifyChannelInvalid |
| 619 |
} |
| 620 |
// Check user is allowed to add phone numbers |
| 621 |
if u == nil || (u.IsUser() && u.Tier == nil) { |
| 622 |
return errHTTPUnauthorized |
| 623 |
} else if u.IsUser() && u.Tier.CallLimit == 0 { |
| 624 |
return errHTTPUnauthorized |
| 625 |
} |
| 626 |
// Check if phone number exists |
| 627 |
phoneNumbers, err := s.userManager.PhoneNumbers(u.ID) |
| 628 |
if err != nil { |
| 629 |
return err |
| 630 |
} else if util.Contains(phoneNumbers, req.Number) { |
| 631 |
return errHTTPConflictPhoneNumberExists |
| 632 |
} |
| 633 |
// Actually add the unverified number, and send verification |
| 634 |
logvr(v, r).Tag(tagAccount).Field("phone_number", req.Number).Debug("Sending phone number verification") |
| 635 |
if err := s.twilio.Verify(req.Number, req.Channel); err != nil { |
| 636 |
return err |
| 637 |
} |
| 638 |
return s.writeJSON(w, newSuccessResponse()) |
| 639 |
} |
| 640 |
|
| 641 |
func (s *Server) handleAccountPhoneNumberAdd(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 642 |
u := v.User() |
| 643 |
req, err := readJSONWithLimit[apiAccountPhoneNumberAddRequest](r.Body, jsonBodyBytesLimit, false) |
| 644 |
if err != nil { |
| 645 |
return err |
| 646 |
} |
| 647 |
if !phoneNumberRegex.MatchString(req.Number) { |
| 648 |
return errHTTPBadRequestPhoneNumberInvalid |
| 649 |
} |
| 650 |
if err := s.twilio.CheckVerify(req.Number, req.Code); err != nil { |
| 651 |
if errors.Is(err, twilio.ErrVerificationExpired) { |
| 652 |
return errHTTPGonePhoneVerificationExpired |
| 653 |
} |
| 654 |
return err |
| 655 |
} |
| 656 |
logvr(v, r).Tag(tagAccount).Field("phone_number", req.Number).Debug("Adding phone number as verified") |
| 657 |
if err := s.userManager.AddPhoneNumber(u.ID, req.Number); err != nil { |
| 658 |
return err |
| 659 |
} |
| 660 |
return s.writeJSON(w, newSuccessResponse()) |
| 661 |
} |
| 662 |
|
| 663 |
func (s *Server) handleAccountPhoneNumberDelete(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 664 |
u := v.User() |
| 665 |
req, err := readJSONWithLimit[apiAccountPhoneNumberAddRequest](r.Body, jsonBodyBytesLimit, false) |
| 666 |
if err != nil { |
| 667 |
return err |
| 668 |
} |
| 669 |
if !phoneNumberRegex.MatchString(req.Number) { |
| 670 |
return errHTTPBadRequestPhoneNumberInvalid |
| 671 |
} |
| 672 |
logvr(v, r).Tag(tagAccount).Field("phone_number", req.Number).Debug("Deleting phone number") |
| 673 |
if err := s.userManager.RemovePhoneNumber(u.ID, req.Number); err != nil { |
| 674 |
return err |
| 675 |
} |
| 676 |
return s.writeJSON(w, newSuccessResponse()) |
| 677 |
} |
| 678 |
|
| 679 |
// handleAccountEmailAdd starts email verification (PUT /v1/account/email): it generates a |
| 680 |
// magic-link token, stores a pending verification, and emails the link. The address is NOT |
| 681 |
// added to the verified list until the user clicks the link (handleAccountEmailVerify). |
| 682 |
func (s *Server) handleAccountEmailAdd(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 683 |
u := v.User() |
| 684 |
req, err := readJSONWithLimit[apiAccountEmailRequest](r.Body, jsonBodyBytesLimit, false) |
| 685 |
if err != nil { |
| 686 |
return err |
| 687 |
} else if !emailAddressRegex.MatchString(req.Email) { |
| 688 |
return errHTTPBadRequestEmailAddressInvalid |
| 689 |
} |
| 690 |
// Check user is allowed to add emails (the tier email limit gates the feature) |
| 691 |
if u.IsUser() && u.Tier != nil && u.Tier.EmailLimit == 0 { |
| 692 |
return errHTTPUnauthorized |
| 693 |
} else if u.IsUser() && u.Tier == nil && s.config.VisitorEmailLimitBurst == 0 { |
| 694 |
return errHTTPUnauthorized |
| 695 |
} |
| 696 |
// Reject if already verified on this account (pending re-requests are fine -- they replace) |
| 697 |
emails, err := s.userManager.Emails(u.ID) |
| 698 |
if err != nil { |
| 699 |
return err |
| 700 |
} else if emails.Contains(req.Email) { |
| 701 |
return errHTTPConflictEmailExists |
| 702 |
} |
| 703 |
// Rate limit (counts against the user's email quota) |
| 704 |
if !v.EmailAllowed() { |
| 705 |
return errHTTPTooManyRequestsLimitEmails |
| 706 |
} |
| 707 |
logvr(v, r).Tag(tagAccount).Field("email", req.Email).Info("Starting email verification") |
| 708 |
if err := s.enqueueEmailVerification(u.ID, req.Email); err != nil { |
| 709 |
return err |
| 710 |
} |
| 711 |
return s.writeJSON(w, newSuccessResponse()) |
| 712 |
} |
| 713 |
|
| 714 |
// handleAccountEmailVerify performs verification from the (unauthenticated) landing page |
| 715 |
// (POST /v1/account/email/verify): it validates the raw token, adds the address to the user's |
| 716 |
// verified emails, and -- if the user has no primary yet -- promotes it. No auth is required; |
| 717 |
// the token binds the action to a user, so the click works from a logged-out mail client. |
| 718 |
func (s *Server) handleAccountEmailVerify(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 719 |
req, err := readJSONWithLimit[apiAccountEmailVerifyRequest](r.Body, jsonBodyBytesLimit, false) |
| 720 |
if err != nil { |
| 721 |
return err |
| 722 |
} else if req.Token == "" { |
| 723 |
return errHTTPBadRequestEmailVerificationLinkInvalid |
| 724 |
} |
| 725 |
m, err := s.userManager.VerifyEmail(req.Token) |
| 726 |
if errors.Is(err, user.ErrMagicLinkNotFound) { |
| 727 |
return errHTTPBadRequestEmailVerificationLinkInvalid |
| 728 |
} else if err != nil { |
| 729 |
return err |
| 730 |
} |
| 731 |
logvr(v, r).Tag(tagAccount).Field("email", m.Email).Info("Email verified") |
| 732 |
// Refresh the verified user's other sessions. The request is unauthenticated (v.User() is |
| 733 |
// usually nil), so resolve the user from the token row and publish to their sync topic. |
| 734 |
s.publishSyncEventForUserIDAsync(v, m.UserID) |
| 735 |
return s.writeJSON(w, newSuccessResponse()) |
| 736 |
} |
| 737 |
|
| 738 |
// handleAccountEmailDelete removes an email address, whether verified or still pending |
| 739 |
// (DELETE /v1/account/email). Removing the primary leaves the account with no primary. |
| 740 |
func (s *Server) handleAccountEmailDelete(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 741 |
u := v.User() |
| 742 |
req, err := readJSONWithLimit[apiAccountEmailRequest](r.Body, jsonBodyBytesLimit, false) |
| 743 |
if err != nil { |
| 744 |
return err |
| 745 |
} else if !emailAddressRegex.MatchString(req.Email) { |
| 746 |
return errHTTPBadRequestEmailAddressInvalid |
| 747 |
} |
| 748 |
logvr(v, r).Tag(tagAccount).Field("email", req.Email).Debug("Deleting email (verified or pending)") |
| 749 |
if err := s.userManager.RemoveEmail(u.ID, req.Email); err != nil { |
| 750 |
return err |
| 751 |
} |
| 752 |
// Also drop any pending verification for the address (no-op if there is none) |
| 753 |
if err := s.userManager.DeleteEmailVerification(u.ID, req.Email); err != nil { |
| 754 |
return err |
| 755 |
} |
| 756 |
return s.writeJSON(w, newSuccessResponse()) |
| 757 |
} |
| 758 |
|
| 759 |
// handleAccountEmailSetPrimary marks an already-verified email as the user's primary (recovery) |
| 760 |
// email (POST /v1/account/email/primary). |
| 761 |
func (s *Server) handleAccountEmailSetPrimary(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 762 |
u := v.User() |
| 763 |
req, err := readJSONWithLimit[apiAccountEmailRequest](r.Body, jsonBodyBytesLimit, false) |
| 764 |
if err != nil { |
| 765 |
return err |
| 766 |
} else if !emailAddressRegex.MatchString(req.Email) { |
| 767 |
return errHTTPBadRequestEmailAddressInvalid |
| 768 |
} |
| 769 |
logvr(v, r).Tag(tagAccount).Field("email", req.Email).Info("Setting primary email") |
| 770 |
err = s.userManager.SetPrimaryEmail(u.ID, req.Email) |
| 771 |
if errors.Is(err, user.ErrEmailPrimaryElsewhere) { |
| 772 |
return errHTTPConflictEmailPrimaryElsewhere |
| 773 |
} else if errors.Is(err, user.ErrEmailNotFound) { |
| 774 |
return errHTTPBadRequestEmailAddressNotVerified |
| 775 |
} else if err != nil { |
| 776 |
return err |
| 777 |
} |
| 778 |
return s.writeJSON(w, newSuccessResponse()) |
| 779 |
} |
| 780 |
|
| 781 |
// handleAccountEmailResend re-sends a pending email verification (POST /v1/account/email/resend). |
| 782 |
func (s *Server) handleAccountEmailResend(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 783 |
u := v.User() |
| 784 |
req, err := readJSONWithLimit[apiAccountEmailRequest](r.Body, jsonBodyBytesLimit, false) |
| 785 |
if err != nil { |
| 786 |
return err |
| 787 |
} else if !emailAddressRegex.MatchString(req.Email) { |
| 788 |
return errHTTPBadRequestEmailAddressInvalid |
| 789 |
} |
| 790 |
// Only resend for an address that is actually pending on this account |
| 791 |
pending, err := s.userManager.PendingEmails(u.ID) |
| 792 |
if err != nil { |
| 793 |
return err |
| 794 |
} else if !util.Contains(pending, req.Email) { |
| 795 |
return errHTTPBadRequestEmailAddressInvalid |
| 796 |
} |
| 797 |
if !v.EmailAllowed() { |
| 798 |
return errHTTPTooManyRequestsLimitEmails |
| 799 |
} |
| 800 |
logvr(v, r).Tag(tagAccount).Field("email", req.Email).Info("Resending email verification") |
| 801 |
if err := s.enqueueEmailVerification(u.ID, req.Email); err != nil { |
| 802 |
return err |
| 803 |
} |
| 804 |
return s.writeJSON(w, newSuccessResponse()) |
| 805 |
} |
| 806 |
|
| 807 |
// enqueueEmailVerification generates a magic-link token for the given address, stores the |
| 808 |
// pending verification (replacing any existing one), and emails the link. Shared by the add, |
| 809 |
// resend, signup, and Stripe paths. Requires base-url to build an absolute link. |
| 810 |
func (s *Server) enqueueEmailVerification(userID, email string) error { |
| 811 |
if s.config.BaseURL == "" { |
| 812 |
return errHTTPInternalErrorMissingBaseURL |
| 813 |
} |
| 814 |
token, err := s.userManager.AddMagicLink(user.MagicLinkKindEmailVerify, userID, email, emailVerificationTokenExpiry) |
| 815 |
if err != nil { |
| 816 |
return err |
| 817 |
} |
| 818 |
link := s.config.BaseURL + webAppEmailVerifyPathPrefix + token |
| 819 |
return s.mailer.SendEmailVerification(email, link) |
| 820 |
} |
| 821 |
|
| 822 |
// handleAccountPasswordResetRequest starts a password reset (POST /v1/account/password/reset/request, |
| 823 |
// unauthenticated). It resolves the identifier (username or primary email) to at most one account |
| 824 |
// and emails a reset link to that account's primary email. The response is always a uniform 200, |
| 825 |
// regardless of whether anything matched, so it cannot be used to probe for accounts. |
| 826 |
func (s *Server) handleAccountPasswordResetRequest(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 827 |
req, err := readJSONWithLimit[apiAccountPasswordResetRequest](r.Body, jsonBodyBytesLimit, false) |
| 828 |
if err != nil { |
| 829 |
return err |
| 830 |
} |
| 831 |
// Rate limit via the shared per-visitor account-creation bucket (no new limiter/config) |
| 832 |
if !v.AccountActionAllowed() { |
| 833 |
return errHTTPTooManyRequestsLimitAccountActions |
| 834 |
} |
| 835 |
v.AccountActionPerformed() // Consume a token on every request (including no-match), to throttle probing |
| 836 |
identifier := strings.TrimSpace(req.Identifier) |
| 837 |
if identifier != "" && s.config.BaseURL != "" { |
| 838 |
if userID, email, ok := s.resolveResetPasswordTarget(identifier); ok { |
| 839 |
token, err := s.userManager.AddMagicLink(user.MagicLinkKindPasswordReset, userID, "", passwordResetTokenExpiry) |
| 840 |
if err != nil { |
| 841 |
logvr(v, r).Tag(tagAccount).Err(err).Warn("Failed to create password reset token") |
| 842 |
} else { |
| 843 |
link := s.config.BaseURL + webAppPasswordResetPathPrefix + token |
| 844 |
logvr(v, r).Tag(tagAccount).Field("user_id", userID).Info("Sending password reset link") |
| 845 |
if err := s.mailer.SendPasswordReset(email, link); err != nil { |
| 846 |
logvr(v, r).Tag(tagAccount).Err(err).Warn("Failed to send password reset email") |
| 847 |
} |
| 848 |
} |
| 849 |
} else { |
| 850 |
logvr(v, r).Tag(tagAccount).Debug("Password reset requested for unknown identifier (uniform response)") |
| 851 |
} |
| 852 |
} |
| 853 |
return s.writeJSON(w, newSuccessResponse()) |
| 854 |
} |
| 855 |
|
| 856 |
// resolveResetPasswordTarget resolves a reset identifier (username or primary email) to a single account |
| 857 |
// and its primary email. It applies the reset policy on top of the lookup: provisioned users are |
| 858 |
// excluded, and ok=false is returned unless the account has a verified primary email (reset |
| 859 |
// requires one, and that is where the link is sent). |
| 860 |
func (s *Server) resolveResetPasswordTarget(identifier string) (userID string, email string, ok bool) { |
| 861 |
u, err := s.userManager.UserByEmailOrUsername(identifier) |
| 862 |
if err != nil || u == nil || u.Provisioned { |
| 863 |
return "", "", false |
| 864 |
} |
| 865 |
primary, err := s.userManager.PrimaryEmail(u.ID) |
| 866 |
if err != nil || primary == "" { |
| 867 |
return "", "", false |
| 868 |
} |
| 869 |
return u.ID, primary, true |
| 870 |
} |
| 871 |
|
| 872 |
// handleAccountPasswordReset performs the reset (POST /v1/account/password/reset, unauthenticated): |
| 873 |
// it validates the token and sets the new password. Existing access tokens stay valid. |
| 874 |
func (s *Server) handleAccountPasswordReset(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 875 |
req, err := readJSONWithLimit[apiAccountPasswordResetConfirmRequest](r.Body, jsonBodyBytesLimit, false) |
| 876 |
if err != nil { |
| 877 |
return err |
| 878 |
} |
| 879 |
if req.Token == "" { |
| 880 |
return errHTTPBadRequestResetLinkInvalid |
| 881 |
} else if req.Password == "" { |
| 882 |
return errHTTPBadRequest |
| 883 |
} |
| 884 |
err = s.userManager.ResetPassword(req.Token, req.Password) |
| 885 |
if errors.Is(err, user.ErrMagicLinkNotFound) || errors.Is(err, user.ErrProvisionedUserChange) { |
| 886 |
return errHTTPBadRequestResetLinkInvalid // Generic 400 (provisioned users can't be reset; don't leak that) |
| 887 |
} else if err != nil { |
| 888 |
return err |
| 889 |
} |
| 890 |
logvr(v, r).Tag(tagAccount).Info("Password reset performed") |
| 891 |
return s.writeJSON(w, newSuccessResponse()) |
| 892 |
} |
| 893 |
|
| 894 |
// convertEmailAddress resolves the X-Email value to the address ntfy should send to. |
| 895 |
// |
| 896 |
// "yes"/"true"/"1" resolves to the user's primary verified address -- or, if no primary is |
| 897 |
// designated (e.g. a provisioned user), the first verified address (alphabetically). This is |
| 898 |
// independent of smtp-sender-verify: it only requires an authenticated user with a verified |
| 899 |
// address, since it means "send to my own email". |
| 900 |
// |
| 901 |
// A literal address is sent as-is when smtp-sender-verify is false (the default, backwards |
| 902 |
// compatible); when true, the address must be one the user has verified. |
| 903 |
func (s *Server) convertEmailAddress(u *user.User, email string) (string, *errHTTP) { |
| 904 |
if toBool(email) { |
| 905 |
if u == nil { |
| 906 |
return "", errHTTPBadRequestAnonymousEmailNotAllowed |
| 907 |
} else if s.userManager == nil { |
| 908 |
return "", errHTTPBadRequestEmailAddressNotVerified |
| 909 |
} |
| 910 |
primary, err := s.userManager.PrimaryEmail(u.ID) |
| 911 |
if err != nil { |
| 912 |
return "", errHTTPInternalError |
| 913 |
} else if primary != "" { |
| 914 |
return primary, nil |
| 915 |
} |
| 916 |
// No primary designated -> fall back to the first verified address, if any |
| 917 |
emails, err := s.userManager.Emails(u.ID) |
| 918 |
if err != nil { |
| 919 |
return "", errHTTPInternalError |
| 920 |
} else if len(emails) > 0 { |
| 921 |
return emails[0].Address, nil |
| 922 |
} |
| 923 |
return "", errHTTPBadRequestEmailAddressNotVerified |
| 924 |
} |
| 925 |
// A literal address |
| 926 |
if !s.config.SMTPSenderVerify { |
| 927 |
return email, nil |
| 928 |
} else if u == nil { |
| 929 |
return "", errHTTPBadRequestAnonymousEmailNotAllowed |
| 930 |
} else if s.userManager == nil { |
| 931 |
return email, nil |
| 932 |
} |
| 933 |
emails, err := s.userManager.Emails(u.ID) |
| 934 |
if err != nil { |
| 935 |
return "", errHTTPInternalError |
| 936 |
} else if emails.Contains(email) { |
| 937 |
return email, nil |
| 938 |
} |
| 939 |
return "", errHTTPBadRequestEmailAddressNotVerified |
| 940 |
} |
| 941 |
|
| 942 |
// publishSyncEventAsync kicks of a Go routine to publish a sync message to the user's sync topic |
| 943 |
func (s *Server) publishSyncEventAsync(v *visitor) { |
| 944 |
go func() { |
| 945 |
if err := s.publishSyncEvent(v); err != nil { |
| 946 |
logv(v).Err(err).Trace("Error publishing to user's sync topic") |
| 947 |
} |
| 948 |
}() |
| 949 |
} |
| 950 |
|
| 951 |
// publishSyncEvent publishes a sync message to the authenticated user's sync topic |
| 952 |
func (s *Server) publishSyncEvent(v *visitor) error { |
| 953 |
return s.publishSyncEventForUser(v, v.User()) |
| 954 |
} |
| 955 |
|
| 956 |
// publishSyncEventForUserIDAsync publishes a sync event to the sync topic of the user with the |
| 957 |
// given ID, resolving the user first. Used by the unauthenticated email-verify handler, where |
| 958 |
// the request visitor has no associated user but the token identifies the account to refresh. |
| 959 |
func (s *Server) publishSyncEventForUserIDAsync(v *visitor, userID string) { |
| 960 |
go func() { |
| 961 |
u, err := s.userManager.UserByID(userID) |
| 962 |
if err != nil { |
| 963 |
logv(v).Err(err).Trace("Error loading user for sync event") |
| 964 |
return |
| 965 |
} |
| 966 |
if err := s.publishSyncEventForUser(v, u); err != nil { |
| 967 |
logv(v).Err(err).Trace("Error publishing to user's sync topic") |
| 968 |
} |
| 969 |
}() |
| 970 |
} |
| 971 |
|
| 972 |
// publishSyncEventForUser publishes a sync message to the given user's sync topic, using v as |
| 973 |
// the publishing visitor (for rate-limit accounting). No-op if the user has no sync topic. |
| 974 |
func (s *Server) publishSyncEventForUser(v *visitor, u *user.User) error { |
| 975 |
if u == nil || u.SyncTopic == "" { |
| 976 |
return nil |
| 977 |
} |
| 978 |
logv(v).Field("sync_topic", u.SyncTopic).Trace("Publishing sync event to user's sync topic") |
| 979 |
syncTopic, err := s.topicFromID(nil, u.SyncTopic) // internal: no rate limit |
| 980 |
if err != nil { |
| 981 |
return err |
| 982 |
} |
| 983 |
messageBytes, err := json.Marshal(&apiAccountSyncTopicResponse{Event: syncTopicAccountSyncEvent}) |
| 984 |
if err != nil { |
| 985 |
return err |
| 986 |
} |
| 987 |
m := model.NewDefaultMessage(syncTopic.ID, string(messageBytes)) |
| 988 |
if err := s.dispatch(v, syncTopic, m, dispatchOpts{}); err != nil { |
| 989 |
return err |
| 990 |
} |
| 991 |
return nil |
| 992 |
} |