Skip to content

Commit

Permalink
WIP: checkpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
k0beLeenders authored and chambaz committed Nov 22, 2023
1 parent c7fa15c commit 8df5121
Show file tree
Hide file tree
Showing 7 changed files with 237 additions and 192 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export const PointsSignIn: FC<PointsSignInProps> = ({}) => {
toast.info("Logging in...");
const blockhashInfo = await connection.getLatestBlockhash();
try {
await firebaseApi.login(wallet, useAuthTx ? "tx" : "memo", blockhashInfo);
await firebaseApi.login(wallet);
// localStorage.setItem("authData", JSON.stringify(signedAuthData));
toast.success("Logged in successfully");
} catch (loginError: any) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const PointsSignUp: FC<PointsSignUpProps> = ({ referralCode }) => {
toast.info("Logging in...");
const blockhashInfo = await connection.getLatestBlockhash();
try {
await firebaseApi.signup(wallet, useAuthTx ? "tx" : "memo", blockhashInfo, finalReferralCode);
await firebaseApi.signup(wallet, finalReferralCode);
// localStorage.setItem("authData", JSON.stringify(signedAuthData));
toast.success("Signed up successfully");
} catch (signupError: any) {
Expand Down
26 changes: 16 additions & 10 deletions apps/marginfi-v2-ui/src/pages/api/user/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@ import {
initFirebaseIfNeeded();

export interface LoginRequest {
method: SigningMethod;
signedAuthDataRaw: string;
walletAddress: string;
// method: SigningMethod;
// signedAuthDataRaw: string;
}

export default async function handler(req: NextApiRequest<LoginRequest>, res: any) {
const { method, signedAuthDataRaw } = req.body;
const { walletAddress } = req.body;

/* signing logic
let signer;
try {
const loginData = validateAndUnpackLoginData(signedAuthDataRaw, method);
Expand All @@ -46,32 +48,36 @@ export default async function handler(req: NextApiRequest<LoginRequest>, res: an
status = STATUS_INTERNAL_ERROR;
}
return res.status(status).json({ error: error.message });
}
}*/

let user;
try {
const userResult = await getFirebaseUserByWallet(signer);
const userResult = await getFirebaseUserByWallet(walletAddress);
if (userResult === undefined) {
await logLoginAttempt(signer, null, signedAuthDataRaw, false);
await logLoginAttempt(walletAddress, null, "", false);
Sentry.captureException({ message: "User not found" });
return res.status(STATUS_NOT_FOUND).json({ error: "User not found" });
} else {
await logLoginAttempt(walletAddress, user.uid, "", true);
}
user = userResult;
} catch (error: any) {
Sentry.captureException(error);
return res.status(STATUS_INTERNAL_ERROR).json({ error: error.message }); // An unexpected error occurred
}

await logLoginAttempt(signer, user.uid, signedAuthDataRaw, true);

// Generate a custom token for the client to log in
const customToken = await admin.auth().createCustomToken(signer);
const customToken = await admin.auth().createCustomToken(walletAddress);

return res.status(STATUS_OK).json({ status: "success", uid: signer, token: customToken });
return res.status(STATUS_OK).json({ status: "success", uid: walletAddress, token: customToken });
}

// -------- Helpers

/**
* @deprecated
* Signing functionality
*/
export function validateAndUnpackLoginData(
signedAuthDataRaw: string,
signingMethod: SigningMethod
Expand Down
68 changes: 36 additions & 32 deletions apps/marginfi-v2-ui/src/pages/api/user/signup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import base58 from "bs58";
import nacl from "tweetnacl";
import {
SigningMethod,
SignupPayload,
STATUS_BAD_REQUEST,
STATUS_UNAUTHORIZED,
STATUS_INTERNAL_ERROR,
Expand All @@ -19,43 +20,42 @@ import {
initFirebaseIfNeeded();

export interface SignupRequest {
method: SigningMethod;
signedAuthDataRaw: string;
walletAddress: string;
payload: SignupPayload;
// method: SigningMethod;
// signedAuthDataRaw: string;
}

export default async function handler(req: NextApiRequest<SignupRequest>, res: any) {
const { method, signedAuthDataRaw } = req.body;
const { walletAddress, payload } = req.body;

Sentry.setContext("signup_args", {
method,
signedAuthDataRaw,
walletAddress,
});

let signer;
let payload;
try {
const signupData = validateAndUnpackSignupData(signedAuthDataRaw, method);
signer = signupData.signer.toBase58();
payload = signupData.payload;
} catch (error: any) {
Sentry.captureException(error);
let status;
switch (error.message) {
case "Invalid signup tx":
case "Invalid signup payload":
status = STATUS_BAD_REQUEST;
break;
case "Invalid signature":
status = STATUS_UNAUTHORIZED;
break;
default:
status = STATUS_INTERNAL_ERROR;
}
return res.status(status).json({ error: error.message });
}
// try {
// const signupData = validateAndUnpackSignupData(signedAuthDataRaw, method);
// signer = signupData.signer.toBase58();
// payload = signupData.payload;
// } catch (error: any) {
// Sentry.captureException(error);
// let status;
// switch (error.message) {
// case "Invalid signup tx":
// case "Invalid signup payload":
// status = STATUS_BAD_REQUEST;
// break;
// case "Invalid signature":
// status = STATUS_UNAUTHORIZED;
// break;
// default:
// status = STATUS_INTERNAL_ERROR;
// }
// return res.status(status).json({ error: error.message });
// }

try {
const user = await getFirebaseUserByWallet(signer);
const user = await getFirebaseUserByWallet(walletAddress);
if (user) {
Sentry.captureException({ message: "User already exists" });
return res.status(STATUS_BAD_REQUEST).json({ error: "User already exists" });
Expand All @@ -66,23 +66,27 @@ export default async function handler(req: NextApiRequest<SignupRequest>, res: a
}

try {
await createFirebaseUser(signer, payload.referralCode);
await createFirebaseUser(walletAddress, payload.referralCode);
console.log("successfully created new user");
} catch (createUserError: any) {
Sentry.captureException(createUserError);
return res.status(STATUS_INTERNAL_ERROR).json({ error: createUserError.message });
}

await logSignupAttempt(signer, payload.uuid, signedAuthDataRaw, true);
await logSignupAttempt(walletAddress, payload.uuid, "", true);

// Generate a custom token for the client to sign in
const customToken = await admin.auth().createCustomToken(signer);
const customToken = await admin.auth().createCustomToken(walletAddress);

return res.status(STATUS_OK).json({ status: "success", uid: signer, token: customToken });
return res.status(STATUS_OK).json({ status: "success", uid: walletAddress, token: customToken });
}

// -------- Helpers

/**
* @deprecated
* Signing functionality
*/
export function validateAndUnpackSignupData(
signedAuthDataRaw: string,
signingMethod: SigningMethod
Expand Down
15 changes: 1 addition & 14 deletions apps/marginfi-v2-ui/src/pages/points.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ import {
const Points = () => {
const { connected } = useWalletContext();
const { query: routerQuery } = useRouter();
// useUserProfileStore(() => {
// state
// })

const [currentFirebaseUser, hasUser, userPointsData] = useUserProfileStore((state) => [
state.currentFirebaseUser,
state.hasUser,
Expand All @@ -35,17 +33,6 @@ const Points = () => {
const referralCode = React.useMemo(() => routerQuery.referralCode as string | undefined, [routerQuery.referralCode]);
const [isReferralCopied, setIsReferralCopied] = React.useState(false);

// React.useEffect(() => {
// fetchMrgnlendState({ marginfiConfig: config.mfiConfig, connection, wallet, isOverride }).catch(console.error);
// const id = setInterval(() => {
// setIsRefreshingStore(true);
// fetchMrgnlendState().catch(console.error);
// }, 30_000);
// return () => clearInterval(id);
// }, [wallet, isOverride]); // eslint-disable-line react-hooks/exhaustive-deps
// ^ crucial to omit both `connection` and `fetchMrgnlendState` from the dependency array
// TODO: fix...

return (
<>
<PageHeader>points</PageHeader>
Expand Down
Loading

0 comments on commit 8df5121

Please sign in to comment.