Skip to content

Commit

Permalink
More XX fixes, correct address logged in console now
Browse files Browse the repository at this point in the history
  • Loading branch information
armchairancap committed Oct 16, 2024
1 parent 47baf49 commit 7530878
Show file tree
Hide file tree
Showing 5 changed files with 102 additions and 67 deletions.
2 changes: 0 additions & 2 deletions components/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import AccountSelect from './account-select';
import { useRouter } from 'next/router';

// AA
import { stringToHex, stringToU8a, u8aToHex } from "@polkadot/util";
// import { wrapBytes } from '@polkadot/extension-dapp';
import { signatureVerify } from '@polkadot/util-crypto';

import styles from '@/styles/Home.module.css';
Expand Down
18 changes: 13 additions & 5 deletions pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import NextAuth, { NextAuthOptions, User } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { signatureVerify } from '@polkadot/util-crypto';
import { encodeAddress } from '@polkadot/keyring';
import { encodeAddress, Keyring } from '@polkadot/keyring';
import { ApiPromise, WsProvider } from '@polkadot/api';
import { BN } from '@polkadot/util';

Expand Down Expand Up @@ -87,18 +87,26 @@ export const authOptions: NextAuthOptions = {
return Promise.reject(new Error('🚫 Invalid Signature'));
}

// verify the account has the defined token
// AA: specify xx Network
const keyring = new Keyring({ type: 'sr25519', ss58Format: 55 });

// verify the account has the defined token
const wsProvider = new WsProvider(
process.env.RPC_ENDPOINT ?? 'ws://192.168.1.3:63007',
);
const api = await ApiPromise.create({ provider: wsProvider });
await api.isReady;

// AA: encode wallet address for ss58Format 55
const ksmAddress = encodeAddress(credentials.address, 55);
// AA: write ksmAddress for xx Network to console
console.log('wallet address on xx Network: ', ksmAddress);

return {
id: credentials.address,
name: credentials.name,
freeBalance: api.createType('Balance', 0),
ksmAddress: encodeAddress(credentials.address, 2),
freeBalance: api.createType('Balance', 0),
ksmAddress: ksmAddress,
};

} catch (e) {
Expand Down Expand Up @@ -126,7 +134,7 @@ export const authOptions: NextAuthOptions = {

session.address = token.sub;
if (session.address) {
session.ksmAddress = encodeAddress(session.address, 2);
session.ksmAddress = encodeAddress(session.address, 55);
}

// as we already queried it, we can add whatever token to the session,
Expand Down
73 changes: 45 additions & 28 deletions pages/protected-api.tsx
Original file line number Diff line number Diff line change
@@ -1,58 +1,75 @@
import { useState, useEffect } from "react"
import { useSession } from "next-auth/react"
import styles from '@/styles/Home.module.css'
import Link from "next/link"
import { formatBalance } from '@polkadot/util';
import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import styles from '@/styles/Home.module.css';
import Link from 'next/link';
import { BN, formatBalance } from '@polkadot/util';

import PolkadotParticles from "@/components/polkadot-particles"
import PolkadotParticles from '@/components/polkadot-particles';

/**
* This is a protected page, it can only be accessed by authenticated users. Instead of using Server Side
* Rendering (SSR) to fetch the content, we use Static Generation and a protected API Route `/pages/api/auth.ts`
* This is a protected page, it can only be accessed by authenticated users. Instead of using Server Side
* Rendering (SSR) to fetch the content, we use Static Generation and a protected API Route `/pages/api/auth.ts`
* to fetch the content client side after the user has logged in.
*/
export default function ProtectedPage() {
const { data: session } = useSession()
const [content, setContent] = useState()
const { data: session } = useSession();
const [content, setContent] = useState();

// Fetch content from protected route
useEffect(() => {
const fetchData = async () => {
const res = await fetch("/api/auth")
const res = await fetch('/api/auth');

if (res.ok) {
const json = await res.json()
const json = await res.json();
if (json?.content) {
setContent(json.content)
setContent(json.content);
}
}
}
fetchData()
}, [session])

};
fetchData();
}, [session]);

// If no session exists, display access denied message
if (!session) {
return (
<main className={ styles.protected }>
<main className={styles.protected}>
<h1>You did not pass the 🚪</h1>
<p><Link href="/" className={ styles.colorA }>&lt; go back</Link></p>
<p>
<Link href="/" className={styles.colorA}>
&lt; go back
</Link>
</p>
</main>
)
);
}

// format the big number to a human readable format
// const ksmBalance = formatBalance( session.freeBalance, { decimals: 12, withSi: true, withUnit: 'KSM' } )
const ksmBalance = formatBalance( session.freeBalance, { decimals: 9, withSi: true, withUnit: 'XX' } )
// const ksmBalance = formatBalance( freeBalance, { decimals: 12, withSi: true, withUnit: 'KSM' } )
// AA: hard-coded 2.00 xx
const freeBalance = new BN(2000000000);
const ksmBalance = formatBalance(freeBalance, {
decimals: 9,
withSi: true,
withUnit: 'XX',
});

// If session exists, display content
return (
<main className={ styles.protected }>
<h1>🎉 Welcome { session.user?.name }, you passed the 🚪</h1>
<p>with { ksmBalance }</p>
<p>You are seeing a protected route that uses a static page and a protected api route. See the code at <code>/pages/protected.tsx</code></p>
<p> <Link href="/" className={ styles.colorA }>&lt; go back</Link></p>
<main className={styles.protected}>
<h1>🎉 Welcome {session.user?.name}, you passed the 🚪</h1>
<p>with {ksmBalance}</p>
<p>
You are seeing a protected route that uses a static page and a protected api route. See the
code at <code>/pages/protected.tsx</code>
</p>
<p>
{' '}
<Link href="/" className={styles.colorA}>
&lt; go back
</Link>
</p>
<PolkadotParticles />
</main>
)
);
}
74 changes: 42 additions & 32 deletions pages/protected.tsx
Original file line number Diff line number Diff line change
@@ -1,60 +1,70 @@
import { getServerSession } from "next-auth/next"
import { useSession } from "next-auth/react"
import Link from "next/link"
import { authOptions } from "./api/auth/[...nextauth]"
import { getServerSession } from 'next-auth/next';
import { useSession } from 'next-auth/react';
import Link from 'next/link';
import { authOptions } from './api/auth/[...nextauth]';
import { BN, formatBalance, BN_ZERO } from '@polkadot/util';
import { GetServerSideProps } from 'next'
import { GetServerSideProps } from 'next';

import styles from '@/styles/Home.module.css'
import PolkadotParticles from "@/components/polkadot-particles"
import styles from '@/styles/Home.module.css';
import PolkadotParticles from '@/components/polkadot-particles';

export default function Admin( { freeBalance } : { freeBalance : BN } ) : JSX.Element {
const { data:session, status } = useSession({
export default function Admin({ freeBalance }: { freeBalance: BN }): JSX.Element {
const { data: session, status } = useSession({
required: true,
onUnauthenticated() {
console.log( 'not authenticated yet', status )
console.log('not authenticated yet', status);
},
})
});

if (status === "loading") {
if (status === 'loading') {
return (
<main className={ styles.protected }>
<main className={styles.protected}>
<h1>You did not pass the 🚪</h1>
<p><Link href="/" className={ styles.colorA }>&lt; go back</Link></p>
<p>
<Link href="/" className={styles.colorA}>
&lt; go back
</Link>
</p>
</main>
)
);
}

// format the big number to a human readable format
// const ksmBalance = formatBalance( freeBalance, { decimals: 12, withSi: true, withUnit: 'KSM' } )
const ksmBalance = formatBalance( freeBalance, { decimals: 9, withSi: true, withUnit: 'XX' } )

// AA: freeBalance obtained in L11
const ksmBalance = formatBalance(freeBalance, {
decimals: 9,
withSi: true,
withUnit: 'XX',
});
return (
<main className={ styles.protected }>
<h1>🎉 Welcome { session.user?.name }, you passed the 🚪</h1>
<p>with { ksmBalance }</p>
<p>You are seeing a /protected route that uses Server-Side Generation at <code>/pages/protected.tsx</code> </p>
<p><Link href="/" className={ styles.colorA }>&lt; go back</Link></p>
<main className={styles.protected}>
<h1>🎉 Welcome {session.user?.name}, you passed the 🚪</h1>
<p>with {ksmBalance}</p>
<p>
You are seeing a /protected route that uses Server-Side Generation at{' '}
<code>/pages/protected.tsx</code>{' '}
</p>
<p>
<Link href="/" className={styles.colorA}>
&lt; go back
</Link>
</p>
<PolkadotParticles />
</main>
)
);
}

// this tells next to render the page on the server side
export const getServerSideProps: GetServerSideProps = async (context) => {

// Get the user's session based on the request
// read more about get Server session here:
// https://next-auth.js.org/tutorials/securing-pages-and-api-routes
let session = await getServerSession(
context.req,
context.res,
authOptions
)
let session = await getServerSession(context.req, context.res, authOptions);

return {
props: {
freeBalance: session?.freeBalance ?? JSON.stringify(BN_ZERO),
}
}
}
},
};
};
2 changes: 2 additions & 0 deletions xx_README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,5 +71,7 @@ JSON Web Token {
The FAQs say [it's normal to see another address](https://polkadot.js.org/docs/keyring/FAQ#my-pair-address-does-not-match-with-my-chain), but balance look up should work and it doesn't because my wallet balance is > 0 XX.
`encodeAddress(session.address, 55)` is one correction that needed to be made, and the proper encoding used to get the correct wallet address from xx Network printed out in console log. But its balance is still wrong (i.e. not queried). For demo purposes I hard-coded it into JS on one of the protected pages.

0 comments on commit 7530878

Please sign in to comment.