Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
lochie committed May 28, 2024
1 parent 7e81f88 commit cf30c13
Showing 1 changed file with 32 additions and 9 deletions.
41 changes: 32 additions & 9 deletions packages/connectkit-next-siwe/src/configureSIWE.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,14 @@ import { SIWEProvider } from 'connectkit';
import type { IncomingMessage, ServerResponse } from 'http';
import { getIronSession, IronSession, IronSessionOptions } from 'iron-session';
import { NextApiHandler, NextApiRequest, NextApiResponse } from 'next';
import { generateSiweNonce, createSiweMessage } from 'viem/siwe';
import {
generateSiweNonce,
createSiweMessage,
verifySiweMessage,
} from 'viem/siwe';

import { createPublicClient, http } from 'viem';
import { mainnet } from 'viem/chains';

type RouteHandlerOptions = {
afterNonce?: (
Expand Down Expand Up @@ -151,25 +158,41 @@ const verifyRoute = async (
) => {
switch (req.method) {
case 'POST':
const publicClient = createPublicClient({
chain: mainnet, // TODO: use chain from message
transport: http(),
});

try {
const session = await getSession(req, res, sessionConfig);
const { message, signature } = req.body;
const siweMessage = createSiweMessage(message);
const { data: fields } = await verifySiweMessage({
const { message, signature } = req.body as {
message: string;
signature: `0x${string}`;
};
const verified = await verifySiweMessage(publicClient, {
message,
signature,
nonce: session.nonce,
});
if (fields.nonce !== session.nonce) {
if (!verified) {
return res.status(422).end('Invalid nonce.');
}
session.address = fields.address;
session.chainId = fields.chainId;

const splitMessage = message.split('\n');
session.address = splitMessage.find((m) => m.startsWith('0x'));
session.chainId = Number(
splitMessage
.find((m) => m.startsWith('Chain ID: '))
?.split('Chain ID: ')[1]
);

await session.save();
if (afterCallback) {
await afterCallback(req, res, session);
}
res.status(200).end();
} catch (error) {
} catch (error: any) {
console.log(error.shortMessage);
switch (error) {
/*
case SiweErrorType.INVALID_NONCE:
Expand All @@ -179,7 +202,7 @@ const verifyRoute = async (
}
*/
default: {
res.status(400).end(String(error));
res.status(400).end(String(error.shortMessage));
break;
}
}
Expand Down

0 comments on commit cf30c13

Please sign in to comment.