Skip to content

Instantly share code, notes, and snippets.

@jermsam
Last active May 3, 2019 00:44
Show Gist options
  • Save jermsam/40257197eb6d225be73a31b131c6c559 to your computer and use it in GitHub Desktop.
Save jermsam/40257197eb6d225be73a31b131c6c559 to your computer and use it in GitHub Desktop.
// track all authentication for the whole app at the very ancestor. then pass it on to all children
export default class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
let pageProps = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return { pageProps }
}
_isMounted = false;
state = {
authUser:null,
stripe:null
};
componentDidMount() {
this._isMounted = true;
loadReCaptcha();
if (window.Stripe) {
this.setState({stripe: window.Stripe(process.env.STRIPE_PUBLISHABLE)});
}
this.handleAuth();
app.on('authenticated', this.handleAuth);
app.service('users').on('patched', this.handleAuth);
app.service('licenses').on('created', this.handleAuth);
app.service('licenses').on('patched', this.handleAuth);
app.service('address').on('created', this.handleAuth);
app.service('address').on('patched', this.handleAuth);
app.service('stories').on('created', this.handleAuth);
app.service('stories').on('patched', this.handleAuth);
}
componentWillUnmount() {
this._isMounted = false;
}
handleAuth = () =>getAuthUserFromStoredJWT(app).then(authUser=>{if (this._isMounted) {
this.setState({ authUser });
}})
logout=()=>{if(this._isMounted){app.logout();
Router.push(`/signin`);
this.setState({ authUser: null });
}
};
render() {
const { Component, pageProps } = this.props;
const {authUser,stripe}=this.state
return (
<Container>
{/* Here we call NextSeo and pass our default configuration to it */}
<NextSeo config={SEO} />
<TopMenu {...{ authUser }} logout={this.logout} />
<StripeProvider {...{ stripe }}>
<Component {...pageProps} {...this.state}/>
</StripeProvider>
</Container>
);
}
}
import React from 'react'
import { withRouter } from 'next/router'
import Layout from './layout';
const Page = ({router,authUser}) => {
// render whether authUser is null or not
console.log(authUser)
const{userId}=router.query
return (
<Layout withFooter>
<div>
{userId}
</div>
</Layout>
);
};
export default withRouter(Page)
import React from 'react';
import { Container, Grid, Button, Icon, Header } from 'semantic-ui-react';
import { url } from '../../feathers';
const SocialLogins = () => (
<Container textAlign="center">
<Header
color="grey"
dividing
content="Alternatively:"
subheader="Sign in with: "
/>
<Grid>
<Grid.Row columns={1}>
<Grid.Column>
<Button
color="facebook"
as="a"
href={`${url}/auth/facebook`}
fluid
size="massive"
>
<Icon name="facebook f" />
facebook
</Button>
</Grid.Column>
</Grid.Row>
<Grid.Row columns={1}>
<Grid.Column>
<!-- send to google for Oauth 2 as directed by backend api-->
<Button
color="google plus"
as="a"
href={`${url}/auth/google`}
fluid
size="massive"
>
<Icon name="google plus" /> {' '} google
</Button>
</Grid.Column>
</Grid.Row>
</Grid>
</Container>
);
export default SocialLogins;
import React,{Fragment,useState,useEffect,useCallback} from 'react';
import { Grid, Header, Image, Divider, Loader } from 'semantic-ui-react';
import { withRouter } from 'next/router'
import Layout from './layout';
import VerifyForm from './forms/VerifyForm';
import { app,sendToken } from '../feathers';
// this page manages verification whether by socialor local (username,password) login
const PageContent = ({router, email, isVerified ,isLoading}) => (
<Fragment>
{isLoading ?
<Grid
columns={1}
verticalAlign="middle"
textAlign="center"
style={{ minHeight: '100vh' }}
>
<Grid.Column>
<Header
sub
content="redirecting"
subheader="please wait ..."
/>
<Divider section hidden />
<Loader active={isLoading} inline="centered" size="massive" />
</Grid.Column>
</Grid>
:
<Grid textAlign="center" style={{ height: '100%' }} verticalAlign="middle">
<Grid.Column style={{ maxWidth: 450 }} id='top'>
{!isVerified && (
<Fragment>
{' '}
<Header as="h2" color="grey" textAlign="center">
<Image src="/static/imgs/chat-logo.png" /> Account Verification
</Header>
<VerifyForm {...{ email }} {...{router}}/>
</Fragment>
)}
</Grid.Column>
</Grid>
}
</Fragment>
);
const Page = ({authUser,router}) => {
const [isVerified,setIsVerified]=useState(false)
const [isLoading,setIsLoading]=useState(false)
// redirect to dashboard if already logged in (never show this page)
if(authUser){
router.push({pathname:'/dashboard',query:{userId:authUser.id}})
}
const sendToSignIn = useCallback(async () => {
const { token } = router.query
try {
if (token) {// check for token,
setIsLoading(true);
// auth manage
const res = await sendToken(
app,
'verifySignupLong',
token
);
console.log(res)
// set is verified and push to signin page
setIsVerified(res.isVerified);
router.push({
pathname:'/signin',
query:{
email:router.query.email,
isVerified:res.isVerified
}
}
);
setIsLoading(false)
}
} catch ({ message }) {
// console.log('Error: ', message);
}
// return null
}, [router]);
useEffect(()=>{sendToSignIn()}, [isVerified, sendToSignIn]);
return (
<Layout withFooter>
<PageContent
{...{router}}
email={router.query.email}
{...{isVerified}}
{...{isLoading}}
/>
</Layout>
);
};
export default withRouter(Page)
import React,{useEffect,useCallback} from 'react';
import { Grid, Header, Divider, Loader } from 'semantic-ui-react';
import { withRouter } from 'next/router'
import Layout from './layout';
import {app,getAuthUserFromJWT,} from '../feathers'
const Page = ({router,authUser}) => {
// redirect to dashboard if already logged in (never show this page)
if(authUser){ router.push({pathname:'/dashboard',query:{userId:authUser.id}})}
const handleVerify = useCallback(async () => {
// read token from url path returned by google after social login
const { token } = router.query;
try {
// read authUser info from returned token
const {email,verifyToken } = await getAuthUserFromJWT(app,token);
// if user is not verified, redirect them to verify.js sor verification
if (verifyToken) {
router.push({
pathname:'/verify',
query:{
email,token:verifyToken
}
});
} else {
//else store their token in localstorage
localStorage.setItem('feathers-jwt', token);
// read their id from stored token
const { userId } = await app.passport.verifyJWT(token);
// and hence redirect them to respective dashboard **chaeting here***
await router.push({pathname:'/dashboard',query:{userId}});
window.location.reload()
//
}
} catch ({ message }) {
// console.log('Error: ', message);
}
},[router,]);
useEffect(()=>{handleVerify()},[handleVerify])
return (
<Layout withFooter>
<Grid
columns={1}
verticalAlign="middle"
textAlign="center"
style={{ minHeight: '100vh' }}
>
<Grid.Column>
<Header
sub
content="processing verification"
subheader="please wait ..."
/>
<Divider section hidden />
<Loader active inline="centered" size="massive" />
</Grid.Column>
</Grid>
</Layout>
);
};
export default withRouter(Page)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment