| 1 |
import i18n from "i18next"; |
| 2 |
import { |
| 3 |
accountBillingPortalUrl, |
| 4 |
accountBillingSubscriptionUrl, |
| 5 |
accountEmailUrl, |
| 6 |
accountEmailVerifyUrl, |
| 7 |
accountEmailPrimaryUrl, |
| 8 |
accountEmailResendUrl, |
| 9 |
accountLoginUrl, |
| 10 |
accountPasswordResetRequestUrl, |
| 11 |
accountPasswordResetUrl, |
| 12 |
accountPasswordUrl, |
| 13 |
accountPhoneUrl, |
| 14 |
accountPhoneVerifyUrl, |
| 15 |
accountReservationSingleUrl, |
| 16 |
accountReservationUrl, |
| 17 |
accountSettingsUrl, |
| 18 |
accountSubscriptionUrl, |
| 19 |
accountTokenUrl, |
| 20 |
accountUrl, |
| 21 |
maybeWithBearerAuth, |
| 22 |
tiersUrl, |
| 23 |
withBasicAuth, |
| 24 |
withBearerAuth, |
| 25 |
} from "./utils"; |
| 26 |
import session from "./Session"; |
| 27 |
import subscriptionManager from "./SubscriptionManager"; |
| 28 |
import prefs from "./Prefs"; |
| 29 |
import routes from "../components/routes"; |
| 30 |
import { fetchOrThrow, UnauthorizedError } from "./errors"; |
| 31 |
|
| 32 |
const delayMillis = 45000; // 45 seconds |
| 33 |
const intervalMillis = 900000; // 15 minutes |
| 34 |
|
| 35 |
class AccountApi { |
| 36 |
constructor() { |
| 37 |
this.timer = null; |
| 38 |
this.listener = null; // Fired when account is fetched from remote |
| 39 |
this.tiers = null; // Cached |
| 40 |
} |
| 41 |
|
| 42 |
registerListener(listener) { |
| 43 |
this.listener = listener; |
| 44 |
} |
| 45 |
|
| 46 |
resetListener() { |
| 47 |
this.listener = null; |
| 48 |
} |
| 49 |
|
| 50 |
async login(user) { |
| 51 |
const url = accountLoginUrl(config.base_url); |
| 52 |
console.log(`[AccountApi] Logging in at ${url}`); |
| 53 |
const response = await fetchOrThrow(url, { |
| 54 |
method: "POST", |
| 55 |
headers: withBasicAuth({}, user.username, user.password), |
| 56 |
}); |
| 57 |
const json = await response.json(); // May throw SyntaxError |
| 58 |
if (!json.token) { |
| 59 |
throw new Error(`Unexpected server response: Cannot find token`); |
| 60 |
} |
| 61 |
// The identifier the user typed may be a primary email; login returns the canonical username |
| 62 |
// so callers can store it and show the real username rather than whatever was typed. Fall back |
| 63 |
// to the typed identifier if an older server omits the username, so the session still stores one. |
| 64 |
return { token: json.token, username: json.username || user.username }; |
| 65 |
} |
| 66 |
|
| 67 |
async logout() { |
| 68 |
const url = accountTokenUrl(config.base_url); |
| 69 |
console.log(`[AccountApi] Logging out from ${url} using token ${session.token()}`); |
| 70 |
await fetchOrThrow(url, { |
| 71 |
method: "DELETE", |
| 72 |
headers: withBearerAuth({}, session.token()), |
| 73 |
}); |
| 74 |
} |
| 75 |
|
| 76 |
async create(username, password, email) { |
| 77 |
const url = accountUrl(config.base_url); |
| 78 |
const body = JSON.stringify({ |
| 79 |
username, |
| 80 |
password, |
| 81 |
email: email || "", |
| 82 |
}); |
| 83 |
console.log(`[AccountApi] Creating user account ${url}`); |
| 84 |
await fetchOrThrow(url, { |
| 85 |
method: "POST", |
| 86 |
body, |
| 87 |
}); |
| 88 |
} |
| 89 |
|
| 90 |
async get() { |
| 91 |
const url = accountUrl(config.base_url); |
| 92 |
console.log(`[AccountApi] Fetching user account ${url}`); |
| 93 |
const response = await fetchOrThrow(url, { |
| 94 |
headers: maybeWithBearerAuth({}, session.token()), // GET /v1/account endpoint can be called by anonymous |
| 95 |
}); |
| 96 |
const account = await response.json(); // May throw SyntaxError |
| 97 |
console.log(`[AccountApi] Account`, account); |
| 98 |
if (this.listener) { |
| 99 |
this.listener(account); |
| 100 |
} |
| 101 |
return account; |
| 102 |
} |
| 103 |
|
| 104 |
async delete(password) { |
| 105 |
const url = accountUrl(config.base_url); |
| 106 |
console.log(`[AccountApi] Deleting user account ${url}`); |
| 107 |
await fetchOrThrow(url, { |
| 108 |
method: "DELETE", |
| 109 |
headers: withBearerAuth({}, session.token()), |
| 110 |
body: JSON.stringify({ |
| 111 |
password, |
| 112 |
}), |
| 113 |
}); |
| 114 |
} |
| 115 |
|
| 116 |
async changePassword(currentPassword, newPassword) { |
| 117 |
const url = accountPasswordUrl(config.base_url); |
| 118 |
console.log(`[AccountApi] Changing account password ${url}`); |
| 119 |
await fetchOrThrow(url, { |
| 120 |
method: "POST", |
| 121 |
headers: withBearerAuth({}, session.token()), |
| 122 |
body: JSON.stringify({ |
| 123 |
password: currentPassword, |
| 124 |
new_password: newPassword, |
| 125 |
}), |
| 126 |
}); |
| 127 |
} |
| 128 |
|
| 129 |
async createToken(label, expires) { |
| 130 |
const url = accountTokenUrl(config.base_url); |
| 131 |
const body = { |
| 132 |
label, |
| 133 |
expires: expires > 0 ? Math.floor(Date.now() / 1000) + expires : 0, |
| 134 |
}; |
| 135 |
console.log(`[AccountApi] Creating user access token ${url}`); |
| 136 |
await fetchOrThrow(url, { |
| 137 |
method: "POST", |
| 138 |
headers: withBearerAuth({}, session.token()), |
| 139 |
body: JSON.stringify(body), |
| 140 |
}); |
| 141 |
} |
| 142 |
|
| 143 |
async updateToken(token, label, expires) { |
| 144 |
const url = accountTokenUrl(config.base_url); |
| 145 |
const body = { |
| 146 |
token, |
| 147 |
label, |
| 148 |
}; |
| 149 |
if (expires >= 0) { |
| 150 |
body.expires = expires > 0 ? Math.floor(Date.now() / 1000) + expires : 0; |
| 151 |
} |
| 152 |
console.log(`[AccountApi] Creating user access token ${url}`); |
| 153 |
await fetchOrThrow(url, { |
| 154 |
method: "PATCH", |
| 155 |
headers: withBearerAuth({}, session.token()), |
| 156 |
body: JSON.stringify(body), |
| 157 |
}); |
| 158 |
} |
| 159 |
|
| 160 |
async extendToken() { |
| 161 |
const url = accountTokenUrl(config.base_url); |
| 162 |
console.log(`[AccountApi] Extending user access token ${url}`); |
| 163 |
await fetchOrThrow(url, { |
| 164 |
method: "PATCH", |
| 165 |
headers: withBearerAuth({}, session.token()), |
| 166 |
}); |
| 167 |
await session.setLastExtendedAtAsync(); |
| 168 |
} |
| 169 |
|
| 170 |
async deleteToken(token) { |
| 171 |
const url = accountTokenUrl(config.base_url); |
| 172 |
console.log(`[AccountApi] Deleting user access token ${url}`); |
| 173 |
await fetchOrThrow(url, { |
| 174 |
method: "DELETE", |
| 175 |
headers: withBearerAuth({ "X-Token": token }, session.token()), |
| 176 |
}); |
| 177 |
} |
| 178 |
|
| 179 |
async updateSettings(payload) { |
| 180 |
const url = accountSettingsUrl(config.base_url); |
| 181 |
const body = JSON.stringify(payload); |
| 182 |
console.log(`[AccountApi] Updating user account ${url}: ${body}`); |
| 183 |
await fetchOrThrow(url, { |
| 184 |
method: "PATCH", |
| 185 |
headers: withBearerAuth({}, session.token()), |
| 186 |
body, |
| 187 |
}); |
| 188 |
} |
| 189 |
|
| 190 |
async addSubscription(baseUrl, topic) { |
| 191 |
const url = accountSubscriptionUrl(config.base_url); |
| 192 |
const body = JSON.stringify({ |
| 193 |
base_url: baseUrl, |
| 194 |
topic, |
| 195 |
}); |
| 196 |
console.log(`[AccountApi] Adding user subscription ${url}: ${body}`); |
| 197 |
const response = await fetchOrThrow(url, { |
| 198 |
method: "POST", |
| 199 |
headers: withBearerAuth({}, session.token()), |
| 200 |
body, |
| 201 |
}); |
| 202 |
const subscription = await response.json(); // May throw SyntaxError |
| 203 |
console.log(`[AccountApi] Subscription`, subscription); |
| 204 |
return subscription; |
| 205 |
} |
| 206 |
|
| 207 |
async updateSubscription(baseUrl, topic, payload) { |
| 208 |
const url = accountSubscriptionUrl(config.base_url); |
| 209 |
const body = JSON.stringify({ |
| 210 |
base_url: baseUrl, |
| 211 |
topic, |
| 212 |
...payload, |
| 213 |
}); |
| 214 |
console.log(`[AccountApi] Updating user subscription ${url}: ${body}`); |
| 215 |
const response = await fetchOrThrow(url, { |
| 216 |
method: "PATCH", |
| 217 |
headers: withBearerAuth({}, session.token()), |
| 218 |
body, |
| 219 |
}); |
| 220 |
const subscription = await response.json(); // May throw SyntaxError |
| 221 |
console.log(`[AccountApi] Subscription`, subscription); |
| 222 |
return subscription; |
| 223 |
} |
| 224 |
|
| 225 |
async deleteSubscription(baseUrl, topic) { |
| 226 |
const url = accountSubscriptionUrl(config.base_url); |
| 227 |
console.log(`[AccountApi] Removing user subscription ${url}`); |
| 228 |
const headers = { |
| 229 |
"X-BaseURL": baseUrl, |
| 230 |
"X-Topic": topic, |
| 231 |
}; |
| 232 |
await fetchOrThrow(url, { |
| 233 |
method: "DELETE", |
| 234 |
headers: withBearerAuth(headers, session.token()), |
| 235 |
}); |
| 236 |
} |
| 237 |
|
| 238 |
async upsertReservation(topic, everyone) { |
| 239 |
const url = accountReservationUrl(config.base_url); |
| 240 |
console.log(`[AccountApi] Upserting user access to topic ${topic}, everyone=${everyone}`); |
| 241 |
await fetchOrThrow(url, { |
| 242 |
method: "POST", |
| 243 |
headers: withBearerAuth({}, session.token()), |
| 244 |
body: JSON.stringify({ |
| 245 |
topic, |
| 246 |
everyone, |
| 247 |
}), |
| 248 |
}); |
| 249 |
} |
| 250 |
|
| 251 |
async deleteReservation(topic, deleteMessages) { |
| 252 |
const url = accountReservationSingleUrl(config.base_url, topic); |
| 253 |
console.log(`[AccountApi] Removing topic reservation ${url}`); |
| 254 |
const headers = { |
| 255 |
"X-Delete-Messages": deleteMessages ? "true" : "false", |
| 256 |
}; |
| 257 |
await fetchOrThrow(url, { |
| 258 |
method: "DELETE", |
| 259 |
headers: withBearerAuth(headers, session.token()), |
| 260 |
}); |
| 261 |
} |
| 262 |
|
| 263 |
async billingTiers() { |
| 264 |
if (this.tiers) { |
| 265 |
return this.tiers; |
| 266 |
} |
| 267 |
const url = tiersUrl(config.base_url); |
| 268 |
console.log(`[AccountApi] Fetching billing tiers`); |
| 269 |
const response = await fetchOrThrow(url); // No auth needed! |
| 270 |
this.tiers = await response.json(); // May throw SyntaxError |
| 271 |
return this.tiers; |
| 272 |
} |
| 273 |
|
| 274 |
async createBillingSubscription(tier, interval) { |
| 275 |
console.log(`[AccountApi] Creating billing subscription with ${tier} and interval ${interval}`); |
| 276 |
return this.upsertBillingSubscription("POST", tier, interval); |
| 277 |
} |
| 278 |
|
| 279 |
async updateBillingSubscription(tier, interval) { |
| 280 |
console.log(`[AccountApi] Updating billing subscription with ${tier} and interval ${interval}`); |
| 281 |
return this.upsertBillingSubscription("PUT", tier, interval); |
| 282 |
} |
| 283 |
|
| 284 |
async upsertBillingSubscription(method, tier, interval) { |
| 285 |
const url = accountBillingSubscriptionUrl(config.base_url); |
| 286 |
const response = await fetchOrThrow(url, { |
| 287 |
method, |
| 288 |
headers: withBearerAuth({}, session.token()), |
| 289 |
body: JSON.stringify({ |
| 290 |
tier, |
| 291 |
interval, |
| 292 |
}), |
| 293 |
}); |
| 294 |
return response.json(); // May throw SyntaxError |
| 295 |
} |
| 296 |
|
| 297 |
async deleteBillingSubscription() { |
| 298 |
const url = accountBillingSubscriptionUrl(config.base_url); |
| 299 |
console.log(`[AccountApi] Cancelling billing subscription`); |
| 300 |
await fetchOrThrow(url, { |
| 301 |
method: "DELETE", |
| 302 |
headers: withBearerAuth({}, session.token()), |
| 303 |
}); |
| 304 |
} |
| 305 |
|
| 306 |
async createBillingPortalSession() { |
| 307 |
const url = accountBillingPortalUrl(config.base_url); |
| 308 |
console.log(`[AccountApi] Creating billing portal session`); |
| 309 |
const response = await fetchOrThrow(url, { |
| 310 |
method: "POST", |
| 311 |
headers: withBearerAuth({}, session.token()), |
| 312 |
}); |
| 313 |
return response.json(); // May throw SyntaxError |
| 314 |
} |
| 315 |
|
| 316 |
async verifyPhoneNumber(phoneNumber, channel) { |
| 317 |
const url = accountPhoneVerifyUrl(config.base_url); |
| 318 |
console.log(`[AccountApi] Sending phone verification ${url}`); |
| 319 |
await fetchOrThrow(url, { |
| 320 |
method: "PUT", |
| 321 |
headers: withBearerAuth({}, session.token()), |
| 322 |
body: JSON.stringify({ |
| 323 |
number: phoneNumber, |
| 324 |
channel, |
| 325 |
}), |
| 326 |
}); |
| 327 |
} |
| 328 |
|
| 329 |
async addPhoneNumber(phoneNumber, code) { |
| 330 |
const url = accountPhoneUrl(config.base_url); |
| 331 |
console.log(`[AccountApi] Adding phone number with verification code ${url}`); |
| 332 |
await fetchOrThrow(url, { |
| 333 |
method: "PUT", |
| 334 |
headers: withBearerAuth({}, session.token()), |
| 335 |
body: JSON.stringify({ |
| 336 |
number: phoneNumber, |
| 337 |
code, |
| 338 |
}), |
| 339 |
}); |
| 340 |
} |
| 341 |
|
| 342 |
async deletePhoneNumber(phoneNumber) { |
| 343 |
const url = accountPhoneUrl(config.base_url); |
| 344 |
console.log(`[AccountApi] Deleting phone number ${url}`); |
| 345 |
await fetchOrThrow(url, { |
| 346 |
method: "DELETE", |
| 347 |
headers: withBearerAuth({}, session.token()), |
| 348 |
body: JSON.stringify({ |
| 349 |
number: phoneNumber, |
| 350 |
}), |
| 351 |
}); |
| 352 |
} |
| 353 |
|
| 354 |
// startEmailVerification begins adding an email: the server stores a pending verification and |
| 355 |
// emails a magic link. The address is not verified until the link is clicked. |
| 356 |
async startEmailVerification(email) { |
| 357 |
const url = accountEmailUrl(config.base_url); |
| 358 |
console.log(`[AccountApi] Starting email verification ${url}`); |
| 359 |
await fetchOrThrow(url, { |
| 360 |
method: "PUT", |
| 361 |
headers: withBearerAuth({}, session.token()), |
| 362 |
body: JSON.stringify({ |
| 363 |
email, |
| 364 |
}), |
| 365 |
}); |
| 366 |
} |
| 367 |
|
| 368 |
// verifyEmailToken performs verification from the magic-link landing page. It is unauthenticated: |
| 369 |
// the token identifies the account, so this works even when clicked from a logged-out browser. |
| 370 |
async verifyEmailToken(token) { |
| 371 |
const url = accountEmailVerifyUrl(config.base_url); |
| 372 |
console.log(`[AccountApi] Verifying email token ${url}`); |
| 373 |
await fetchOrThrow(url, { |
| 374 |
method: "POST", |
| 375 |
body: JSON.stringify({ |
| 376 |
token, |
| 377 |
}), |
| 378 |
}); |
| 379 |
} |
| 380 |
|
| 381 |
// resendEmailVerification re-sends the magic link for a pending (unverified) address. |
| 382 |
async resendEmailVerification(email) { |
| 383 |
const url = accountEmailResendUrl(config.base_url); |
| 384 |
console.log(`[AccountApi] Resending email verification ${url}`); |
| 385 |
await fetchOrThrow(url, { |
| 386 |
method: "POST", |
| 387 |
headers: withBearerAuth({}, session.token()), |
| 388 |
body: JSON.stringify({ |
| 389 |
email, |
| 390 |
}), |
| 391 |
}); |
| 392 |
} |
| 393 |
|
| 394 |
// setPrimaryEmail marks an already-verified address as the primary (recovery) email. |
| 395 |
async setPrimaryEmail(email) { |
| 396 |
const url = accountEmailPrimaryUrl(config.base_url); |
| 397 |
console.log(`[AccountApi] Setting primary email ${url}`); |
| 398 |
await fetchOrThrow(url, { |
| 399 |
method: "POST", |
| 400 |
headers: withBearerAuth({}, session.token()), |
| 401 |
body: JSON.stringify({ |
| 402 |
email, |
| 403 |
}), |
| 404 |
}); |
| 405 |
} |
| 406 |
|
| 407 |
// requestPasswordReset starts the (unauthenticated) reset flow. The identifier is a username or |
| 408 |
// primary email. The server always responds uniformly, regardless of whether an account matched. |
| 409 |
async requestPasswordReset(identifier) { |
| 410 |
const url = accountPasswordResetRequestUrl(config.base_url); |
| 411 |
console.log(`[AccountApi] Requesting password reset ${url}`); |
| 412 |
await fetchOrThrow(url, { |
| 413 |
method: "POST", |
| 414 |
body: JSON.stringify({ |
| 415 |
identifier, |
| 416 |
}), |
| 417 |
}); |
| 418 |
} |
| 419 |
|
| 420 |
// resetPassword performs the (unauthenticated) reset from the set-new-password landing page. |
| 421 |
async resetPassword(token, password) { |
| 422 |
const url = accountPasswordResetUrl(config.base_url); |
| 423 |
console.log(`[AccountApi] Resetting password ${url}`); |
| 424 |
await fetchOrThrow(url, { |
| 425 |
method: "POST", |
| 426 |
body: JSON.stringify({ |
| 427 |
token, |
| 428 |
password, |
| 429 |
}), |
| 430 |
}); |
| 431 |
} |
| 432 |
|
| 433 |
async deleteEmail(email) { |
| 434 |
const url = accountEmailUrl(config.base_url); |
| 435 |
console.log(`[AccountApi] Deleting email ${url}`); |
| 436 |
await fetchOrThrow(url, { |
| 437 |
method: "DELETE", |
| 438 |
headers: withBearerAuth({}, session.token()), |
| 439 |
body: JSON.stringify({ |
| 440 |
email, |
| 441 |
}), |
| 442 |
}); |
| 443 |
} |
| 444 |
|
| 445 |
async sync() { |
| 446 |
try { |
| 447 |
if (!session.token()) { |
| 448 |
return null; |
| 449 |
} |
| 450 |
console.log(`[AccountApi] Syncing account`); |
| 451 |
const account = await this.get(); |
| 452 |
if (account.language) { |
| 453 |
await i18n.changeLanguage(account.language); |
| 454 |
} |
| 455 |
if (account.date_format) { |
| 456 |
await prefs.setDateFormat(account.date_format); |
| 457 |
} |
| 458 |
if (account.time_format) { |
| 459 |
await prefs.setTimeFormat(account.time_format); |
| 460 |
} |
| 461 |
if (account.notification) { |
| 462 |
if (account.notification.sound) { |
| 463 |
await prefs.setSound(account.notification.sound); |
| 464 |
} |
| 465 |
if (account.notification.delete_after) { |
| 466 |
await prefs.setDeleteAfter(account.notification.delete_after); |
| 467 |
} |
| 468 |
if (account.notification.min_priority) { |
| 469 |
await prefs.setMinPriority(account.notification.min_priority); |
| 470 |
} |
| 471 |
} |
| 472 |
if (account.subscriptions) { |
| 473 |
await subscriptionManager.syncFromRemote(account.subscriptions, account.reservations); |
| 474 |
} |
| 475 |
return account; |
| 476 |
} catch (e) { |
| 477 |
console.log(`[AccountApi] Error fetching account`, e); |
| 478 |
if (e instanceof UnauthorizedError) { |
| 479 |
await session.resetAndRedirect(routes.login); |
| 480 |
} |
| 481 |
return undefined; |
| 482 |
} |
| 483 |
} |
| 484 |
|
| 485 |
startWorker() { |
| 486 |
if (this.timer !== null) { |
| 487 |
return; |
| 488 |
} |
| 489 |
console.log(`[AccountApi] Starting worker`); |
| 490 |
this.timer = setInterval(() => this.runWorker(), intervalMillis); |
| 491 |
setTimeout(() => this.runWorker(), delayMillis); |
| 492 |
} |
| 493 |
|
| 494 |
stopWorker() { |
| 495 |
clearTimeout(this.timer); |
| 496 |
} |
| 497 |
|
| 498 |
async runWorker() { |
| 499 |
if (!session.token()) { |
| 500 |
return; |
| 501 |
} |
| 502 |
console.log(`[AccountApi] Extending user access token`); |
| 503 |
try { |
| 504 |
await this.extendToken(); |
| 505 |
} catch (e) { |
| 506 |
console.log(`[AccountApi] Error extending user access token`, e); |
| 507 |
} |
| 508 |
} |
| 509 |
} |
| 510 |
|
| 511 |
// Maps to user.Role in user/types.go |
| 512 |
export const Role = { |
| 513 |
ADMIN: "admin", |
| 514 |
USER: "user", |
| 515 |
}; |
| 516 |
|
| 517 |
// Maps to server.visitorLimitBasis in server/visitor.go |
| 518 |
export const LimitBasis = { |
| 519 |
IP: "ip", |
| 520 |
TIER: "tier", |
| 521 |
}; |
| 522 |
|
| 523 |
// Maps to stripe.SubscriptionStatus |
| 524 |
export const SubscriptionStatus = { |
| 525 |
ACTIVE: "active", |
| 526 |
PAST_DUE: "past_due", |
| 527 |
}; |
| 528 |
|
| 529 |
// Maps to stripe.PriceRecurringInterval |
| 530 |
export const SubscriptionInterval = { |
| 531 |
MONTH: "month", |
| 532 |
YEAR: "year", |
| 533 |
}; |
| 534 |
|
| 535 |
// Maps to user.Permission in user/types.go |
| 536 |
export const Permission = { |
| 537 |
READ_WRITE: "read-write", |
| 538 |
READ_ONLY: "read-only", |
| 539 |
WRITE_ONLY: "write-only", |
| 540 |
DENY_ALL: "deny-all", |
| 541 |
}; |
| 542 |
|
| 543 |
const accountApi = new AccountApi(); |
| 544 |
export default accountApi; |