Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: profile credential form #186

Merged
merged 2 commits into from
Oct 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ const Identifier = () => {
IDIDManager & IResolver & IIdentifierProfilePlugin
>()

const { data: profile } = useQuery(['profile', id, agent?.context.id], () =>
const { data: profile } = useQuery(['identifierProfile', {
did: id, agentId: agent?.context.id
}], () =>
agent?.getIdentifierProfile({ did: id }),
)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
/* eslint-disable */

import React, { useEffect, useState } from 'react';
import React from 'react';
import { IIdentifierHoverComponentProps } from "@veramo-community/agent-explorer-plugin";
import { IDataStoreORM } from '@veramo/core-types';
import { useVeramo } from '@veramo-community/veramo-react';
Expand All @@ -23,8 +21,7 @@ export const IdentifierHoverComponent: React.FC<IIdentifierHoverComponentProps>
const { data: profileCredentials, isLoading } = useQuery(
[
'identifierProfileCredentials',
did,
{ agentId: agent?.context.name },
{ did, agentId: agent?.context.id },
],
() =>
agent?.dataStoreORMGetVerifiableCredentials(
Expand Down Expand Up @@ -58,6 +55,8 @@ export const IdentifierHoverComponent: React.FC<IIdentifierHoverComponentProps>

if (isLoading) return <Spin />

if (Object.keys(profile).length === 0) return null

return (
<Space direction='vertical'>
<Space direction='horizontal'>
Expand Down
110 changes: 110 additions & 0 deletions packages/agent-explore/src/plugins/profile/IdentifierTabComponent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import React, { useState } from 'react';
import { IIdentifierHoverComponentProps, usePlugins } from "@veramo-community/agent-explorer-plugin";
import { IDataStoreORM } from '@veramo/core-types';
import { useVeramo } from '@veramo-community/veramo-react';
import { Button, Col, Row, Space } from 'antd';
import { ProfileForm } from './ProfileForm';
import { useQueryClient } from 'react-query'
type IProfileInfo = {
name?: string
bio?: string
email?: string
picture?: string
twitter?: string
github?: string
}

export const IdentifierTabComponent: React.FC<IIdentifierHoverComponentProps> = ({did}) => {
const { agent } = useVeramo<IDataStoreORM>()
const { plugins } = usePlugins()
const [ showForm, setShowForm ] = useState(false)
const queryClient = useQueryClient()



const hoverComponents = React.useMemo(() => {
const components: React.FC<IIdentifierHoverComponentProps>[] = []
plugins.forEach((plugin) => {
if (plugin.config?.enabled && plugin.getIdentifierHoverComponent) {
const Component = plugin.getIdentifierHoverComponent()
if (Component) {
components.push(Component)
}
}
})
return components
}, [plugins])

const handleProfileSubmit = async (issuer: string, values: IProfileInfo) => {
console.log('values', values)
if (values.name || values.email || values.bio || values.github || values.twitter || values.picture) {
console.log('submitting profile', values)
const credentialSubject: any = {
id: did,
}
if (values.name) credentialSubject['name'] = values.name
if (values.email) credentialSubject['email'] = values.email
if (values.bio) credentialSubject['bio'] = values.bio
if (values.github) credentialSubject['github'] = values.github
if (values.twitter) credentialSubject['twitter'] = values.twitter
if (values.picture) credentialSubject['picture'] = values.picture
const credential = await agent?.createVerifiableCredential({
credential: {
issuer: { id: issuer },
issuanceDate: new Date().toISOString(),
type: ['VerifiableCredential', 'Profile'],
credentialSubject,
},
proofFormat: 'jwt',
})
if (credential) {
await agent?.dataStoreSaveVerifiableCredential({
verifiableCredential: credential,
})
queryClient.invalidateQueries({
queryKey: [
'identifierProfileCredentials',
{did, agentId: agent?.context.id}
]
})
queryClient.invalidateQueries({
queryKey: [
'identifierProfile',
{did, agentId: agent?.context.id}
]
})
}

}
setShowForm(false)
}

return (
<>
<Row>
<Col md={6}/>
<Col
md={12}
xs={24}
style={{position: 'relative'}}
>
{!showForm && <Space direction='vertical'>
{!showForm && hoverComponents.map((Component, index) => (
React.createElement(Component, { key: index, did: did })
))}
<Button
type='text'
onClick={() => setShowForm(true)}
style={{position: 'absolute', top: 0, right: 0}}
>Edit</Button>
</Space>}
{showForm && <ProfileForm onProfileSubmit={handleProfileSubmit}/>}

</Col>
<Col md={6}/>
</Row>
</>
)
}


119 changes: 119 additions & 0 deletions packages/agent-explore/src/plugins/profile/ProfileForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import React from 'react'
import { App, Col, Form, Input, Row, Upload } from 'antd'
import { GithubOutlined, LoadingOutlined, MailOutlined, PlusOutlined, TwitterOutlined } from '@ant-design/icons'
import type { RcFile } from 'antd/es/upload/interface';
import { ActionButton } from '@veramo-community/agent-explorer-plugin';

export interface ProfileFormValues {
name?: string
email?: string
bio?: string
github?: string
twitter?: string
picture?: string
}

interface ProfileFormProps {
onProfileSubmit: (did: string, values: ProfileFormValues) => void
}

const getBase64 = (img: RcFile, callback: (url: string) => void) => {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result as string));
reader.readAsDataURL(img);
};


export const ProfileForm: React.FC<ProfileFormProps> = ({
onProfileSubmit,
}) => {
const { notification } = App.useApp()
const [form] = Form.useForm()

const [loading, setLoading] = React.useState(false);
const picture = Form.useWatch('picture', {form, preserve:true});

const beforeUpload = (file: RcFile) => {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
notification.error({ message: 'You can only upload JPG/PNG file!'});
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
notification.error({ message: 'Image must smaller than 2MB!'});
}

getBase64(file as RcFile, (url) => {
setLoading(false);
form.setFieldValue('picture', url);
});

return false
};

const uploadButton = (
<div>
{loading ? <LoadingOutlined /> : <PlusOutlined />}
<div style={{ marginTop: 8 }}>Picture</div>
</div>
);

const handleOk = (did: string) => {
form
.validateFields()
.then((values) => {
form.resetFields()
onProfileSubmit(did, values)
})
.catch((info) => {
console.log('Validate Failed:', info)
})
}

return (
<Form
form={form}
layout="vertical"
name="form_in_form"
initialValues={{
}}
>
<Row justify={'center'}>
<Col >

<Upload
name="avatar"
listType="picture-circle"
showUploadList={false}
beforeUpload={beforeUpload}
onChange={() => {console.log('changed')}}
>
{picture ? <img src={picture} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
</Upload>
</Col>
</Row>

<Form.Item name="picture" hidden>
<Input />
</Form.Item>
<Form.Item name="name" label="Name" required={false}>
<Input />
</Form.Item>
<Form.Item name="bio" label="Bio">
<Input.TextArea rows={2}/>
</Form.Item>
<Form.Item name="email" label="Email">
<Input prefix={<MailOutlined className="site-form-item-icon" />}/>
</Form.Item>
<Form.Item name="twitter" label="Twitter">
<Input prefix={<TwitterOutlined className="site-form-item-icon" />}/>
</Form.Item>
<Form.Item name="github" label="Github">
<Input prefix={<GithubOutlined className="site-form-item-icon" />}/>
</Form.Item>
<ActionButton title='Save' onAction={(did) => handleOk(did)} />

</Form>

)
}
8 changes: 7 additions & 1 deletion packages/agent-explore/src/plugins/profile/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { IPlugin } from '@veramo-community/agent-explorer-plugin';
import { IdentifierHoverComponent } from './IdentifierHoverComponent';
import { IdentifierTabComponent } from './IdentifierTabComponent';
import { UniqueVerifiableCredential } from '@veramo/core-types';
import { Profile } from './Profile';

Expand All @@ -20,7 +21,12 @@ const Plugin: IPlugin = {
}
return undefined
},

getIdentifierTabsComponents: () => [
{
label: 'Profile',
component: IdentifierTabComponent,
},
],
}
}
};
Expand Down
43 changes: 26 additions & 17 deletions packages/plugin/src/PluginProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { createContext, useState, useEffect, useContext } from 'react'
import { IAgentExplorerPlugin, IAgentExplorerPluginConfig, IPlugin } from './types.js'
import { App } from 'antd'

type PluginContextType = {
plugins: IAgentExplorerPlugin[]
Expand Down Expand Up @@ -54,6 +55,7 @@ export type PluginProviderProps = {

const PluginProvider = (props: PluginProviderProps) => {

const { notification } = App.useApp()
const [pluginConfigs, setPluginConfigs] = useState<IAgentExplorerPluginConfig[]>(
getStoredPluginConfigs(props.corePlugins || []),
)
Expand All @@ -71,25 +73,32 @@ const PluginProvider = (props: PluginProviderProps) => {
result.push(plugin)
}
} else {
const module = await import(/* webpackIgnore: true */ config.url)
const plugin = module.default.init() as IAgentExplorerPlugin
plugin.config = config
result.push(plugin)
//FIXME
if (plugin.hasCss && config.enabled) {
const cssUrl = config.url.replace('plugin.js', 'plugin.css')
try {
const cssResponse = await fetch(cssUrl)
if (cssResponse.ok) {
const css = await cssResponse.text()
const style = document.createElement('style')
style.type = 'text/css'
style.appendChild(document.createTextNode(css))
document.head.appendChild(style)
try {
const module = await import(/* webpackIgnore: true */ config.url)
const plugin = module.default.init() as IAgentExplorerPlugin
plugin.config = config
result.push(plugin)
//FIXME
if (plugin.hasCss && config.enabled) {
const cssUrl = config.url.replace('plugin.js', 'plugin.css')
try {
const cssResponse = await fetch(cssUrl)
if (cssResponse.ok) {
const css = await cssResponse.text()
const style = document.createElement('style')
style.type = 'text/css'
style.appendChild(document.createTextNode(css))
document.head.appendChild(style)
}
} catch (e) {
//do nothing
}
} catch (e) {
//do nothing
}
} catch (e: any) {
notification.error({
message: `Error loading plugin ${config.url}`,
description: e.message,
})
}
}
}
Expand Down
22 changes: 16 additions & 6 deletions packages/plugin/src/agent-plugins/IdentifierProfilePlugin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export class IdentifierProfilePlugin implements IAgentPlugin {
args: IGetIdentifierProfileArgs,
context: IContext,
): Promise<IIdentifierProfile> {

if (!args.did) return Promise.reject('DID Required')

const GRAVATAR_URI = 'https://www.gravatar.com/avatar/'
Expand All @@ -52,21 +53,30 @@ export class IdentifierProfilePlugin implements IAgentPlugin {
.includes('dataStoreORMGetVerifiableCredentials')
) {
try {
const result = await context.agent.dataStoreORMGetVerifiableCredentials(
const profileCredentials = await context.agent.dataStoreORMGetVerifiableCredentials(
{
where: [
{ column: 'type', value: ['VerifiableCredential,Profile'] },
{ column: 'subject', value: [args.did] },
],
order: [{ column: 'issuanceDate', direction: 'DESC' }],
order: [{ column: 'issuanceDate', direction: 'ASC' }],
},
)
const profile: {
name?: string
picture?: string
} = {}
if (profileCredentials && profileCredentials.length > 0) {
for (const credential of profileCredentials) {
const { name, bio, email, picture, twitter, github }
= credential.verifiableCredential.credentialSubject
if (name) profile.name = name
if (picture) profile.picture = picture
}

if (result.length > 0) {
const { name, picture } =
result[0].verifiableCredential.credentialSubject
return { did: args.did, name, picture: picture || fallBackPictureUrl }
return { did: args.did, name: profile.name, picture: profile.picture || fallBackPictureUrl }
}

} catch (e) {
console.log(e)
}
Expand Down
Loading