Skip to content

Commit

Permalink
unifying the way extension/wallet name is saved
Browse files Browse the repository at this point in the history
  • Loading branch information
piggydoughnut committed Mar 11, 2024
1 parent 2b259f5 commit b93f845
Show file tree
Hide file tree
Showing 8 changed files with 60 additions and 65 deletions.
3 changes: 2 additions & 1 deletion src/client/components/auth/helper.tsx
Expand Up @@ -248,7 +248,8 @@ export const getAddressType = (address: string) => {
return 'polkadot'
}

if (address.startsWith('C')) {
const regex = /^[CDFGHJ]/i
if (regex.test(address)) {
return 'kusama'
}

Expand Down
12 changes: 7 additions & 5 deletions src/modules/users/client/components/AuthAccountsLinkModal.tsx
Expand Up @@ -15,8 +15,8 @@ export const AuthAccountsLinkModal: React.FC<{
onChoose: (addr: ExtensionAccount) => Promise<void>
onCancel: () => void
loading: boolean
linkedAccounts: Record<string, AuthAddressPair[]>
}> = ({ wallets, onChoose, onCancel, loading, linkedAccounts }) => {
linkedAddresses: string[]
}> = ({ wallets, onChoose, onCancel, loading, linkedAddresses }) => {
const [step, setStep] = useState('')
const [error, setError] = useState<JSX.Element | string>()
const [selectedAddress, setSelectedAddress] = useState('')
Expand All @@ -40,9 +40,11 @@ export const AuthAccountsLinkModal: React.FC<{
wallet.type as WalletType.INJECTED | WalletType.WALLET_CONNECT
](wallet)
setChosenWallet(wallet)
console.log(accounts)
console.log(linkedAccounts)
setAccounts(accounts)
setAccounts(
accounts.filter(
(account) => !linkedAddresses.includes(account.address)
)
)
setStep(AuthSteps.ChooseAccount)
} catch (e) {
console.error(e)
Expand Down
27 changes: 13 additions & 14 deletions src/modules/users/client/components/MySettings.tsx
Expand Up @@ -24,30 +24,21 @@ import { AuthAccountsLinkModal } from './AuthAccountsLinkModal'
import { AuthAccount } from './AuthAccount'
import { AuthAddressPair, AuthExtension } from '#shared/types'
import config from '#client/config'
import { filterOutForbiddenAuth } from '../helpers'
import { DeleteUserModal } from './DeleteUserModal'
import dayjs from 'dayjs'
import { DATE_FORMAT_DAY_NAME } from '#client/constants'
import { WalletType } from '@polkadot-onboard/core'
import { getWallets } from '#client/components/auth/helper'
import { formatName } from '#modules/users/shared-helpers'

export const MySettings: React.FC = () => {
useDocumentTitle('Settings')
// @todo move to some config?
const allowedWallets = [
'polkadot-js',
'talisman',
'subwallet-js',
'subwallet',
'novawallet',
'walletconnect',
]
const me = useStore(stores.me)
const [showModal, setShowModal] = useState(false)
const [wallets, setWallets] = useState<any>([])
const [linkedAccounts, setLinkedAccounts] = useState<
Record<string, AuthAddressPair[]>
>({})
const [linkedAddresses, setLinkedAddresses] = useState<string[]>([])
const [loading, setLoading] = useState(false)

const officeId = useStore(stores.officeId)
Expand All @@ -73,8 +64,16 @@ export const MySettings: React.FC = () => {

useEffect(() => {
if (me) {
const res = filterOutForbiddenAuth(me.authIds, allowedWallets)
setLinkedAccounts(res ?? [])
const addresses: Array<string[]> = []
const linked: Record<string, AuthAddressPair[]> = {}
Object.entries(me.authIds['polkadot']).forEach(
([walletName, authAddressPairs]) => {
linked[formatName(walletName)] = authAddressPairs
addresses.push(authAddressPairs.map((a) => a.address))
}
)
setLinkedAddresses(addresses.flat())
setLinkedAccounts(linked)
}
}, [me])

Expand Down Expand Up @@ -192,7 +191,7 @@ export const MySettings: React.FC = () => {
<AuthAccountsLinkModal
wallets={wallets}
loading={loading}
linkedAccounts={linkedAccounts}
linkedAddresses={linkedAddresses}
onChoose={async (selectedAccount: any) => {
try {
if (!selectedAccount) {
Expand Down
18 changes: 0 additions & 18 deletions src/modules/users/client/helpers/index.ts
Expand Up @@ -84,21 +84,3 @@ export const reverseGeocoding = async (
countryCode: countryCode.toUpperCase(),
}
}

export const filterOutForbiddenAuth = (
authIds: AuthIds,
allowedKeys: string[]
) => {
const res: Record<string, Array<AuthAddressPair>> = {}

const polkaDotWallets = authIds[AuthProvider.Polkadot]
if (!!polkaDotWallets) {
for (const extension of allowedKeys) {
if (polkaDotWallets[extension as AuthExtension]) {
res[extension as AuthExtension] =
polkaDotWallets[extension as AuthExtension]
}
}
}
return res
}
15 changes: 3 additions & 12 deletions src/modules/users/server/models/user.ts
Expand Up @@ -144,24 +144,15 @@ export class User
}
return addresses
}

addAuthId(
this: User,
provider: AuthProvider,
extensionName: AuthExtension,
authId: AuthAddressPair
): User {
const authIds = this.toJSON().authIds
if (!authIds[provider]) {
// @todo more general adding of authIds
authIds[provider] = {
[AuthExtension.PolkadotJs]: [],
[AuthExtension.Talisman]: [],
}
}
if (!authIds[provider][extensionName]) {
authIds[provider][extensionName] = []
}
const authIds = { ...this.toJSON().authIds }
authIds[provider] = authIds[provider] || {}
authIds[provider][extensionName] = authIds[provider][extensionName] || []
authIds[provider][extensionName].push(authId)
return this.set('authIds', authIds)
}
Expand Down
27 changes: 17 additions & 10 deletions src/modules/users/server/router.ts
Expand Up @@ -32,6 +32,7 @@ import {
} from './helpers'

import { Metadata } from '../metadata-schema'
import { allowedPolkadotAuthProviders } from '../shared-helpers'

const ROLES_ALLOWED_TO_BE_ON_MAP = appConfig.getRolesByPermission(
Permissions.UseMap
Expand Down Expand Up @@ -467,11 +468,12 @@ const userRouter: FastifyPluginCallback = async function (fastify, opts) {
reply
) => {
const authIds = req.user.authIds[PROVIDER_NAME] ?? []
const alreadyLinked = authIds[req.body.extensionName]
? authIds[req.body.extensionName].find(
(one) => one.address == req.body.address
)
: false
const alreadyLinked = Object.keys(authIds).map((name) =>
authIds[name as AuthExtension].find(
(one) => one.address == req.body.address
)
)

if (!alreadyLinked) {
return reply.throw.badParams()
}
Expand All @@ -493,11 +495,16 @@ const userRouter: FastifyPluginCallback = async function (fastify, opts) {
}>,
reply
) => {
const source: AuthExtension = req.body.extensionName
.replaceAll(' ', '')
.toLowerCase()
const extensionName = req.body.extensionName as string
const source = extensionName.replace(/ /g, '').toLowerCase()

if (!allowedPolkadotAuthProviders.includes(source)) {
return reply.throw.badParams(
'This authentication provider is not approved. Please contact administrator.'
)
}
const providerAuthIds = req.user.authIds[AuthProvider.Polkadot] ?? []
const extensionIds = providerAuthIds[source] ?? []
const extensionIds = providerAuthIds[source as AuthExtension] ?? []

if (!!Object.keys(providerAuthIds).length && extensionIds) {
const alreadyLinked = extensionIds.find(
Expand Down Expand Up @@ -526,7 +533,7 @@ const userRouter: FastifyPluginCallback = async function (fastify, opts) {
}

await req.user
.addAuthId(AuthProvider.Polkadot, source, {
.addAuthId(AuthProvider.Polkadot, source as AuthExtension, {
name: req.body.name,
address: req.body.address,
})
Expand Down
12 changes: 12 additions & 0 deletions src/modules/users/shared-helpers/index.ts
Expand Up @@ -2,6 +2,15 @@ import dayjs from 'dayjs'
import dayjsTimezone from 'dayjs/plugin/timezone'
import dayjsUtc from 'dayjs/plugin/utc'

export const allowedPolkadotAuthProviders = [
'polkadot-js',
'talisman',
'subwallet-js',
'subwallet',
'novawallet',
'walletconnect',
]

dayjs.extend(dayjsTimezone)
dayjs.extend(dayjsUtc)

Expand All @@ -23,3 +32,6 @@ export const parseGmtOffset = (timezone: string): string => {

return 'GMT'.concat(`${sign}`).concat(offsetNumber.toString())
}

export const formatName = (source: string) =>
source.replace(/ /g, '').toLowerCase()
11 changes: 6 additions & 5 deletions src/server/auth/providers/polkadot/index.ts
Expand Up @@ -3,6 +3,7 @@ import { AuthAddressPair, AuthIds, AuthProvider } from '#shared/types'
import { FastifyInstance, FastifyPluginCallback, FastifyRequest } from 'fastify'
import type { InjectedAccountWithMeta } from '@polkadot/extension-inject/types'
import { getSession, getUserByProvider, isValidSignature } from '../helper'
import { ExtensionAccount } from '#client/components/auth/helper'

export const plugin: FastifyPluginCallback = async (
fastify: FastifyInstance
Expand Down Expand Up @@ -62,14 +63,14 @@ export const plugin: FastifyPluginCallback = async (
'/register',
async (
req: FastifyRequest<{
Body: { selectedAccount: InjectedAccountWithMeta; signature: string }
Body: { selectedAccount: ExtensionAccount; signature: string }
}>,
reply
) => {
const body: InjectedAccountWithMeta = req.body.selectedAccount
const source = body.source?.replaceAll(' ', '').toLowerCase()
const body: ExtensionAccount = req.body.selectedAccount
const source = body.source?.replace(/ /g, '').toLowerCase()
// @todo move to app config?
const allowedExtensions = [
const allowedPolkadotAuthProviders = [
'polkadot-js',
'talisman',
'subwallet-js',
Expand All @@ -78,7 +79,7 @@ export const plugin: FastifyPluginCallback = async (
'walletconnect',
]

if (!allowedExtensions.includes(source)) {
if (!allowedPolkadotAuthProviders.includes(source)) {
return reply.throw.conflict('Unsupported extension')
}

Expand Down

0 comments on commit b93f845

Please sign in to comment.