Skip to content

Instantly share code, notes, and snippets.

@jermsam
Last active April 10, 2019 17:37
Show Gist options
  • Save jermsam/547061889cad80475bdbc4f9e6db5a1c to your computer and use it in GitHub Desktop.
Save jermsam/547061889cad80475bdbc4f9e6db5a1c to your computer and use it in GitHub Desktop.
import React from 'react';
import App, { Container } from 'next/app';
import NextSeo from 'next-seo';
import 'semantic-ui-css/semantic.min.css';
import 'react-dropzone-component/styles/filepicker.css';
import 'react-toastify/dist/ReactToastify.css';
import 'dropzone/dist/min/dropzone.min.css';
import 'react-image-crop/dist/ReactCrop.css';
import 'react-datepicker/dist/react-datepicker.css';
import { loadReCaptcha } from 'react-recaptcha-google';
import { StripeProvider } from 'react-stripe-elements';
// import { AuthProvider,AuthConsumer } from '../AuthContext';
import '../static/css/style.css';
import '../static/css/upload.css';
import '../static/css/stripe.css';
// import your default seo configuration
import SEO from '../next-seo.config';
import { app } from '../feathers';
export default class MyApp extends App {
_isMounted = false;
state = { stripe: null, authUser: null };
componentDidMount() {
this._isMounted = true;
loadReCaptcha();
this.setState({ stripe: window.Stripe(process.env.STRIPE_PUBLISHABLE) });
this.getAuthUser()
}
componentDidUpdate(prevState,) {
const { authUser} = this.state
if (prevState.authUser !== authUser) {
this.getAuthUser()
}
}
componentWillUnmount() {
this._isMounted = false;
}
getAuthUser = async() =>{
const token = localStorage.getItem('feathers-jwt');
if (token) {
try{
const { userId } = await app.passport.verifyJWT(token);
// console.log('banny request: ',userId)
// return userId
const authUser = await app.service('users').get(userId);
if (this._isMounted) {
this.setState({ authUser })
}
}catch({message}){
console.log("Error: ",message)
}
}
}
render() {
const { Component, pageProps,} = this.props;
const { stripe,authUser} = this.state;
// console.log('rendered user: ', authUser); // contains old info when authenticated
return (
<Container>
{/* Here we call NextSeo and pass our default configuration to it */}
<NextSeo config={SEO} />
<StripeProvider {...{ stripe }}>
<Component {...pageProps} {...{ authUser }} />
</StripeProvider>
</Container>
);
}
}
MyApp.getInitialProps = async ({ Component, ctx }) => {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
return { pageProps,};
};
import React from 'react';
/* eslint-disable no-console */
import {
Message,
Button,
Header,
Icon,
Input,
Grid,
Container,
Dimmer,
Loader,
Divider,
Segment
} from 'semantic-ui-react';
import Validator from 'validator';
import { Router } from '../../../routes';
import { app } from '../../../feathers';
import SocialLogin from './SocialLogin';
const INNITIAL_STATE = {
isSubmitting: false,
disableSave: true,
concealed: true,
data: {
email: '',
password: ''
},
errors: [],
loading: false
};
const validate = values => {
const errors = [];
if (!values.email) {
errors.email = {
message: 'email required'
};
} else if (!Validator.isEmail(values.email)) {
errors.email = {
message: 'invalid email'
};
}
if (!values.password) {
errors.password = {
message: 'password required'
};
}
//
return errors;
};
export default class SigninForm extends React.Component {
state = INNITIAL_STATE;
_isMounted = false;
componentDidMount() {
this._isMounted = true;
this.updateDataEmail()
}
componentDidUpdate(prevProps) {
const {email}=this.props
if (prevProps.email !== email) {
this.updateDataEmail()
}
}
componentWillUnmount() {
this._isMounted = false;
}
updateDataEmail =()=>{
const { email } = this.props
if (email) {
if(this._isMounted){
this.setState(prevState => ({
data: {
...prevState.data,
email
}
}))
}
}
}
toggleConcealled = () => {
if (this._isMounted) {
this.setState(prevState => ({ concealed: !prevState.concealed }));
}
};
handleOnChange = (e, { name, value }) => {
const { data } = this.state;
const errors = validate(data);
if (this._isMounted) {
this.setState(prevState => ({
data: {
...prevState.data,
[name]: value
},
disableSave: false && !errors
}));
}
};
handleSignin = () => {
const { data } = this.state;
const errors = validate(data);
if (this._isMounted) {
this.setState({ errors });
}
if (Object.keys(errors).length === 0) {
// Sign in
this.doAuth(data);
// this.Sign inUser(data);
}
if (this._isMounted) {
this.setState({ disableSave: true });
}
};
doAuth = async data => {
try {
const res = await app.authenticate({
strategy: 'local',
...data
});
if (this._isMounted) {
this.setState({ isSubmitting: true });
}
const { userId } = await app.passport.verifyJWT(res.accessToken);
await Router.push(`/dashboard?userId=${userId}`);
if (this._isMounted) {
this.setState({ isSubmitting: false });
}
// window.location.reload();
return userId;
} catch ({ message }) {
if (this._isMounted) {
this.setState(prevState => ({
isSubmitting: false ,
errors: {
...prevState.errors,
general: { message }
}
}));
}
return null;
}
};
render() {
const {
isSubmitting,
concealed,
disableSave,
data: { email, password },
errors,
loading
} = this.state;
return (
<Container text textAlign="center">
<Segment basic>
<Segment padded="very">
<div>
<Header color="olive" as="h2">
{!!errors.general && (
<span style={{ color: 'red', fontSize: '0.7em' }}>
(
{errors.general.message === 'Invalid login'
? 'You entered an incorrect email or password'
: 'Something went wrong. Please Try again later'}
)
</span>
)}
</Header>
<Grid>
<Grid.Row columns="equal">
<Grid.Column>
<div>
{!!errors.email && (
<span style={{ color: 'red' }}>
{errors.email.message}
</span>
)}
</div>
<Input
placeholder="enter e-mail"
fluid
name="email"
value={email}
onChange={this.handleOnChange}
/>
</Grid.Column>
</Grid.Row>
<Grid.Row columns="equal">
<Grid.Column width={16}>
<div>
{!!errors.password && (
<span style={{ color: 'red' }}>
{errors.password.message}
</span>
)}
</div>
<Input
type={concealed ? 'password' : 'text'}
placeholder="enter password"
action
fluid
name="password"
value={password}
onChange={this.handleOnChange}
>
<input />
<Button basic onClick={this.toggleConcealled}>
{concealed ? (
<div>
<Icon name="unhide" /> unhide
</div>
) : (
<div>
<Icon name="hide" /> hide
</div>
)}
</Button>
</Input>
</Grid.Column>
</Grid.Row>
<Grid.Row columns="equal" textAlign="center">
<Grid.Column width={16}>
<Header color="olive" as="h2">
{!!errors.general && (
<a
href="/passwordreset"
style={{ color: 'green', fontSize: '0.7em' }}
>
Forgot password?
</a>
)}
</Header>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<Dimmer active={loading}>
<Grid
textAlign="center"
verticalAlign="middle"
columns={1}
>
<Divider section hidden />
<Divider section hidden />
<Header
inverted
content="We are signing you in"
subheader="Please wait ..."
/>
<Divider section hidden />
<Divider section hidden />
<Loader />
</Grid>
</Dimmer>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<Button
color="instagram"
fluid
size="large"
disabled={disableSave}
onClick={this.handleSignin}
>
{!isSubmitting ? 'submit' : 'submiting ...'}
</Button>
<Divider section />
<Container textAlign="center">
By using our site, you agree to our{' '}
<a href="/terms">terms</a> and{' '}
<a href="/policy">privacy policy</a>.
</Container>
</Grid.Column>
</Grid.Row>
</Grid>
</div>
</Segment>
</Segment>
<SocialLogin />
<Message>
New to us? <a href="/signup">Sign Up</a>
</Message>
</Container>
);
}
}
SigninForm.getInitialProps = ({ email }) => ({ email });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment