Compare commits

..

3 Commits

Author SHA1 Message Date
c89e96b824 chore: added comment
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 31s
2024-11-04 22:04:27 +01:00
22debeb033 chore(git): Merge branch 'staging' into issue-232
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-11-04 14:28:27 +01:00
0008e98146 feat: Add Sigit ID as a Path Param to /verify
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 29s
2024-11-04 13:35:06 +01:00
8 changed files with 111 additions and 351 deletions

View File

@ -1,5 +1,5 @@
import { useEffect } from 'react'
import { useAppSelector } from './hooks/store'
import { useAppSelector } from './hooks'
import { Navigate, Route, Routes } from 'react-router-dom'
import { AuthController } from './controllers'
import { MainLayout } from './layouts/Main'
@ -29,9 +29,11 @@ const App = () => {
const handleRootRedirect = () => {
if (authState.loggedIn) return appPrivateRoutes.homePage
const callbackPathEncoded = btoa(
window.location.href.split(`${window.location.origin}/#`)[1]
)
return `${appPublicRoutes.login}?callbackPath=${callbackPathEncoded}`
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 186 KiB

View File

@ -42,8 +42,7 @@ export const DisplaySigit = ({
<div className={styles.itemWrapper}>
{signedStatus === SigitStatus.Complete && (
<Link
to={appPublicRoutes.verify}
state={{ meta }}
to={`${appPublicRoutes.verify}/${sigitCreateId}`}
className={styles.insetLink}
></Link>
)}

View File

@ -14,7 +14,6 @@ import {
compareObjects,
getAuthToken,
getRelayMap,
getVisitedLink,
saveAuthToken,
unixNow
} from '../utils'
@ -91,21 +90,33 @@ export class AuthController {
store.dispatch(setRelayMapAction(relayMap.map))
}
const currentLocation = window.location.hash.replace('#', '')
/**
* This block was added before we started using the `nostr-login` package
* At this point it seems it's not needed anymore and it's even blocking the flow (reloading on /verify)
* TODO to remove this if app works fine
*/
// const currentLocation = window.location.hash.replace('#', '')
if (!Object.values(appPrivateRoutes).includes(currentLocation)) {
// User did change the location to one of the private routes
const visitedLink = getVisitedLink()
if (visitedLink) {
const { pathname, search } = visitedLink
return Promise.resolve(`${pathname}${search}`)
} else {
// Navigate user in
return Promise.resolve(appPrivateRoutes.homePage)
}
}
// if (!Object.values(appPrivateRoutes).includes(currentLocation)) {
// // Since verify is both public and private route, we don't use the `visitedLink`
// // value for it. Otherwise, when linking to /verify/:id we get redirected
// // to the root `/`
// if (currentLocation.includes(appPublicRoutes.verify)) {
// return Promise.resolve(currentLocation)
// }
//
// // User did change the location to one of the private routes
// const visitedLink = getVisitedLink()
//
// if (visitedLink) {
// const { pathname, search } = visitedLink
//
// return Promise.resolve(`${pathname}${search}`)
// } else {
// // Navigate user in
// return Promise.resolve(appPrivateRoutes.homePage)
// }
// }
}
checkSession() {

View File

@ -1,17 +1,10 @@
import styles from './style.module.scss'
import {
Box,
Button,
CircularProgress,
FormHelperText,
TextField,
Tooltip
} from '@mui/material'
import { Button, FormHelperText, TextField, Tooltip } from '@mui/material'
import type { Identifier, XYCoord } from 'dnd-core'
import saveAs from 'file-saver'
import JSZip from 'jszip'
import { Event, kinds } from 'nostr-tools'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { DndProvider, useDrag, useDrop } from 'react-dnd'
import { MultiBackend } from 'react-dnd-multi-backend'
import { HTML5toTouch } from 'rdndmb-html5-to-touch'
@ -20,20 +13,16 @@ import { useLocation, useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import { UserAvatar } from '../../components/UserAvatar'
import {
MetadataController,
NostrController,
RelayController
} from '../../controllers'
import { MetadataController, NostrController } from '../../controllers'
import { appPrivateRoutes } from '../../routes'
import {
CreateSignatureEventContent,
KeyboardCode,
Meta,
ProfileMetadata,
SignedEvent,
User,
UserRole
UserRole,
KeyboardCode
} from '../../types'
import {
encryptArrayBuffer,
@ -69,19 +58,13 @@ import {
faGripLines,
faPen,
faPlus,
faSearch,
faToolbox,
faTrash,
faUpload
} from '@fortawesome/free-solid-svg-icons'
import { getSigitFile, SigitFile } from '../../utils/file.ts'
import _ from 'lodash'
import { generateTimestamp } from '../../utils/opentimestamps.ts'
import { Autocomplete } from '@mui/lab'
import _, { truncate } from 'lodash'
import * as React from 'react'
import { AvatarIconButton } from '../../components/UserAvatarIconButton'
type FoundUser = Event & { npub: string }
export const CreatePage = () => {
const navigate = useNavigate()
@ -104,16 +87,23 @@ export const CreatePage = () => {
}
const [userInput, setUserInput] = useState('')
const [userSearchInput, setUserSearchInput] = useState('')
const [userRole] = useState<UserRole>(UserRole.signer)
const handleInputKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
if (
event.code === KeyboardCode.Enter ||
event.code === KeyboardCode.NumpadEnter
) {
event.preventDefault()
handleAddUser()
}
}
const [userRole, setUserRole] = useState<UserRole>(UserRole.signer)
const [error, setError] = useState<string>()
const [users, setUsers] = useState<User[]>([])
const signers = users.filter((u) => u.role === UserRole.signer)
const viewers = users.filter((u) => u.role === UserRole.viewer)
const usersPubkey = useAppSelector((state) => state.auth.usersPubkey)!
const usersPubkey = useAppSelector((state) => state.auth.usersPubkey)
const nostrController = NostrController.getInstance()
@ -122,129 +112,10 @@ export const CreatePage = () => {
)
const [drawnFiles, setDrawnFiles] = useState<SigitFile[]>([])
const [parsingPdf, setIsParsing] = useState<boolean>(false)
const searchFieldRef = useRef<HTMLInputElement>(null)
const [selectedTool, setSelectedTool] = useState<DrawTool>()
const [foundUsers, setFoundUsers] = useState<FoundUser[]>([])
const [searchUsersLoading, setSearchUsersLoading] = useState<boolean>(false)
const [pastedUserNpubOrNip05, setPastedUserNpubOrNip05] = useState<
string | undefined
>()
/**
* Fired when user select
*/
const handleSearchUserChange = useCallback(
(_event: React.SyntheticEvent, value: string | FoundUser | null) => {
if (typeof value === 'object') {
const ndkEvent = value as FoundUser
if (ndkEvent?.pubkey) {
setUserInput(hexToNpub(ndkEvent.pubkey))
}
}
},
[setUserInput]
)
const handleSearchUsers = async (searchValue?: string) => {
const searchString = searchValue || userSearchInput || undefined
if (!searchString) return
setSearchUsersLoading(true)
const relayController = RelayController.getInstance()
const metadataController = MetadataController.getInstance()
const relaySet = await metadataController.findRelayListMetadata(usersPubkey)
const searchTerm = searchString.trim()
relayController
.fetchEvents(
{
kinds: [0],
search: searchTerm
},
[...relaySet.write]
)
.then((events) => {
console.log('events', events)
const fineFilteredEvents: FoundUser[] = events
.filter((event) => {
const lowercaseContent = event.content.toLowerCase()
return (
lowercaseContent.includes(
`"name":"${searchTerm.toLowerCase()}"`
) ||
lowercaseContent.includes(
`"display_name":"${searchTerm.toLowerCase()}"`
) ||
lowercaseContent.includes(
`"username":"${searchTerm.toLowerCase()}"`
) ||
lowercaseContent.includes(`"nip05":"${searchTerm.toLowerCase()}"`)
)
})
.reduce((uniqueEvents: FoundUser[], event: Event) => {
if (!uniqueEvents.some((e: Event) => e.pubkey === event.pubkey)) {
uniqueEvents.push({
...event,
npub: hexToNpub(event.pubkey)
})
}
return uniqueEvents
}, [])
console.log('fineFilteredEvents', fineFilteredEvents)
setFoundUsers(fineFilteredEvents)
})
.catch((error) => {
console.error(error)
})
.finally(() => {
setSearchUsersLoading(false)
})
}
useEffect(() => {
setTimeout(() => {
if (foundUsers.length) {
if (searchFieldRef.current) {
searchFieldRef.current.blur()
searchFieldRef.current.focus()
}
}
})
}, [foundUsers])
const handleInputKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
if (
event.code === KeyboardCode.Enter ||
event.code === KeyboardCode.NumpadEnter
) {
event.preventDefault()
// If pasted user npub of nip05 is present, we just add the user to the counterparts list
if (pastedUserNpubOrNip05) {
setUserInput(pastedUserNpubOrNip05)
setPastedUserNpubOrNip05(undefined)
} else {
// Otherwize if search already provided some results, user must manually click the search button
if (!foundUsers.length) {
handleSearchUsers()
}
}
}
}
useEffect(() => {
if (selectedFiles) {
/**
* Reads the binary files and converts to an internal file type
* Reads the binary files and converts to internal file type
* and sets to a state (adds images if it's a PDF)
*/
const parsePages = async () => {
@ -264,6 +135,8 @@ export const CreatePage = () => {
}
}, [selectedFiles])
const [selectedTool, setSelectedTool] = useState<DrawTool>()
/**
* Changes the drawing tool
* @param drawTool to draw with
@ -336,7 +209,7 @@ export const CreatePage = () => {
}
}, [usersPubkey])
const handleAddUser = useCallback(async () => {
const handleAddUser = async () => {
setError(undefined)
const addUser = (pubkey: string) => {
@ -378,8 +251,6 @@ export const CreatePage = () => {
const input = userInput.toLowerCase()
setUserSearchInput('')
if (input.startsWith('npub')) {
return handleAddNpubUser(input)
}
@ -429,20 +300,7 @@ export const CreatePage = () => {
}
return
}
}, [
userInput,
userRole,
setError,
setUsers,
setUserSearchInput,
setIsLoading,
setLoadingSpinnerDesc,
setUserInput
])
useEffect(() => {
if (userInput?.length > 0) handleAddUser()
}, [handleAddUser, userInput])
}
const handleUserRoleChange = (role: UserRole, pubkey: string) => {
setUsers((prevUsers) =>
@ -931,61 +789,6 @@ export const CreatePage = () => {
}
}
/**
* Handles the user search textfield change
* If it's not valid npub or nip05, search will be automatically triggered
*/
const handleSearchAutocompleteTextfieldChange = async (
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
) => {
const value = e.target.value
const disarmAddOnEnter = () => {
setPastedUserNpubOrNip05(undefined)
}
// Seems like it's npub format
if (value.startsWith('npub')) {
// We will try to convert npub to hex and if it's successfull that means
// npub is valid
const validHexPubkey = npubToHex(value)
if (validHexPubkey) {
// Arm the manual user npub add after enter is hit, we don't want to trigger search
setPastedUserNpubOrNip05(value)
} else {
disarmAddOnEnter()
}
} else if (value.includes('@')) {
// Seems like it's nip05 format
const { pubkey } = await queryNip05(value).catch((err) => {
console.error(err)
return { pubkey: null }
})
if (pubkey) {
// Arm the manual user npub add after enter is hit, we don't want to trigger search
setPastedUserNpubOrNip05(hexToNpub(pubkey))
} else {
disarmAddOnEnter()
}
} else {
// Disarm the add user on enter hit, and trigger search after 1 second
disarmAddOnEnter()
}
setUserSearchInput(value)
}
const parseContent = (event: Event) => {
try {
return JSON.parse(event.content)
} catch (e) {
return undefined
console.error(e)
}
}
return (
<>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
@ -1049,108 +852,42 @@ export const CreatePage = () => {
moveSigner={moveSigner}
/>
</div>
<div className={styles.addCounterpart}>
<div className={styles.inputWrapper}>
<Autocomplete
sx={{ width: 300 }}
options={foundUsers}
onChange={handleSearchUserChange}
inputValue={userSearchInput}
disableClearable
openOnFocus
autoHighlight
freeSolo
filterOptions={(x) => x}
getOptionLabel={(option) => {
let label: string = (option as FoundUser).npub
const contentJson = parseContent(option as FoundUser)
if (contentJson?.name) {
label = contentJson.name
} else {
label = option as string
}
return label
}}
renderOption={(props, option) => {
const { ...optionProps } = props
const contentJson = parseContent(option)
return (
<Box
component="li"
sx={{ '& > img': { mr: 2, flexShrink: 0 } }}
{...optionProps}
key={option.pubkey}
>
<AvatarIconButton
src={contentJson.picture}
hexKey={option.pubkey}
color="inherit"
sx={{
padding: '0 10px 0 0'
}}
/>
<div>
{contentJson.name}{' '}
{usersPubkey === option.pubkey ? (
<span
style={{
color: '#4c82a3',
fontWeight: 'bold'
}}
>
Me
</span>
) : (
''
)}{' '}
({truncate(option.npub, { length: 16 })})
</div>
</Box>
)
}}
renderInput={(params) => (
<TextField
{...params}
key={params.id}
inputRef={searchFieldRef}
label="Add/Search counterpart"
onKeyDown={handleInputKeyDown}
onChange={handleSearchAutocompleteTextfieldChange}
/>
)}
<TextField
fullWidth
placeholder="Add counterpart"
value={userInput}
onChange={(e) => setUserInput(e.target.value)}
onKeyDown={handleInputKeyDown}
error={!!error}
/>
</div>
{!pastedUserNpubOrNip05 ? (
<Button
disabled={!userSearchInput || searchUsersLoading}
onClick={() => handleSearchUsers()}
variant="contained"
aria-label="Add"
className={styles.counterpartToggleButton}
>
{searchUsersLoading ? (
<CircularProgress size={14} />
) : (
<FontAwesomeIcon icon={faSearch} />
)}
</Button>
) : (
<Button
onClick={handleAddUser}
variant="contained"
aria-label="Add"
className={styles.counterpartToggleButton}
>
<FontAwesomeIcon icon={faPlus} />
</Button>
)}
<Button
onClick={() =>
setUserRole(
userRole === UserRole.signer
? UserRole.viewer
: UserRole.signer
)
}
variant="contained"
aria-label="Toggle User Role"
className={styles.counterpartToggleButton}
>
<FontAwesomeIcon
icon={userRole === UserRole.signer ? faPen : faEye}
/>
</Button>
<Button
disabled={!userInput}
onClick={handleAddUser}
variant="contained"
aria-label="Add"
className={styles.counterpartToggleButton}
>
<FontAwesomeIcon icon={faPlus} />
</Button>
</div>
<div className={`${styles.paperGroup} ${styles.toolbox}`}>

View File

@ -26,10 +26,10 @@ import {
sendNotification
} from '../../utils'
import styles from './style.module.scss'
import { useLocation } from 'react-router-dom'
import { useLocation, useParams } from 'react-router-dom'
import axios from 'axios'
import { FONT_SIZE, FONT_TYPE, inPx } from '../../utils/pdf.ts'
import { useAppSelector } from '../../hooks/store'
import { useAppSelector } from '../../hooks'
import { getLastSignersSig } from '../../utils/sign.ts'
import { saveAs } from 'file-saver'
import { Container } from '../../components/Container'
@ -165,6 +165,9 @@ const SlimPdfView = ({
export const VerifyPage = () => {
const location = useLocation()
const params = useParams()
const usersAppData = useAppSelector((state) => state.userAppData)
const usersPubkey = useAppSelector((state) => state.auth.usersPubkey)
const nostrController = NostrController.getInstance()
@ -176,8 +179,27 @@ export const VerifyPage = () => {
* uploadedZip will be received from home page when a user uploads a sigit zip wrapper that contains meta.json
* meta will be received in navigation from create & home page in online mode
*/
const { uploadedZip, meta: metaInNavState } = location.state || {}
let metaInNavState = location?.state?.meta || undefined
const { uploadedZip } = location.state || {}
const [selectedFile, setSelectedFile] = useState<File | null>(null)
/**
* If `userAppData` is present it means user is logged in and we can extract list of `sigits` from the store.
* If ID is present in the URL we search in the `sigits` list
* Otherwise sigit is set from the `location.state.meta`
*/
if (usersAppData) {
const sigitCreateId = params.id
if (sigitCreateId) {
const sigit = usersAppData.sigits[sigitCreateId]
if (sigit) {
metaInNavState = sigit
}
}
}
useEffect(() => {
if (uploadedZip) {
setSelectedFile(uploadedZip)
@ -185,6 +207,7 @@ export const VerifyPage = () => {
}, [uploadedZip])
const [meta, setMeta] = useState<Meta>(metaInNavState)
const {
submittedBy,
zipUrl,

View File

@ -90,7 +90,7 @@ export const publicRoutes: PublicRouteProps[] = [
element: <ProfilePage />
},
{
path: appPublicRoutes.verify,
path: `${appPublicRoutes.verify}/:id?`,
element: <VerifyPage />
}
]

View File

@ -2,18 +2,6 @@ import { TimeoutError } from '../types/errors/TimeoutError.ts'
import { CurrentUserFile } from '../types/file.ts'
import { SigitFile } from './file.ts'
export const debounceCustom = <T extends (...args: never[]) => void>(
fn: T,
delay: number
): ((...args: Parameters<T>) => void) => {
let timerId: ReturnType<typeof setTimeout>
return (...args: Parameters<T>) => {
clearTimeout(timerId)
timerId = setTimeout(() => fn(...args), delay)
}
}
export const compareObjects = (
obj1: object | null | undefined,
obj2: object | null | undefined