stacker.news/pages/settings/index.js

1135 lines
40 KiB
JavaScript
Raw Normal View History

import { Checkbox, Form, Input, SubmitButton, Select, VariableInput, CopyInput } from '@/components/form'
2023-07-24 18:35:05 +00:00
import Alert from 'react-bootstrap/Alert'
import Button from 'react-bootstrap/Button'
import InputGroup from 'react-bootstrap/InputGroup'
import Nav from 'react-bootstrap/Nav'
import Layout from '@/components/layout'
import { useState, useMemo } from 'react'
2022-06-02 22:55:23 +00:00
import { gql, useMutation, useQuery } from '@apollo/client'
import { getGetServerSideProps } from '@/api/ssrApollo'
import LoginButton from '@/components/login-button'
import { signIn } from 'next-auth/react'
import { LightningAuth } from '@/components/lightning-auth'
import { SETTINGS, SET_SETTINGS } from '@/fragments/users'
2022-06-02 22:55:23 +00:00
import { useRouter } from 'next/router'
import Info from '@/components/info'
2022-12-01 21:31:04 +00:00
import Link from 'next/link'
import AccordianItem from '@/components/accordian-item'
2023-02-01 15:54:08 +00:00
import { bech32 } from 'bech32'
import { NOSTR_MAX_RELAY_NUM, NOSTR_PUBKEY_BECH32, DEFAULT_CROSSPOSTING_RELAYS } from '@/lib/nostr'
import { emailSchema, lastAuthRemovalSchema, settingsSchema } from '@/lib/validate'
import { SUPPORTED_CURRENCIES } from '@/lib/currency'
import PageLoading from '@/components/page-loading'
import { useShowModal } from '@/components/modal'
import { authErrorMessage } from '@/components/login'
import { NostrAuth } from '@/components/nostr-auth'
import { useToast } from '@/components/toast'
Wallet Logs (#994) * nwc wallet logs * persist logs in IndexedDB * Potential fix for empty error message * load logs limited to 5m ago from IDB * load logs from past via query param * Add 5m, 1h, 6h links for earlier logs * Show end of log * Clamp to logStart * Add log.module.css * Remove TODO about persistence * Use table for logs * <table> fixes bad format with fixed width and message overflow into start of next row * also using ---start of log--- instead of ---end of log--- now * removed time string in header nav * Rename .header to .logNav * Simply load all logs and remove navigation I realized the code for navigation was most likely premature optimization which even resulted in worse UX: Using the buttons to load logs from 5m, 1h, 6h ago sometimes meant that nothing happened at all since there were no logs from 5m, 1h, 6h ago. That's why I added a time string as "start of logs" so it's at least visible that it changed but that looked bad so I removed it. But all of this was not necessary: I can simply load all logs at once and then the user can scroll around however they like. I was worried that it would be bad for performance to load all logs at once since we might store a lot of logs but as mentioned, that's probably premature optimization. WHEN a lot of logs are stored AND this becomes a problem (What problem even? Slow page load?), THEN we can think about this. If page load ever becomes slow because of loading logs, we could probably simply not load the logs at page load but only when /wallet/logs is visited. But for now, this works fine. * Add follow checkbox * Create WalletLogs component * Embed wallet logs * Remove test error * Fix level padding * Add LNbits logs * Add logs for attaching LND and lnAddr * Use err.message || err.toString?.() consistently * Autowithdrawal logs * Use details from LND error * Don't log test invoice individually * Also refetch logs on error * Remove obsolete and annoying toasts * Replace scrollIntoView with scroll * Use constant embedded max-height * Fix missing width: 100% for embedded logs * Show full payment hash and preimage in logs * Also parse details from LND errors on autowithdrawal failures * Remove TODO * Fix accidental removal of wss:// check * Fix alignment of start marker and show empty if empty * Fix sendPayment loop * Split context in two
2024-04-03 22:27:21 +00:00
import { useServiceWorkerLogger } from '@/components/logger'
import { useMe } from '@/components/me'
Frontend payment UX cleanup (#1194) * Replace useInvoiceable with usePayment hook * Show WebLnError in QR code fallback * Fix missing removal of old zap undo code * Fix payment timeout message * Fix unused arg in super() * Also bail if invoice expired * Fix revert on reply error * Use JIT_INVOICE_TIMEOUT_MS constant * Remove unnecessary PaymentContext * Fix me as a dependency in FeeButtonContext * Fix anon sats added before act success * Optimistic updates for zaps * Fix modal not closed after custom zap * Optimistic update for custom zaps * Optimistic update for bounty payments * Consistent error handling for zaps and bounty payments * Optimistic update for poll votes * Use var balance in payment.request * Rename invoiceable to prepaid * Log cancelled invoices * Client notifications We now show notifications that are stored on the client to inform the user about following errors in the prepaid payment flow: - if a payment fails - if an invoice expires before it is paid - if a payment was interrupted (for example via page refresh) - if the action fails after payment * Remove unnecessary passing of act * Use AbortController for zap undos * Fix anon zap update not updating bolt color * Fix zap counted towards anon sats even if logged in * Fix duplicate onComplete call * Fix downzap type error * Fix "missing field 'path' while writing result" error * Pass full item in downzap props The previous commit fixed cache updates for downzaps but then the cache update for custom zaps failed because 'path' wasn't included in the server response. This commit is the proper fix. * Parse lnc rpc error messages * Add hash to InvoiceExpiredError
2024-05-28 17:18:54 +00:00
import { INVOICE_RETENTION_DAYS, ZAP_UNDO_DELAY_MS } from '@/lib/constants'
import { OverlayTrigger, Tooltip } from 'react-bootstrap'
2024-03-25 00:46:12 +00:00
import { useField } from 'formik'
import styles from './settings.module.css'
import { AuthBanner } from '@/components/banners'
2022-04-21 22:50:02 +00:00
export const getServerSideProps = getGetServerSideProps({ query: SETTINGS, authRequired: true })
2021-10-30 16:20:11 +00:00
2023-02-01 15:54:08 +00:00
function bech32encode (hexString) {
return bech32.encode('npub', bech32.toWords(Buffer.from(hexString, 'hex')))
}
// sort to prevent hydration mismatch
const getProviders = (authMethods) =>
Object.keys(authMethods).filter(k => k !== '__typename' && k !== 'apiKey').sort()
// Show alert message if user only has one auth method activated
// as users are losing access to their accounts
const hasOnlyOneAuthMethod = (authMethods) => {
const activatedAuths = getProviders(authMethods)
.filter(provider => !!authMethods[provider])
return activatedAuths.length === 1
}
export function SettingsHeader () {
const router = useRouter()
const pathParts = router.asPath.split('/').filter(segment => !!segment)
const activeKey = pathParts[1] ?? 'general'
return (
<>
<h2 className='mb-2 text-start'>settings</h2>
<Nav
className={styles.nav}
activeKey={activeKey}
>
<Nav.Item>
<Link href='/settings' passHref legacyBehavior>
<Nav.Link eventKey='general'>general</Nav.Link>
</Link>
</Nav.Item>
<Nav.Item>
<Link href='/settings/subscriptions' passHref legacyBehavior>
<Nav.Link eventKey='subscriptions'>subscriptions</Nav.Link>
</Link>
</Nav.Item>
<Nav.Item>
<Link href='/settings/mutes' passHref legacyBehavior>
<Nav.Link eventKey='mutes'>muted stackers</Nav.Link>
</Link>
</Nav.Item>
</Nav>
</>
)
}
export default function Settings ({ ssrData }) {
const toaster = useToast()
Account Switching (#644) * WIP: Account switching * Fix empty USER query ANON_USER_ID was undefined and thus the query for @anon had no variables. * Apply multiAuthMiddleware in /api/graphql * Fix 'you must be logged in' query error on switch to anon * Add smart 'switch account' button "smart" means that it only shows if there are accounts to which one can switch * Fix multiAuth not set in backend * Comment fixes, minor changes * Use fw-bold instead of 'selected' * Close dropdown and offcanvas Inside a dropdown, we can rely on autoClose but need to wrap the buttons with <Dropdown.Item> for that to work. For the offcanvas, we need to pass down handleClose. * Use button to add account * Some pages require hard reload on account switch * Reinit settings form on account switch * Also don't refetch WalletHistory * Formatting * Use width: fit-content for standalone SignUpButton * Remove unused className * Use fw-bold and text-underline on selected * Fix inconsistent padding of login buttons * Fix duplicate redirect from /settings on anon switch * Never throw during refetch * Throw errors which extend GraphQLError * Only use meAnonSats if logged out * Use reactive variable for meAnonSats The previous commit broke the UI update after anon zaps because we actually updated item.meSats in the cache and not item.meAnonSats. Updating item.meAnonSats was not possible because it's a local field. For that, one needs to use reactive variables. We do this now and thus also don't need the useEffect hack in item-info.js anymore. * Switch to new user * Fix missing cleanup during logout If we logged in but never switched to any other account, the 'multi_auth.user-id' cookie was not set. This meant that during logout, the other 'multi_auth.*' cookies were not deleted. This broke the account switch modal. This is fixed by setting the 'multi_auth.user-id' cookie on login. Additionally, we now cleanup if cookie pointer OR session is set (instead of only if both are set). * Fix comments in middleware * Remove unnecessary effect dependencies setState is stable and thus only noise in effect dependencies * Show but disable unavailable auth methods * make signup button consistent with others * Always reload page on switch * refine account switch styling * logout barrier --------- Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com> Co-authored-by: k00b <k00b@stacker.news>
2024-09-12 18:05:11 +00:00
const { me } = useMe()
const [setSettings] = useMutation(SET_SETTINGS, {
update (cache, { data: { setSettings } }) {
cache.modify({
id: 'ROOT_QUERY',
fields: {
settings () {
return setSettings
}
}
})
}
Account Switching (#644) * WIP: Account switching * Fix empty USER query ANON_USER_ID was undefined and thus the query for @anon had no variables. * Apply multiAuthMiddleware in /api/graphql * Fix 'you must be logged in' query error on switch to anon * Add smart 'switch account' button "smart" means that it only shows if there are accounts to which one can switch * Fix multiAuth not set in backend * Comment fixes, minor changes * Use fw-bold instead of 'selected' * Close dropdown and offcanvas Inside a dropdown, we can rely on autoClose but need to wrap the buttons with <Dropdown.Item> for that to work. For the offcanvas, we need to pass down handleClose. * Use button to add account * Some pages require hard reload on account switch * Reinit settings form on account switch * Also don't refetch WalletHistory * Formatting * Use width: fit-content for standalone SignUpButton * Remove unused className * Use fw-bold and text-underline on selected * Fix inconsistent padding of login buttons * Fix duplicate redirect from /settings on anon switch * Never throw during refetch * Throw errors which extend GraphQLError * Only use meAnonSats if logged out * Use reactive variable for meAnonSats The previous commit broke the UI update after anon zaps because we actually updated item.meSats in the cache and not item.meAnonSats. Updating item.meAnonSats was not possible because it's a local field. For that, one needs to use reactive variables. We do this now and thus also don't need the useEffect hack in item-info.js anymore. * Switch to new user * Fix missing cleanup during logout If we logged in but never switched to any other account, the 'multi_auth.user-id' cookie was not set. This meant that during logout, the other 'multi_auth.*' cookies were not deleted. This broke the account switch modal. This is fixed by setting the 'multi_auth.user-id' cookie on login. Additionally, we now cleanup if cookie pointer OR session is set (instead of only if both are set). * Fix comments in middleware * Remove unnecessary effect dependencies setState is stable and thus only noise in effect dependencies * Show but disable unavailable auth methods * make signup button consistent with others * Always reload page on switch * refine account switch styling * logout barrier --------- Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com> Co-authored-by: k00b <k00b@stacker.news>
2024-09-12 18:05:11 +00:00
})
Wallet Logs (#994) * nwc wallet logs * persist logs in IndexedDB * Potential fix for empty error message * load logs limited to 5m ago from IDB * load logs from past via query param * Add 5m, 1h, 6h links for earlier logs * Show end of log * Clamp to logStart * Add log.module.css * Remove TODO about persistence * Use table for logs * <table> fixes bad format with fixed width and message overflow into start of next row * also using ---start of log--- instead of ---end of log--- now * removed time string in header nav * Rename .header to .logNav * Simply load all logs and remove navigation I realized the code for navigation was most likely premature optimization which even resulted in worse UX: Using the buttons to load logs from 5m, 1h, 6h ago sometimes meant that nothing happened at all since there were no logs from 5m, 1h, 6h ago. That's why I added a time string as "start of logs" so it's at least visible that it changed but that looked bad so I removed it. But all of this was not necessary: I can simply load all logs at once and then the user can scroll around however they like. I was worried that it would be bad for performance to load all logs at once since we might store a lot of logs but as mentioned, that's probably premature optimization. WHEN a lot of logs are stored AND this becomes a problem (What problem even? Slow page load?), THEN we can think about this. If page load ever becomes slow because of loading logs, we could probably simply not load the logs at page load but only when /wallet/logs is visited. But for now, this works fine. * Add follow checkbox * Create WalletLogs component * Embed wallet logs * Remove test error * Fix level padding * Add LNbits logs * Add logs for attaching LND and lnAddr * Use err.message || err.toString?.() consistently * Autowithdrawal logs * Use details from LND error * Don't log test invoice individually * Also refetch logs on error * Remove obsolete and annoying toasts * Replace scrollIntoView with scroll * Use constant embedded max-height * Fix missing width: 100% for embedded logs * Show full payment hash and preimage in logs * Also parse details from LND errors on autowithdrawal failures * Remove TODO * Fix accidental removal of wss:// check * Fix alignment of start marker and show empty if empty * Fix sendPayment loop * Split context in two
2024-04-03 22:27:21 +00:00
const logger = useServiceWorkerLogger()
2021-10-30 16:20:11 +00:00
2022-06-02 22:55:23 +00:00
const { data } = useQuery(SETTINGS)
const { settings: { privates: settings } } = useMemo(() => data ?? ssrData, [data, ssrData])
Account Switching (#644) * WIP: Account switching * Fix empty USER query ANON_USER_ID was undefined and thus the query for @anon had no variables. * Apply multiAuthMiddleware in /api/graphql * Fix 'you must be logged in' query error on switch to anon * Add smart 'switch account' button "smart" means that it only shows if there are accounts to which one can switch * Fix multiAuth not set in backend * Comment fixes, minor changes * Use fw-bold instead of 'selected' * Close dropdown and offcanvas Inside a dropdown, we can rely on autoClose but need to wrap the buttons with <Dropdown.Item> for that to work. For the offcanvas, we need to pass down handleClose. * Use button to add account * Some pages require hard reload on account switch * Reinit settings form on account switch * Also don't refetch WalletHistory * Formatting * Use width: fit-content for standalone SignUpButton * Remove unused className * Use fw-bold and text-underline on selected * Fix inconsistent padding of login buttons * Fix duplicate redirect from /settings on anon switch * Never throw during refetch * Throw errors which extend GraphQLError * Only use meAnonSats if logged out * Use reactive variable for meAnonSats The previous commit broke the UI update after anon zaps because we actually updated item.meSats in the cache and not item.meAnonSats. Updating item.meAnonSats was not possible because it's a local field. For that, one needs to use reactive variables. We do this now and thus also don't need the useEffect hack in item-info.js anymore. * Switch to new user * Fix missing cleanup during logout If we logged in but never switched to any other account, the 'multi_auth.user-id' cookie was not set. This meant that during logout, the other 'multi_auth.*' cookies were not deleted. This broke the account switch modal. This is fixed by setting the 'multi_auth.user-id' cookie on login. Additionally, we now cleanup if cookie pointer OR session is set (instead of only if both are set). * Fix comments in middleware * Remove unnecessary effect dependencies setState is stable and thus only noise in effect dependencies * Show but disable unavailable auth methods * make signup button consistent with others * Always reload page on switch * refine account switch styling * logout barrier --------- Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com> Co-authored-by: k00b <k00b@stacker.news>
2024-09-12 18:05:11 +00:00
// if we switched to anon, me is null before the page is reloaded
if ((!data && !ssrData) || !me) return <PageLoading />
2022-06-02 22:55:23 +00:00
2021-10-30 16:20:11 +00:00
return (
<Layout>
<div className='pb-3 w-100 mt-2' style={{ maxWidth: '600px' }}>
<SettingsHeader />
{hasOnlyOneAuthMethod(settings?.authMethods) && <AuthBanner />}
2022-06-02 22:55:23 +00:00
<Form
Account Switching (#644) * WIP: Account switching * Fix empty USER query ANON_USER_ID was undefined and thus the query for @anon had no variables. * Apply multiAuthMiddleware in /api/graphql * Fix 'you must be logged in' query error on switch to anon * Add smart 'switch account' button "smart" means that it only shows if there are accounts to which one can switch * Fix multiAuth not set in backend * Comment fixes, minor changes * Use fw-bold instead of 'selected' * Close dropdown and offcanvas Inside a dropdown, we can rely on autoClose but need to wrap the buttons with <Dropdown.Item> for that to work. For the offcanvas, we need to pass down handleClose. * Use button to add account * Some pages require hard reload on account switch * Reinit settings form on account switch * Also don't refetch WalletHistory * Formatting * Use width: fit-content for standalone SignUpButton * Remove unused className * Use fw-bold and text-underline on selected * Fix inconsistent padding of login buttons * Fix duplicate redirect from /settings on anon switch * Never throw during refetch * Throw errors which extend GraphQLError * Only use meAnonSats if logged out * Use reactive variable for meAnonSats The previous commit broke the UI update after anon zaps because we actually updated item.meSats in the cache and not item.meAnonSats. Updating item.meAnonSats was not possible because it's a local field. For that, one needs to use reactive variables. We do this now and thus also don't need the useEffect hack in item-info.js anymore. * Switch to new user * Fix missing cleanup during logout If we logged in but never switched to any other account, the 'multi_auth.user-id' cookie was not set. This meant that during logout, the other 'multi_auth.*' cookies were not deleted. This broke the account switch modal. This is fixed by setting the 'multi_auth.user-id' cookie on login. Additionally, we now cleanup if cookie pointer OR session is set (instead of only if both are set). * Fix comments in middleware * Remove unnecessary effect dependencies setState is stable and thus only noise in effect dependencies * Show but disable unavailable auth methods * make signup button consistent with others * Always reload page on switch * refine account switch styling * logout barrier --------- Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com> Co-authored-by: k00b <k00b@stacker.news>
2024-09-12 18:05:11 +00:00
enableReinitialize
2022-06-02 22:55:23 +00:00
initial={{
tipDefault: settings?.tipDefault || 21,
tipRandom: settings?.tipRandom,
tipRandomMin: settings?.tipRandomMin || 1,
2024-08-03 19:07:17 +00:00
tipRandomMax: settings?.tipRandomMax || 10,
2022-12-09 19:25:38 +00:00
turboTipping: settings?.turboTipping,
disableFreebies: settings?.disableFreebies || undefined,
2024-03-26 16:57:20 +00:00
zapUndos: settings?.zapUndos || (settings?.tipDefault ? 100 * settings.tipDefault : 2100),
2024-03-25 08:47:50 +00:00
zapUndosEnabled: settings?.zapUndos !== null,
fiatCurrency: settings?.fiatCurrency || 'USD',
withdrawMaxFeeDefault: settings?.withdrawMaxFeeDefault,
2022-06-02 22:55:23 +00:00
noteItemSats: settings?.noteItemSats,
noteEarning: settings?.noteEarning,
noteAllDescendants: settings?.noteAllDescendants,
noteMentions: settings?.noteMentions,
noteItemMentions: settings?.noteItemMentions,
2022-06-02 22:55:23 +00:00
noteDeposits: settings?.noteDeposits,
2024-03-25 20:20:11 +00:00
noteWithdrawals: settings?.noteWithdrawals,
2022-06-02 22:55:23 +00:00
noteInvites: settings?.noteInvites,
2022-08-30 21:50:47 +00:00
noteJobIndicator: settings?.noteJobIndicator,
2023-02-01 14:44:35 +00:00
noteCowboyHat: settings?.noteCowboyHat,
noteForwardedSats: settings?.noteForwardedSats,
2022-09-21 19:57:36 +00:00
hideInvoiceDesc: settings?.hideInvoiceDesc,
autoDropBolt11s: settings?.autoDropBolt11s,
2022-12-01 21:31:04 +00:00
hideFromTopUsers: settings?.hideFromTopUsers,
2023-05-01 21:49:47 +00:00
hideCowboyHat: settings?.hideCowboyHat,
hideGithub: settings?.hideGithub,
hideNostr: settings?.hideNostr,
hideTwitter: settings?.hideTwitter,
imgproxyOnly: settings?.imgproxyOnly,
showImagesAndVideos: settings?.showImagesAndVideos,
2022-09-27 21:19:15 +00:00
wildWestMode: settings?.wildWestMode,
satsFilter: settings?.satsFilter,
nsfwMode: settings?.nsfwMode,
2023-02-01 15:54:08 +00:00
nostrPubkey: settings?.nostrPubkey ? bech32encode(settings.nostrPubkey) : '',
nostrCrossposting: settings?.nostrCrossposting,
nostrRelays: settings?.nostrRelays?.length ? settings?.nostrRelays : [''],
hideBookmarks: settings?.hideBookmarks,
hideWalletBalance: settings?.hideWalletBalance,
diagnostics: settings?.diagnostics,
hideIsContributor: settings?.hideIsContributor,
noReferralLinks: settings?.noReferralLinks
2022-06-02 22:55:23 +00:00
}}
2023-02-08 19:38:04 +00:00
schema={settingsSchema}
onSubmit={async ({
tipDefault, tipRandom, tipRandomMin, tipRandomMax, withdrawMaxFeeDefault,
zapUndos, zapUndosEnabled, nostrPubkey, nostrRelays, satsFilter,
...values
}) => {
2023-01-07 00:53:09 +00:00
if (nostrPubkey.length === 0) {
nostrPubkey = null
2023-02-01 15:54:08 +00:00
} else {
2023-02-08 19:38:04 +00:00
if (NOSTR_PUBKEY_BECH32.test(nostrPubkey)) {
2023-02-01 15:54:08 +00:00
const { words } = bech32.decode(nostrPubkey)
nostrPubkey = Buffer.from(bech32.fromWords(words)).toString('hex')
}
2023-01-07 00:53:09 +00:00
}
const nostrRelaysFiltered = nostrRelays
?.filter(word => word.trim().length > 0)
.map(relay => relay.startsWith('wss://') ? relay : `wss://${relay}`)
2023-01-07 00:53:09 +00:00
try {
await setSettings({
variables: {
2023-11-10 01:05:35 +00:00
settings: {
tipDefault: Number(tipDefault),
tipRandomMin: tipRandom ? Number(tipRandomMin) : null,
tipRandomMax: tipRandom ? Number(tipRandomMax) : null,
2023-11-10 01:05:35 +00:00
withdrawMaxFeeDefault: Number(withdrawMaxFeeDefault),
satsFilter: Number(satsFilter),
2024-03-25 00:46:12 +00:00
zapUndos: zapUndosEnabled ? Number(zapUndos) : null,
2023-11-10 01:05:35 +00:00
nostrPubkey,
nostrRelays: nostrRelaysFiltered,
...values
}
}
})
toaster.success('saved settings')
} catch (err) {
console.error(err)
toaster.danger('failed to save settings')
}
2022-06-02 22:55:23 +00:00
}}
>
<Input
2023-06-19 18:21:55 +00:00
label='zap default'
2022-06-02 22:55:23 +00:00
name='tipDefault'
2022-12-09 19:25:38 +00:00
groupClassName='mb-0'
2022-06-02 22:55:23 +00:00
required
autoFocus
append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
2023-06-19 18:21:55 +00:00
hint={<small className='text-muted'>note: you can also press and hold the lightning bolt to zap custom amounts</small>}
2022-06-02 22:55:23 +00:00
/>
<div className='pb-4'>
2022-12-09 19:25:38 +00:00
<AccordianItem
show={settings?.turboTipping}
header={<div style={{ fontWeight: 'bold', fontSize: '92%' }}>advanced</div>}
body={
<>
<Checkbox
name='turboTipping'
label={
<div className='d-flex align-items-center'>turbo zapping
<Info>
<ul>
<li>Makes every additional bolt click raise your total zap to another 10x multiple of your default zap</li>
<li>e.g. if your zap default is 10 sats
<ul>
<li>1st click: 10 sats total zapped</li>
<li>2nd click: 100 sats total zapped</li>
<li>3rd click: 1000 sats total zapped</li>
<li>4th click: 10000 sats total zapped</li>
<li>and so on ...</li>
</ul>
</li>
<li>You can still custom zap via long press
<ul>
<li>the next bolt click rounds up to the next greatest 10x multiple of your default</li>
</ul>
</li>
2022-12-09 19:25:38 +00:00
</ul>
</Info>
</div>
}
groupClassName='mb-0'
/>
<ZapUndosField />
<TipRandomField />
</>
}
2022-12-09 19:25:38 +00:00
/>
</div>
<Select
label='fiat currency'
name='fiatCurrency'
size='sm'
2023-02-08 19:38:04 +00:00
items={SUPPORTED_CURRENCIES}
required
/>
<Input
label='default max fee for withdrawals'
name='withdrawMaxFeeDefault'
required
append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
/>
<Checkbox
label={
<div className='d-flex align-items-center'>disable freebies
<Info>
<p>Some comments can be created without paying. However, those comments have limited visibility.</p>
<p>If you disable freebies, you will always pay for your comments and get standard visibility.</p>
<p>If you attach a sending wallet, we disable freebies for you unless you have checked/unchecked this value already.</p>
</Info>
</div>
}
name='disableFreebies'
/>
<div className='form-label'>notify me when ...</div>
2022-06-02 22:55:23 +00:00
<Checkbox
label='I stack sats from posts and comments'
name='noteItemSats'
groupClassName='mb-0'
/>
<Checkbox
label='I get forwarded sats from a post'
name='noteForwardedSats'
groupClassName='mb-0'
/>
2022-06-02 22:55:23 +00:00
<Checkbox
label='I get a daily airdrop'
name='noteEarning'
groupClassName='mb-0'
/>
<Checkbox
label='someone replies to someone who replied to me'
name='noteAllDescendants'
groupClassName='mb-0'
/>
<Checkbox
2022-12-19 22:27:52 +00:00
label='someone joins using my invite or referral links'
2022-06-02 22:55:23 +00:00
name='noteInvites'
groupClassName='mb-0'
/>
<Checkbox
label='sats are deposited in my account'
name='noteDeposits'
groupClassName='mb-0'
/>
2024-03-25 20:20:11 +00:00
<Checkbox
label='sats are withdrawn from my account'
name='noteWithdrawals'
groupClassName='mb-0'
/>
2022-06-02 22:55:23 +00:00
<Checkbox
label='someone mentions me'
name='noteMentions'
groupClassName='mb-0'
/>
<Checkbox
label='someone mentions one of my items'
name='noteItemMentions'
groupClassName='mb-0'
/>
2022-06-02 22:55:23 +00:00
<Checkbox
label='there is a new job'
name='noteJobIndicator'
2023-02-01 14:44:35 +00:00
groupClassName='mb-0'
/>
<Checkbox
label='I find or lose cowboy essentials (e.g. cowboy hat)'
2023-02-01 14:44:35 +00:00
name='noteCowboyHat'
2022-06-02 22:55:23 +00:00
/>
2022-08-30 21:50:47 +00:00
<div className='form-label'>privacy</div>
<Checkbox
label={
2022-09-21 19:57:36 +00:00
<div className='d-flex align-items-center'>hide invoice descriptions
2022-08-30 21:50:47 +00:00
<Info>
<ul>
2022-08-30 21:50:47 +00:00
<li>Use this if you don't want funding sources to be linkable to your SN identity.</li>
<li>It makes your invoice descriptions blank.</li>
<li>This only applies to invoices you create
2022-08-30 21:50:47 +00:00
<ul>
<li>lnurl-pay and lightning addresses still reference your nym</li>
2022-08-30 21:50:47 +00:00
</ul>
</li>
</ul>
</Info>
2022-09-21 19:57:36 +00:00
</div>
2022-08-30 21:50:47 +00:00
}
name='hideInvoiceDesc'
2022-12-01 21:31:04 +00:00
groupClassName='mb-0'
/>
<DropBolt11sCheckbox
ssrData={ssrData}
label={
<div className='d-flex align-items-center'>autodelete withdrawal invoices
<Info>
<ul>
<li>use this to protect receiver privacy</li>
<li>applies retroactively, cannot be reversed</li>
<li>withdrawal invoices are kept at least {INVOICE_RETENTION_DAYS} days for security and debugging purposes</li>
<li>autodeletions are run on a daily basis at night</li>
</ul>
</Info>
</div>
}
name='autoDropBolt11s'
groupClassName='mb-0'
/>
2022-12-01 21:31:04 +00:00
<Checkbox
label={<>hide me from <Link href='/top/stackers/day'>top stackers</Link></>}
2022-12-01 21:31:04 +00:00
name='hideFromTopUsers'
2023-05-01 21:49:47 +00:00
groupClassName='mb-0'
/>
<Checkbox
label={<>hide my cowboy hat</>}
name='hideCowboyHat'
groupClassName='mb-0'
/>
<Checkbox
label={<>hide my wallet balance</>}
name='hideWalletBalance'
groupClassName='mb-0'
/>
<Checkbox
2023-09-18 23:44:30 +00:00
label={<>hide my bookmarks from other stackers</>}
name='hideBookmarks'
groupClassName='mb-0'
/>
<Checkbox
disabled={!settings?.authMethods?.github}
label={
<div className='d-flex align-items-center'>hide my linked github profile
<Info>
<ul>
<li>Linked accounts are hidden from your profile by default</li>
<li>uncheck this to display your github on your profile</li>
{!settings?.authMethods?.github &&
<div className='my-2'>
<li><i>You don't seem to have a linked github account</i></li>
<ul><li>If this is wrong, try unlinking/relinking</li></ul>
</div>}
</ul>
</Info>
</div>
}
name='hideGithub'
groupClassName='mb-0'
/>
<Checkbox
disabled={!settings?.authMethods?.nostr}
label={
<div className='d-flex align-items-center'>hide my linked nostr profile
<Info>
<ul>
<li>Linked accounts are hidden from your profile by default</li>
<li>Uncheck this to display your npub on your profile</li>
{!settings?.authMethods?.nostr &&
<div className='my-2'>
<li>You don't seem to have a linked nostr account</li>
<ul><li>If this is wrong, try unlinking/relinking</li></ul>
</div>}
</ul>
</Info>
</div>
}
name='hideNostr'
groupClassName='mb-0'
/>
<Checkbox
disabled={!settings?.authMethods?.twitter}
label={
<div className='d-flex align-items-center'>hide my linked twitter profile
<Info>
<ul>
<li>Linked accounts are hidden from your profile by default</li>
<li>Uncheck this to display your twitter on your profile</li>
{!settings?.authMethods?.twitter &&
<div className='my-2'>
<i>You don't seem to have a linked twitter account</i>
<ul><li>If this is wrong, try unlinking/relinking</li></ul>
</div>}
</ul>
</Info>
</div>
}
name='hideTwitter'
groupClassName='mb-0'
/>
{me.optional?.isContributor &&
<Checkbox
label={<>hide that I'm a stacker.news contributor</>}
name='hideIsContributor'
groupClassName='mb-0'
/>}
<Checkbox
label={
<div className='d-flex align-items-center'>do not load images, videos, or content from external sites
<Info>
<ul>
<li>only load images and videos when we can proxy them</li>
<li>this prevents IP address leaks to arbitrary sites</li>
<li>if we can't, the raw link will be shown instead</li>
</ul>
</Info>
</div>
}
name='imgproxyOnly'
groupClassName='mb-0'
/>
<Checkbox
label={
2023-09-18 23:44:30 +00:00
<div className='d-flex align-items-center'>allow anonymous diagnostics
<Info>
<ul>
2023-09-18 23:44:30 +00:00
<li>collect and send back anonymous diagnostics data</li>
<li>this information is used to fix bugs</li>
<li>this information includes:
<ul><li>timestamps</li></ul>
<ul><li>a randomly generated fancy name</li></ul>
<ul><li>your user agent</li></ul>
<ul><li>your operating system</li></ul>
</li>
<li>this information can not be traced back to you without your fancy name</li>
<li>fancy names are generated in your browser</li>
</ul>
<div className='text-muted fst-italic'>your fancy name: {logger.name}</div>
</Info>
</div>
}
name='diagnostics'
groupClassName='mb-0'
/>
<Checkbox
label={<>don't create referral links on copy</>}
name='noReferralLinks'
2022-08-30 21:50:47 +00:00
/>
<h4>content</h4>
<Input
2022-09-21 19:57:36 +00:00
label={
<div className='d-flex align-items-center'>filter by sats
2022-09-21 19:57:36 +00:00
<Info>
<ul>
<li>hide the post if the sum of these is less than your setting:</li>
<ul>
<li>posting cost</li>
<li>total sats from zaps</li>
<li>boost</li>
</ul>
<li>set to zero to be a greeter, with the tradeoff of seeing more spam</li>
2022-09-21 19:57:36 +00:00
</ul>
</Info>
</div>
}
name='satsFilter'
required
append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
2022-09-27 21:19:15 +00:00
/>
<Checkbox
label={
<div className='d-flex align-items-center'>show images, video, and 3rd party embeds
<Info>
<ul>
<li>if checked and a link is an image, video or can be embedded in another way, we will do it</li>
<li>we support embeds from following sites:</li>
<ul>
<li>njump.me</li>
<li>youtube.com</li>
<li>twitter.com</li>
<li>spotify.com</li>
<li>rumble.com</li>
<li>wavlake.com</li>
<li>bitcointv.com</li>
<li>peertube.tv</li>
</ul>
</ul>
</Info>
</div>
}
name='showImagesAndVideos'
groupClassName='mb-0'
/>
2022-09-27 21:19:15 +00:00
<Checkbox
label={
<div className='d-flex align-items-center'>wild west mode
2022-09-27 21:19:15 +00:00
<Info>
<ul>
<li>don't hide flagged content</li>
<li>don't down rank flagged content</li>
2022-09-27 21:19:15 +00:00
</ul>
</Info>
</div>
}
name='wildWestMode'
groupClassName='mb-0'
/>
<Checkbox
label={
<div className='d-flex align-items-center'>nsfw mode
<Info>
<ul>
<li>see posts from nsfw territories</li>
</ul>
</Info>
</div>
}
name='nsfwMode'
2022-09-21 19:57:36 +00:00
/>
<h4>nostr</h4>
<Checkbox
label={
<div className='d-flex align-items-center'>crosspost to nostr
<Info>
<ul>
Nostr crossposting all item types (#779) * crosspost-item * crosspost old items, update with nEventId * Updating noteId encoding, cleaning up a little * Fixing item-info condition, cleaning up * Linting * Add createdAt variable back * Change instances of eventId to noteId * Adding upsertNoteId mutation * Cleaning up updateItem, using toasts to communivate success/failure in crosspost-item * Linting * Move crosspost to share button, make sure only OP can crosspost * Lint * Simplify conditions * user might have no nostr extension installed Co-authored-by: ekzyis <27162016+ekzyis@users.noreply.github.com> * change upsertNoteId to updateNoteID for resolver and mutations, change isOp to mine, remove unused noteId params * Basic setup for crossposting poll / link items * post rebase fixes and Bounty and job crossposts * Job crossposting working * adding back accidentally removed import * Lint / rebase * Outsource as much crossposting logic from discussion-form into use-crossposter as possible * Fix incorrect property for user relays, fix itemId param in updateNoteId * Fix toast messages / error cases in use-crossposter * Update item forms to for updated use-crossposter hook * CrosspostDropdownItem in share updated to accomodate use-crossposter update * Encode paramaterized replacable event id's in naddress format with nostr-tools, bounty to follw nip-99 spec * Increase timeout on relay connection / cleaning up * No longer crossposting job * Add blastr, fix crosspost button in item-info for polls/discussions, finish removing job crosspostr code * Fix toaster error, create reusable crossposterror function to surface toaster * Cleaning up / comments / linting * Update copy * Simplify CrosspostdropdownItem, keep replies from being crossposted * Moved query for missing item fields when crossposting to use-crossposter hook * Remove unneeded param in CrosspostDropdownItem, lint * Small fixes post rebase * Remove unused import * fix nostr-tools version, fix package-lock.json * Update components/item-info.js Co-authored-by: ekzyis <ek@stacker.news> * Remove unused param, determine poll item type from pollCost field, add mutiny strfry relay to defaults * Update toaster implementations, use no-cache for item query, restructure crosspostItem to use await with try catch * crosspost info modal that lives under adv-post-form now has dynamic crossposting info * Move determineItemType into handleEventCreation, mover item/event handing outside of do ... while loop * Lint * Reconcile skip method with onCancel function in toaster * Handle failedRelays being undefined * determine item type from router.query.type if available otherwise use item fields * Initiliaze failerRelays as undefined but handle error explicitly * Lint * Fix crosspost default value for link, poll, bounty forms --------- Co-authored-by: ekzyis <27162016+ekzyis@users.noreply.github.com> Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-02-22 01:18:36 +00:00
<li>crosspost your items to nostr</li>
<li>requires NIP-07 extension for signing</li>
<li>we use your NIP-05 relays if set</li>
Nostr crossposting all item types (#779) * crosspost-item * crosspost old items, update with nEventId * Updating noteId encoding, cleaning up a little * Fixing item-info condition, cleaning up * Linting * Add createdAt variable back * Change instances of eventId to noteId * Adding upsertNoteId mutation * Cleaning up updateItem, using toasts to communivate success/failure in crosspost-item * Linting * Move crosspost to share button, make sure only OP can crosspost * Lint * Simplify conditions * user might have no nostr extension installed Co-authored-by: ekzyis <27162016+ekzyis@users.noreply.github.com> * change upsertNoteId to updateNoteID for resolver and mutations, change isOp to mine, remove unused noteId params * Basic setup for crossposting poll / link items * post rebase fixes and Bounty and job crossposts * Job crossposting working * adding back accidentally removed import * Lint / rebase * Outsource as much crossposting logic from discussion-form into use-crossposter as possible * Fix incorrect property for user relays, fix itemId param in updateNoteId * Fix toast messages / error cases in use-crossposter * Update item forms to for updated use-crossposter hook * CrosspostDropdownItem in share updated to accomodate use-crossposter update * Encode paramaterized replacable event id's in naddress format with nostr-tools, bounty to follw nip-99 spec * Increase timeout on relay connection / cleaning up * No longer crossposting job * Add blastr, fix crosspost button in item-info for polls/discussions, finish removing job crosspostr code * Fix toaster error, create reusable crossposterror function to surface toaster * Cleaning up / comments / linting * Update copy * Simplify CrosspostdropdownItem, keep replies from being crossposted * Moved query for missing item fields when crossposting to use-crossposter hook * Remove unneeded param in CrosspostDropdownItem, lint * Small fixes post rebase * Remove unused import * fix nostr-tools version, fix package-lock.json * Update components/item-info.js Co-authored-by: ekzyis <ek@stacker.news> * Remove unused param, determine poll item type from pollCost field, add mutiny strfry relay to defaults * Update toaster implementations, use no-cache for item query, restructure crosspostItem to use await with try catch * crosspost info modal that lives under adv-post-form now has dynamic crossposting info * Move determineItemType into handleEventCreation, mover item/event handing outside of do ... while loop * Lint * Reconcile skip method with onCancel function in toaster * Handle failedRelays being undefined * determine item type from router.query.type if available otherwise use item fields * Initiliaze failerRelays as undefined but handle error explicitly * Lint * Fix crosspost default value for link, poll, bounty forms --------- Co-authored-by: ekzyis <27162016+ekzyis@users.noreply.github.com> Co-authored-by: ekzyis <ek@stacker.news> Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
2024-02-22 01:18:36 +00:00
<li>we use these relays by default:</li>
<ul>
{DEFAULT_CROSSPOSTING_RELAYS.map((relay, i) => (
<li key={i}>{relay}</li>
))}
</ul>
</ul>
</Info>
</div>
}
name='nostrCrossposting'
/>
<Input
label={<>pubkey <small className='text-muted ms-2'>optional</small></>}
name='nostrPubkey'
clear
hint={<small className='text-muted'>used for NIP-05</small>}
/>
<VariableInput
label={<>relays <small className='text-muted ms-2'>optional</small></>}
name='nostrRelays'
clear
min={0}
max={NOSTR_MAX_RELAY_NUM}
hint={<small className='text-muted'>used for NIP-05 and crossposting</small>}
2023-01-07 00:53:09 +00:00
/>
2022-06-02 22:55:23 +00:00
<div className='d-flex'>
2023-07-24 18:35:05 +00:00
<SubmitButton variant='info' className='ms-auto mt-1 px-4'>save</SubmitButton>
2022-06-02 22:55:23 +00:00
</div>
</Form>
2023-08-13 19:12:18 +00:00
<div className='text-start w-100'>
2022-06-02 22:55:23 +00:00
<div className='form-label'>saturday newsletter</div>
<Button href='https://mail.stacker.news/subscription/form' target='_blank'>(re)subscribe</Button>
{settings?.authMethods && <AuthMethods methods={settings.authMethods} apiKeyEnabled={settings.apiKeyEnabled} />}
2022-06-02 22:55:23 +00:00
</div>
</div>
</Layout>
)
}
const DropBolt11sCheckbox = ({ ssrData, ...props }) => {
const showModal = useShowModal()
const { data } = useQuery(gql`{ numBolt11s }`)
const { numBolt11s } = data || ssrData
return (
<Checkbox
onClick={e => {
if (e.target.checked) {
showModal(onClose => {
return (
<>
<p className='fw-bolder'>{numBolt11s} withdrawal invoices will be deleted with this setting.</p>
<p className='fw-bolder'>You sure? This is a gone forever kind of delete.</p>
<div className='d-flex justify-content-end'>
<Button
variant='danger' onClick={async () => {
await onClose()
}}
>I am sure
</Button>
</div>
</>
)
})
}
}}
{...props}
/>
)
}
function QRLinkButton ({ provider, unlink, status }) {
const showModal = useShowModal()
const text = status ? 'Unlink' : 'Link'
const onClick = status
? unlink
: () => showModal(onClose =>
<div className='d-flex flex-column align-items-center'>
2023-08-17 17:36:23 +00:00
<LightningAuth />
</div>)
return (
<LoginButton
key={provider}
className='d-block mt-2' type={provider} text={text} onClick={onClick}
/>
)
}
function NostrLinkButton ({ unlink, status }) {
const showModal = useShowModal()
const text = status ? 'Unlink' : 'Link'
const onClick = status
? unlink
: () => showModal(onClose =>
<div className='d-flex flex-column align-items-center'>
<NostrAuth text='Unlink' />
</div>)
return (
<LoginButton
className='d-block mt-2' type='nostr' text={text} onClick={onClick}
/>
)
}
function UnlinkObstacle ({ onClose, type, unlinkAuth }) {
const router = useRouter()
const toaster = useToast()
return (
<div>
You are removing your last auth method. It is recommended you link another auth method before removing
your last auth method. If you'd like to proceed anyway, type the following below
2023-07-24 18:35:05 +00:00
<div className='text-danger fw-bold my-2'>
If I logout, even accidentally, I will never be able to access my account again
</div>
<Form
className='mt-3'
initial={{
warning: ''
}}
schema={lastAuthRemovalSchema}
onSubmit={async () => {
try {
await unlinkAuth({ variables: { authType: type } })
router.push('/settings')
onClose()
toaster.success('unlinked auth method')
} catch (err) {
console.error(err)
toaster.danger('failed to unlink auth method')
}
}}
>
<Input
name='warning'
required
/>
2023-07-24 18:35:05 +00:00
<SubmitButton className='d-flex ms-auto' variant='danger'>do it</SubmitButton>
</Form>
</div>
)
}
function AuthMethods ({ methods, apiKeyEnabled }) {
const showModal = useShowModal()
const router = useRouter()
const toaster = useToast()
const [err, setErr] = useState(authErrorMessage(router.query.error))
2022-06-02 22:55:23 +00:00
const [unlinkAuth] = useMutation(
gql`
mutation unlinkAuth($authType: String!) {
unlinkAuth(authType: $authType) {
lightning
email
twitter
github
nostr
2022-06-02 22:55:23 +00:00
}
}`, {
update (cache, { data: { unlinkAuth } }) {
cache.modify({
id: 'ROOT_QUERY',
fields: {
settings (existing) {
2023-11-12 17:59:18 +00:00
return {
...existing,
privates: {
...existing.privates,
authMethods: { ...unlinkAuth }
}
}
2022-06-02 22:55:23 +00:00
}
}
})
}
}
)
const providers = getProviders(methods)
2023-01-18 18:49:20 +00:00
2022-06-02 22:55:23 +00:00
const unlink = async type => {
// if there's only one auth method left
2023-01-18 18:49:20 +00:00
const links = providers.reduce((t, p) => t + (methods[p] ? 1 : 0), 0)
2022-06-02 22:55:23 +00:00
if (links === 1) {
showModal(onClose => (<UnlinkObstacle onClose={onClose} type={type} unlinkAuth={unlinkAuth} />))
2022-06-02 22:55:23 +00:00
} else {
try {
await unlinkAuth({ variables: { authType: type } })
toaster.success('unlinked auth method')
} catch (err) {
console.error(err)
toaster.danger('failed to unlink auth method')
}
2022-06-02 22:55:23 +00:00
}
}
return (
<>
<div className='form-label mt-3'>auth methods</div>
2023-07-31 13:39:10 +00:00
{err && (
<Alert
variant='danger' onClose={() => {
const { pathname, query: { error, nodata, ...rest } } = router
router.replace({
pathname,
query: { nodata, ...rest }
}, { pathname, query: { ...rest } }, { shallow: true })
setErr(undefined)
}} dismissible
>{err}
</Alert>
)}
{providers?.map(provider => {
if (provider === 'email') {
return methods.email
? (
<div key={provider} className='mt-2 d-flex align-items-center'>
<Button
Store hashed and salted email addresses (#1111) * first pass of hashing user emails * use salt * add a salt to .env.development (prod salt needs to be kept a secret) * move `hashEmail` util to a new util module * trigger a one-time job to migrate existing emails via the worker so we can use the salt from an env var * move newsletter signup move newsletter signup to prisma adapter create user with email code path so we can still auto-enroll email accounts without having to persist the email address in plaintext * remove `email` from api key session lookup query * drop user email index before dropping column * restore email column, just null values instead * fix function name * fix salt and hash raw sql statement * update auth methods email type in typedefs from str to bool * remove todo comment * lowercase email before hashing during migration * check for emailHash and email to accommodate migration window update our lookups to check for a matching emailHash, and then a matching email, in that order, to accommodate the case that a user tries to login via email while the migration is running, and their account has not yet been migrated also update sndev to have a command `./sndev email` to launch the mailhog inbox in your browser also update `./sndev login` to hash the generated email address and insert it into the db record * update sndev help * update awards.csv * update the hack in next-auth to re-use the email supplied on input to `getUserByEmail` * consolidate console.error logs * create generic open command --------- Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com> Co-authored-by: keyan <keyan.kousha+huumn@gmail.com>
2024-05-04 23:06:15 +00:00
variant='secondary' onClick={
async () => {
await unlink('email')
}
}
>Unlink Email
</Button>
</div>
)
: <div key={provider} className='mt-2'><EmailLinkForm /></div>
2023-08-17 17:36:23 +00:00
} else if (provider === 'lightning') {
return (
<QRLinkButton
key={provider} provider={provider}
status={methods[provider]} unlink={async () => await unlink(provider)}
/>
)
} else if (provider === 'nostr') {
return <NostrLinkButton key='nostr' status={methods[provider]} unlink={async () => await unlink(provider)} />
} else {
return (
<LoginButton
className='mt-2 d-block'
key={provider}
type={provider.toLowerCase()}
onClick={async () => {
if (methods[provider]) {
await unlink(provider)
} else {
signIn(provider)
}
}}
text={methods[provider] ? 'Unlink' : 'Link'}
/>
)
2022-06-02 22:55:23 +00:00
}
2023-01-18 18:49:20 +00:00
})}
<ApiKey apiKey={methods.apiKey} enabled={apiKeyEnabled} />
2022-06-02 22:55:23 +00:00
</>
)
}
export function EmailLinkForm ({ callbackUrl }) {
const [linkUnverifiedEmail] = useMutation(
gql`
mutation linkUnverifiedEmail($email: String!) {
linkUnverifiedEmail(email: $email)
}`
)
return (
<Form
initial={{
email: ''
}}
2023-02-08 19:38:04 +00:00
schema={emailSchema}
2022-06-02 22:55:23 +00:00
onSubmit={async ({ email }) => {
// add email to user's account
// then call signIn
const { data } = await linkUnverifiedEmail({ variables: { email } })
if (data.linkUnverifiedEmail) {
signIn('email', { email, callbackUrl })
}
}}
>
<div className='d-flex align-items-center'>
2021-10-30 16:20:11 +00:00
<Input
2022-06-02 22:55:23 +00:00
name='email'
placeholder='email@example.com'
2021-10-30 16:20:11 +00:00
required
2022-04-21 22:50:02 +00:00
groupClassName='mb-0'
/>
2023-07-24 18:35:05 +00:00
<SubmitButton className='ms-2' variant='secondary'>Link Email</SubmitButton>
2022-06-02 22:55:23 +00:00
</div>
</Form>
2021-10-30 16:20:11 +00:00
)
}
function ApiKey ({ enabled, apiKey }) {
const showModal = useShowModal()
Account Switching (#644) * WIP: Account switching * Fix empty USER query ANON_USER_ID was undefined and thus the query for @anon had no variables. * Apply multiAuthMiddleware in /api/graphql * Fix 'you must be logged in' query error on switch to anon * Add smart 'switch account' button "smart" means that it only shows if there are accounts to which one can switch * Fix multiAuth not set in backend * Comment fixes, minor changes * Use fw-bold instead of 'selected' * Close dropdown and offcanvas Inside a dropdown, we can rely on autoClose but need to wrap the buttons with <Dropdown.Item> for that to work. For the offcanvas, we need to pass down handleClose. * Use button to add account * Some pages require hard reload on account switch * Reinit settings form on account switch * Also don't refetch WalletHistory * Formatting * Use width: fit-content for standalone SignUpButton * Remove unused className * Use fw-bold and text-underline on selected * Fix inconsistent padding of login buttons * Fix duplicate redirect from /settings on anon switch * Never throw during refetch * Throw errors which extend GraphQLError * Only use meAnonSats if logged out * Use reactive variable for meAnonSats The previous commit broke the UI update after anon zaps because we actually updated item.meSats in the cache and not item.meAnonSats. Updating item.meAnonSats was not possible because it's a local field. For that, one needs to use reactive variables. We do this now and thus also don't need the useEffect hack in item-info.js anymore. * Switch to new user * Fix missing cleanup during logout If we logged in but never switched to any other account, the 'multi_auth.user-id' cookie was not set. This meant that during logout, the other 'multi_auth.*' cookies were not deleted. This broke the account switch modal. This is fixed by setting the 'multi_auth.user-id' cookie on login. Additionally, we now cleanup if cookie pointer OR session is set (instead of only if both are set). * Fix comments in middleware * Remove unnecessary effect dependencies setState is stable and thus only noise in effect dependencies * Show but disable unavailable auth methods * make signup button consistent with others * Always reload page on switch * refine account switch styling * logout barrier --------- Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com> Co-authored-by: k00b <k00b@stacker.news>
2024-09-12 18:05:11 +00:00
const { me } = useMe()
const [generateApiKey] = useMutation(
gql`
mutation generateApiKey($id: ID!) {
generateApiKey(id: $id)
}`,
{
update (cache, { data: { generateApiKey } }) {
cache.modify({
id: 'ROOT_QUERY',
fields: {
settings (existing) {
return {
...existing,
privates: {
...existing.privates,
apiKey: generateApiKey,
authMethods: { ...existing.privates.authMethods, apiKey: true }
}
}
}
}
})
}
}
)
const toaster = useToast()
const subject = '[API Key Request] <your title here>'
const body =
encodeURI(`**[API Key Request]**
Hi, I would like to use API keys with the [Stacker News GraphQL API](/api/graphql) for the following reasons:
...
I expect to call the following GraphQL queries or mutations:
... (you can leave empty if unknown)
I estimate that I will call the GraphQL API this many times (rough estimate is fine):
... (you can leave empty if unknown)
`)
const metaLink = encodeURI(`/~meta/post?type=discussion&title=${subject}&text=${body}`)
const mailto = `mailto:hello@stacker.news?subject=${subject}&body=${body}`
// link to DM with k00b on Telegram
const telegramLink = 'https://t.me/k00bideh'
// link to DM with ek on SimpleX
const simplexLink = 'https://simplex.chat/contact#/?v=1-2&smp=smp%3A%2F%2F6iIcWT_dF2zN_w5xzZEY7HI2Prbh3ldP07YTyDexPjE%3D%40smp10.simplex.im%2FxNnPk9DkTbQJ6NckWom9mi5vheo_VPLm%23%2F%3Fv%3D1-2%26dh%3DMCowBQYDK2VuAyEAnFUiU0M8jS1JY34LxUoPr7mdJlFZwf3pFkjRrhprdQs%253D%26srv%3Drb2pbttocvnbrngnwziclp2f4ckjq65kebafws6g4hy22cdaiv5dwjqd.onion'
return (
<>
<div className='form-label mt-3'>api key</div>
<div className='mt-2 d-flex align-items-center'>
<OverlayTrigger
placement='bottom'
overlay={!enabled ? <Tooltip>{apiKey ? 'you can have only one API key at a time' : 'request access to API keys in ~meta'}</Tooltip> : <></>}
trigger={['hover', 'focus']}
>
<div>
<Button
disabled={!enabled}
variant={apiKey ? 'danger' : 'secondary'}
onClick={async () => {
if (apiKey) {
showModal((onClose) => <ApiKeyDeleteObstacle onClose={onClose} />)
return
}
try {
const { data } = await generateApiKey({ variables: { id: me.id } })
const { generateApiKey: apiKey } = data
showModal(() => <ApiKeyModal apiKey={apiKey} />, { keepOpen: true })
} catch (err) {
console.error(err)
toaster.danger('error generating api key')
}
}}
>{apiKey ? 'Delete' : 'Generate'} API key
</Button>
</div>
</OverlayTrigger>
<Info>
<ul>
<li>use API keys with our <Link target='_blank' href='/api/graphql'>GraphQL API</Link> for authentication</li>
<li>you need to add the API key to the <span className='text-monospace'>X-API-Key</span> header of your requests</li>
<li>you can currently only generate API keys if we enabled it for your account</li>
<li>
you can{' '}
<Link target='_blank' href={metaLink} rel='noreferrer'>create a post in ~meta</Link> to request access
or reach out to us via
<ul>
<li><Link target='_blank' href={mailto} rel='noreferrer'>email</Link></li>
<li><Link target='_blank' href={telegramLink} rel='noreferrer'>Telegram</Link></li>
<li><Link target='_blank' href={simplexLink} rel='noreferrer'>SimpleX</Link></li>
</ul>
</li>
<li>please include following information in your request:
<ul>
<li>your nym on SN</li>
<li>what you want to achieve with authenticated API access</li>
<li>which GraphQL queries or mutations you expect to call</li>
<li>your (rough) estimate how often you will call the GraphQL API</li>
</ul>
</li>
</ul>
</Info>
</div>
</>
)
}
2024-03-25 00:46:12 +00:00
function ApiKeyModal ({ apiKey }) {
return (
<>
<p className='fw-bold'>
Make sure to copy your API key now.<br />
This is the only time we will show it to you.
</p>
<CopyInput readOnly noForm placeholder={apiKey} hint={<>use the <span className='text-monospace'>X-API-Key</span> header to include this key in your requests</>} />
</>
)
}
2024-03-26 21:07:55 +00:00
function ApiKeyDeleteObstacle ({ onClose }) {
Account Switching (#644) * WIP: Account switching * Fix empty USER query ANON_USER_ID was undefined and thus the query for @anon had no variables. * Apply multiAuthMiddleware in /api/graphql * Fix 'you must be logged in' query error on switch to anon * Add smart 'switch account' button "smart" means that it only shows if there are accounts to which one can switch * Fix multiAuth not set in backend * Comment fixes, minor changes * Use fw-bold instead of 'selected' * Close dropdown and offcanvas Inside a dropdown, we can rely on autoClose but need to wrap the buttons with <Dropdown.Item> for that to work. For the offcanvas, we need to pass down handleClose. * Use button to add account * Some pages require hard reload on account switch * Reinit settings form on account switch * Also don't refetch WalletHistory * Formatting * Use width: fit-content for standalone SignUpButton * Remove unused className * Use fw-bold and text-underline on selected * Fix inconsistent padding of login buttons * Fix duplicate redirect from /settings on anon switch * Never throw during refetch * Throw errors which extend GraphQLError * Only use meAnonSats if logged out * Use reactive variable for meAnonSats The previous commit broke the UI update after anon zaps because we actually updated item.meSats in the cache and not item.meAnonSats. Updating item.meAnonSats was not possible because it's a local field. For that, one needs to use reactive variables. We do this now and thus also don't need the useEffect hack in item-info.js anymore. * Switch to new user * Fix missing cleanup during logout If we logged in but never switched to any other account, the 'multi_auth.user-id' cookie was not set. This meant that during logout, the other 'multi_auth.*' cookies were not deleted. This broke the account switch modal. This is fixed by setting the 'multi_auth.user-id' cookie on login. Additionally, we now cleanup if cookie pointer OR session is set (instead of only if both are set). * Fix comments in middleware * Remove unnecessary effect dependencies setState is stable and thus only noise in effect dependencies * Show but disable unavailable auth methods * make signup button consistent with others * Always reload page on switch * refine account switch styling * logout barrier --------- Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com> Co-authored-by: k00b <k00b@stacker.news>
2024-09-12 18:05:11 +00:00
const { me } = useMe()
2024-03-26 21:07:55 +00:00
const [deleteApiKey] = useMutation(
gql`
mutation deleteApiKey($id: ID!) {
deleteApiKey(id: $id) {
id
}
}`,
{
update (cache, { data: { deleteApiKey } }) {
cache.modify({
id: 'ROOT_QUERY',
fields: {
settings (existing) {
return {
...existing,
privates: {
...existing.privates,
authMethods: { ...existing.privates.authMethods, apiKey: false }
}
}
}
}
})
}
}
)
const toaster = useToast()
return (
2024-04-16 20:33:00 +00:00
<div className='m-auto' style={{ maxWidth: 'fit-content' }}>
2024-03-26 21:07:55 +00:00
<p className='fw-bold'>
Do you really want to delete your API key?
</p>
<div className='d-flex flex-row justify-content-end'>
<Button
variant='danger' onClick={async () => {
try {
await deleteApiKey({ variables: { id: me.id } })
onClose()
} catch (err) {
console.error(err)
toaster.danger('error deleting api key')
}
}}
>do it
</Button>
</div>
</div>
)
}
const ZapUndosField = () => {
2024-03-25 00:46:12 +00:00
const [checkboxField] = useField({ name: 'zapUndosEnabled' })
return (
<>
<Checkbox
name='zapUndosEnabled'
groupClassName='mb-0'
2024-03-25 00:46:12 +00:00
label={
<div className='d-flex align-items-center'>
zap undos
<Info>
<ul>
<li>After every zap that exceeds or is equal to the threshold, the bolt will pulse</li>
<li>You can undo the zap if you click the bolt while it's pulsing</li>
<li>The bolt will pulse for {ZAP_UNDO_DELAY_MS / 1000} seconds</li>
</ul>
</Info>
</div>
}
/>
{checkboxField.value &&
<Input
name='zapUndos'
append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
hint={<small className='text-muted'>threshold at which undos will be possible</small>}
groupClassName='mt-1'
/>}
</>
)
}
const TipRandomField = () => {
const [tipRandomField] = useField({ name: 'tipRandom' })
const [tipRandomMinField] = useField({ name: 'tipRandomMin' })
const [tipRandomMaxField] = useField({ name: 'tipRandomMax' })
return (
<>
<Checkbox
name='tipRandom'
groupClassName='mb-0'
label={
<div className='d-flex align-items-center'>
random zaps
<Info>
<ul>
<li>Set a minimum and maximum zap amount</li>
<li>Each time you zap something, a random amount of sats between your minimum and maximum will be zapped</li>
<li>If this setting is enabled, it will ignore your default zap amount</li>
</ul>
</Info>
</div>
2024-03-25 00:46:12 +00:00
}
/>
{tipRandomField.value &&
<>
<Input
type='number'
label='minimum random zap'
name='tipRandomMin'
disabled={!tipRandomField.value}
groupClassName='mb-1'
required
autoFocus
max={tipRandomMaxField.value ? tipRandomMaxField.value - 1 : undefined}
append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
/>
<Input
type='number'
label='maximum random zap'
name='tipRandomMax'
disabled={!tipRandomField.value}
required
autoFocus
min={tipRandomMinField.value ? tipRandomMinField.value + 1 : undefined}
append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
/>
</>}
</>
2024-03-25 00:46:12 +00:00
)
}