Skip to content

Commit

Permalink
Merge pull request #52 from near/login-page
Browse files Browse the repository at this point in the history
login page
  • Loading branch information
esaminu authored Sep 28, 2023
2 parents 1d60263 + cdffb2c commit e8ccefd
Show file tree
Hide file tree
Showing 7 changed files with 161 additions and 70 deletions.
6 changes: 3 additions & 3 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,12 @@ export default function App() {
<RemoveTrailingSlash />
<Routes>
<Route path="/">
<Route index element={<AuthIndicator controller={window.fastAuthController} />} />
<Route path="add-device" element={<AddDevice />} />
<Route index element={<AuthIndicator />} />
<Route path="login" element={<Login />} />
<Route path="create-account" element={<CreateAccount />} />
<Route path="add-device" element={<AddDevice />} />
<Route path="sign" element={<Sign />} />
<Route path="verify-email" element={<VerifyEmailPage />} />
<Route path="login" element={<Login controller={window.fastAuthController} />} />
<Route path="auth-callback" element={<AuthCallbackPage />} />
<Route path="devices" element={<Devices />} />
</Route>
Expand Down
9 changes: 7 additions & 2 deletions src/components/AddDevice/AddDevice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ function SignInPage() {
const { authenticated, controllerState } = useAuthState(skipGetKey);
const [renderRedirectButton, setRenderRedirectButton] = useState('');


if (!window.firestoreController) {
(window as any).firestoreController = new FirestoreController();
}
Expand Down Expand Up @@ -184,6 +185,10 @@ function SignInPage() {

const email = decodeIfTruthy(searchParams.get('email'));
if (controllerState && isFirestoreReady) {
if (!public_key || !contract_id) {
window.location.replace(success_url || window.location.origin);
return;
}
const publicKeyFak = await window.fastAuthController.getPublicKey();
const existingDevice = await window.firestoreController.getDeviceCollection(publicKeyFak);
const existingDeviceLakKey = existingDevice?.publicKeys?.filter((key) => key !== publicKeyFak)[0];
Expand All @@ -193,7 +198,7 @@ function SignInPage() {
const parsedUrl = new URL(success_url || window.location.origin);
parsedUrl.searchParams.set('account_id', (window as any).fastAuthController.getAccountId());
parsedUrl.searchParams.set('public_key', public_key);
parsedUrl.searchParams.set('all_keys', public_key);
parsedUrl.searchParams.set('all_keys', [public_key, publicKeyFak].join(','));

if (inIframe()) {
setRenderRedirectButton(parsedUrl.href);
Expand Down Expand Up @@ -236,7 +241,7 @@ function SignInPage() {
const parsedUrl = new URL(success_url || window.location.origin);
parsedUrl.searchParams.set('account_id', (window as any).fastAuthController.getAccountId());
parsedUrl.searchParams.set('public_key', public_key);
parsedUrl.searchParams.set('all_keys', public_key);
parsedUrl.searchParams.set('all_keys', [public_key, publicKeyFak].join(','));

if (inIframe()) {
setRenderRedirectButton(parsedUrl.href);
Expand Down
23 changes: 11 additions & 12 deletions src/components/AuthIndicator/AuthIndicator.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
import * as React from 'react';
import { useEffect, useState } from 'react';
import React, { useEffect } from 'react';
import { useNavigate } from 'react-router';

import AuthIndicatorButton from './AuthIndicatorButton';
import { useAuthState } from '../../lib/useAuthState';

function AuthIndicator({ controller }) {
const [isSignedIn, setIsSignedIn] = useState<boolean>(false);
function AuthIndicator() {
const { authenticated, controllerState } = useAuthState();
const navigate = useNavigate();

useEffect(() => {
async function fetchSignedInStatus() {
const currentlySignedIn = await controller.isSignedIn();
setTimeout(() => setIsSignedIn(currentlySignedIn), 2000);
if (controllerState !== 'loading' && authenticated === false) {
navigate('/login');
}

fetchSignedInStatus();
}, [controller]);
}, [authenticated, controllerState]);

return (
<AuthIndicatorButton $buttonType="secondary" $isSignedIn={isSignedIn}>
{isSignedIn ? <p>signed in</p>
<AuthIndicatorButton $buttonType="secondary" $isSignedIn={authenticated && controllerState !== 'loading'}>
{authenticated ? <p>signed in</p>
: <p>not signed in</p>}
</AuthIndicatorButton>
);
Expand Down
7 changes: 5 additions & 2 deletions src/components/CreateAccount/CreateAccount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ function CreateAccount() {
const formValues = watch();
const navigate = useNavigate();
const [searchParams] = useSearchParams();


const createAccount = async (data: { email: string; username: string; }) => {
const success_url = searchParams.get('success_url');
Expand Down Expand Up @@ -123,8 +124,10 @@ function CreateAccount() {

if (email) {
setValue('email', email);
setValue('username', username);
createAccount({ email, username });
setValue('username', username || getEmailId(email));
if (username) {
createAccount({ email, username });
}
}
}, []);

Expand Down
64 changes: 64 additions & 0 deletions src/components/Login/Login.style.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import styled from 'styled-components';

export const LoginWrapper = styled.div`
width: 100%;
height: calc(100vh - 66px);
background-color: #f2f1ea;
display: flex;
align-items: center;
justify-content: center;
padding: 0 16px;
form {
max-width: 450px;
width: 100%;
margin: 16px auto;
background-color: #ffffff;
padding: 16px;
border-radius: 12px;
display: flex;
flex-direction: column;
gap: 16px;
}
.buttonsContainer {
}
`;

export const ButtonsContainer = styled.div`
display: flex;
flex-direction: column-reverse;
align-items: center;
button {
margin: 5px;
}
`;

export const InputContainer = styled.div`
width: 100%;
display: flex;
flex-direction: column;
label {
font-size: 12px;
font-weight: 500;
}
input {
padding: 8px 12px;
border: 1px solid #e5e5e5;
border-radius: 10px;
font-size: 14px;
margin-top: 4px;
min-height: 50px;
cursor: text;
&:focus {
outline: none;
border: 1px solid #e5e5e5;
}
}
.subText {
font-size: 12px;
}
`;
105 changes: 61 additions & 44 deletions src/components/Login/Login.tsx
Original file line number Diff line number Diff line change
@@ -1,74 +1,91 @@
import React, { useEffect, useState } from 'react';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import React, { useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';

import { Button } from '../../lib/Button';
import { inIframe } from '../../utils';
import AuthIndicator from '../AuthIndicator/AuthIndicator';
import { LoginWrapper, InputContainer } from './Login.style';
import { useForm } from 'react-hook-form';
import { fetchSignInMethodsForEmail } from 'firebase/auth';
import { firebaseAuth } from '../../utils/firebase';
import { isValidEmail } from '../../utils/form-validation';
import { openToast } from '../../lib/Toast';

function Login({ controller }) {
function Login() {
const [currentSearchParams] = useSearchParams();
const navigate = useNavigate();
const location = useLocation();

const [isSignedIn, setIsSignedIn] = useState<boolean>();

useEffect(() => {
async function fetchSignedInStatus() {
const currentlySignedIn = await controller.isSignedIn();
setTimeout(() => setIsSignedIn(currentlySignedIn), 2000);
}

fetchSignedInStatus();
}, [controller]);

useEffect(() => {
const isRecovery = currentSearchParams.get('isRecovery');
if (isRecovery) {
if (isRecovery === 'true') {
navigate({
pathname: '/add-device',
search: currentSearchParams.toString()
search: currentSearchParams.toString(),
});
} else {
navigate({
pathname: '/create-account',
search: currentSearchParams.toString()
search: currentSearchParams.toString(),
});
}
}
}, [currentSearchParams]);

return (
<div>
Login route
<AuthIndicator controller={window.fastAuthController} />
<Button
label="New account"
variant="affirmative"
onClick={() => {
const { handleSubmit, setValue } = useForm();

const emailCheck = async (params: any) => {
fetchSignInMethodsForEmail(firebaseAuth, params.email)
.then((result) => {
result.length === 0 &&
navigate({
pathname: '/create-account',
search: currentSearchParams.toString()
search: `email=${params.email}`,
});
if (!isSignedIn && inIframe()) {
window.open(`${window.location.origin}${location.pathname}${location.search}`, '_parent');
}
}}
/>
<Button
label="Existing account"
variant="affirmative"
onClick={() => {
result[0] == 'emailLink' &&
navigate({
pathname: '/add-device',
search: currentSearchParams.toString()
search: `email=${params.email}`,
});
if (!isSignedIn && inIframe()) {
window.open(`${window.location.origin}${location.pathname}${location.search}`, '_parent');
}
}}
/>
</div>
})
.catch((error: any) => {
console.error('error', error);
openToast({
type: 'ERROR',
title: error.message,
});
});
};

const onSubmit = handleSubmit(emailCheck);

return (
<LoginWrapper>
<form onSubmit={onSubmit}>
<header>
<h1>Log In</h1>
<p className="desc">Please enter your email</p>
</header>

<InputContainer>
<label htmlFor="email">Email</label>
<input
onChange={(e) => {
setValue('email', e.target.value);
if (!isValidEmail(e.target.value)) return;
}}
placeholder="user_name@email.com"
type="email"
required
/>
</InputContainer>

<Button
type="submit"
label="Continue"
variant="affirmative"
onClick={onSubmit}
/>
</form>
</LoginWrapper>
);
}

Expand Down
17 changes: 10 additions & 7 deletions src/utils/mpc-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,16 @@ export const getAddKeyAction = ({
contractId,
methodNames,
allowance,
}): [Action, Action] => [
addKey(PublicKey.from(webAuthNPublicKey), fullAccessKey()),
addKey(
PublicKey.from(publicKeyLak),
functionCallAccessKey(contractId, methodNames || [], allowance)
)
];
}): Action[] => [
addKey(PublicKey.from(webAuthNPublicKey), fullAccessKey())
].concat(
publicKeyLak
? addKey(
PublicKey.from(publicKeyLak),
functionCallAccessKey(contractId, methodNames || [], allowance)
)
: []
);

export const getAddLAKAction = ({
publicKeyLak,
Expand Down

0 comments on commit e8ccefd

Please sign in to comment.