Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[NEW] Eslint and prettier configs with husky pre-push hook #174

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
1 change: 1 addition & 0 deletions app/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.next
5 changes: 4 additions & 1 deletion app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,19 @@

This community system is a web app dynaically generated and packaged by NextJS during build time, by combinaing structure and data from a headless CMS - strapi.

The app is 100% composed of ReactJS components. See the `components` directory for the set of ReactJS components used, and see the `styles` directory for the CSS module associated with each of the components.
The app is 100% composed of ReactJS components. See the `components` directory for the set of ReactJS components used, and see the `styles` directory for the CSS module associated with each of the components.

The application is written for nextjs and deployable on all nextjs compatible CDN + microservices and scaled deployment platforms. For build and design, start it in a shell:

```
npm i
npm run dev
```

You can use ethe environment variable `NEXT_PUBLIC_STRAPI_API_URL` to override the location of strapi cms, if it is not running on the same host.

```
NEXT_PUBLIC_STRAPI_API_URL=http://127.0.0.1:1337 npm run dev
```

Now RC4Community should be accessible from http://localhost:3000
14 changes: 7 additions & 7 deletions app/apollo-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,25 @@ import { setContext } from '@apollo/client/link/context';
const httpLink = createHttpLink({
// Uncomment the appropriate line according to the
// region group where you created your database.
// uri: 'https://graphql.fauna.com/graphql',
// uri: 'https://graphql.fauna.com/graphql',
// uri: 'https://graphql.eu.fauna.com/graphql',
uri: 'https://graphql.us.fauna.com/graphql',
});

const authLink = setContext((_, { headers }) => {
const token = process.env.NEXT_PUBLIC_FAUNA_SECRET
const token = process.env.NEXT_PUBLIC_FAUNA_SECRET;
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : ''
}
authorization: token ? `Bearer ${token}` : '',
},
};
});

const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});

export default client;
export default client;
40 changes: 20 additions & 20 deletions app/components/auth/NoUserAvatar.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import { FaUser } from "react-icons/fa";
import { FaUser } from 'react-icons/fa';

export function NoUserAvatar({size,name}){
const char = name ? name.charAt(0) : null;
return (
<div
className="d-flex justify-content-center align-items-center text-capitalize"
style={{
width: `${size}px`,
height: `${size}px`,
background: "#dee2e6",
borderRadius: "50%"
}}>
{
char ?
<span style={{fontSize: `${size*0.65}px`}}>{char}</span>
:
<FaUser size={`${size*0.45}px`}/>
}
</div>
)
export function NoUserAvatar({ size, name }) {
const char = name ? name.charAt(0) : null;
return (
<div
className='d-flex justify-content-center align-items-center text-capitalize'
style={{
width: `${size}px`,
height: `${size}px`,
background: '#dee2e6',
borderRadius: '50%',
}}
>
{char ? (
<span style={{ fontSize: `${size * 0.65}px` }}>{char}</span>
) : (
<FaUser size={`${size * 0.45}px`} />
)}
</div>
);
}
10 changes: 8 additions & 2 deletions app/components/auth/firebase/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ COOKIE_SECRET_CURRENT=example_string_feafh3r2rv4ty4893vyt5vt5t38vy5n9t5vyt8vn54
COOKIE_SECRET_PREVIOUS=example_string_u4ht83r3m20rxc34nty340v9t4ty340mtu438ty48ntv4y8v

```
2. Initialize `next-firebase-auth` in _app.js

2. Initialize `next-firebase-auth` in \_app.js

```
// ./pages/_app.js
import { initAuth } from '../components/auth/firebase';
Expand All @@ -35,7 +37,9 @@ initAuth()
..
..
```

3. Export the page component with `withAuthUser(Page)` and use `useAuthUser()` hook to get user info.

```
// ./pages/demo
import React from 'react'
Expand All @@ -55,7 +59,8 @@ const Demo = () => {

export default withAuthUser()(Demo)
```
4. For SSR, use `withAuthUserSSR` to wrap your getServerSideProps.

4. For SSR, use `withAuthUserSSR` to wrap your getServerSideProps.

```
export const getServerSideProps = withAuthUserSSR(options)(({AuthUser}) => { })
Expand All @@ -78,4 +83,5 @@ signed: true,
},

```

7. Build will fail if environment variables are not set. In order not to affect rendering of other components make use of `withFirebaseAuthUser`, `withFirebaseAuthUserSSR`, `withFirebaseAuthUserTokenSSR` and `useFirebaseAuthUser` instead of their respective `next-firebase-auth` version. They are just a wrapper that checks if firebase is initialised properly or not. And prevents build fail. They are exported from `/app/components/auth/firebase`.
12 changes: 6 additions & 6 deletions app/components/auth/firebase/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import functions from "./lib/functions";
import firebaseAuthMenuButtonModule from "./ui/FirebaseAuthMenuButton";
import firebaseAuthUIModule from "./ui/FirebaseAuthUI";
import firebaseLogimFormModule from "./ui/FirebaseLoginForm";
import firebaseSignupFormModule from "./ui/FirebaseSignupForm";
import firebaseUserInfoModule from "./ui/FirebaseUserInfo";
import functions from './lib/functions';
import firebaseAuthMenuButtonModule from './ui/FirebaseAuthMenuButton';
import firebaseAuthUIModule from './ui/FirebaseAuthUI';
import firebaseLogimFormModule from './ui/FirebaseLoginForm';
import firebaseSignupFormModule from './ui/FirebaseSignupForm';
import firebaseUserInfoModule from './ui/FirebaseUserInfo';

export const withFirebaseAuthUser = functions.withFirebaseAuthUser;
export const withFirebaseAuthUserSSR = functions.withFirebaseAuthUserSSR;
Expand Down
136 changes: 74 additions & 62 deletions app/components/auth/firebase/lib/functions.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
import { init, useAuthUser, withAuthUser, withAuthUserSSR, withAuthUserTokenSSR} from 'next-firebase-auth'
import {
init,
useAuthUser,
withAuthUser,
withAuthUserSSR,
withAuthUserTokenSSR,
} from 'next-firebase-auth';
import { getGoogleCredsFromFile } from './getGoogleCredsFromFile';


const initAuthHelper = (function(){
let initAuthResult = {success: false, error: new Error('Firebase auth is not yet initialised')};
const initAuthHelper = (function () {
let initAuthResult = { success: false, error: new Error('Firebase auth is not yet initialised') };
const getInitAuthResult = () => {
return initAuthResult;
}
const setInitAuthResult = ({success,error}) => {
initAuthResult = {success,error};
}
return {getInitAuthResult, setInitAuthResult};
};
const setInitAuthResult = ({ success, error }) => {
initAuthResult = { success, error };
};
return { getInitAuthResult, setInitAuthResult };
})();

export const getInitAuthResult = initAuthHelper.getInitAuthResult;
Expand Down Expand Up @@ -40,30 +45,30 @@ export const createEmptyAuthUser = () => {
clientInitialized: false,
...(includeToken && { _token: null }),
}),
}
}
};
};

export const initAuth = () => {
let googleCreds = {
projectId: process.env.FIREBASE_PROJECT_ID || null,
clientEmail: process.env.FIREBASE_CLIENT_EMAIL || null,
// The private key must not be accessible on the client side.
privateKey: process.env.FIREBASE_PRIVATE_KEY || null,
}
if(typeof window === 'undefined' && process.env.GOOGLE_CREDS_PATH){
};
if (typeof window === 'undefined' && process.env.GOOGLE_CREDS_PATH) {
// firebase admin has to be initialized using service acccount json file.
googleCreds = getGoogleCredsFromFile(process.env.GOOGLE_CREDS_PATH);
}

try {
init({
loginAPIEndpoint: '/api/fb/login', // required
logoutAPIEndpoint: '/api/fb/logout', // required
onLoginRequestError: (err) => {
console.error(err)
console.error(err);
},
onLogoutRequestError: (err) => {
console.error(err)
console.error(err);
},
firebaseAdminInitConfig: {
credential: googleCreds,
Expand All @@ -80,10 +85,7 @@ export const initAuth = () => {
name: 'RC4Community', // required
// Keys are required unless you set `signed` to `false`.
// The keys cannot be accessible on the client side.
keys: [
process.env.COOKIE_SECRET_CURRENT,
process.env.COOKIE_SECRET_PREVIOUS,
],
keys: [process.env.COOKIE_SECRET_CURRENT, process.env.COOKIE_SECRET_PREVIOUS],
httpOnly: true,
maxAge: 12 * 60 * 60 * 24 * 1000, // twelve days
overwrite: true,
Expand All @@ -93,88 +95,98 @@ export const initAuth = () => {
signed: true,
},
onVerifyTokenError: (err) => {
console.error(err)
console.error(err);
},
onTokenRefreshError: (err) => {
console.error(err)
console.error(err);
},
});
initAuthHelper.setInitAuthResult({error: null, success: true});
initAuthHelper.setInitAuthResult({ error: null, success: true });
} catch (e) {
console.error(e)
initAuthHelper.setInitAuthResult({error: e, success: false});
console.error(e);
initAuthHelper.setInitAuthResult({ error: e, success: false });
}
return initAuthHelper.getInitAuthResult();
}
};

export const withFirebaseAuthUser = (options) => (ChildComponent) => {
const WithFirebaseAuthUserHOC = props => {
if(initAuthHelper.getInitAuthResult().success){
const Component = withAuthUser(options)(ChildComponent);
return <Component {...props}/>
const WithFirebaseAuthUserHOC = (props) => {
if (initAuthHelper.getInitAuthResult().success) {
const Component = withAuthUser(options)(ChildComponent);
return <Component {...props} />;
} else {
console.error(initAuthHelper.getInitAuthResult().error);
console.error("You must configure firebase auth before using firebase auth. See https://github.com/RocketChat/RC4Community/blob/master/app/components/auth/firebase/README.md");
return <ChildComponent {...props} initAuthResult={initAuthHelper.getInitAuthResult()}/>
console.error(
'You must configure firebase auth before using firebase auth. See https://github.com/RocketChat/RC4Community/blob/master/app/components/auth/firebase/README.md'
);
return (
<ChildComponent
{...props}
initAuthResult={initAuthHelper.getInitAuthResult()}
/>
);
}
}
WithFirebaseAuthUserHOC.displayName = "WithFirebaseAuthUserHOC";
};
WithFirebaseAuthUserHOC.displayName = 'WithFirebaseAuthUserHOC';
return WithFirebaseAuthUserHOC;
}
};

export const useFirebaseAuthUser = () => {
if(initAuthHelper.getInitAuthResult().success){
if (initAuthHelper.getInitAuthResult().success) {
return useAuthUser();
} else {
return createEmptyAuthUser();
}
}
};

const handleFBNotInitError = async (context,getServerSidePropsFunc) => {
const handleFBNotInitError = async (context, getServerSidePropsFunc) => {
console.error(initAuthHelper.getInitAuthResult().error);
console.error("You must configure firebase auth before using firebase auth. See https://github.com/RocketChat/RC4Community/blob/master/app/components/auth/firebase/README.md");
console.error(
'You must configure firebase auth before using firebase auth. See https://github.com/RocketChat/RC4Community/blob/master/app/components/auth/firebase/README.md'
);

const AuthUser = createEmptyAuthUser();
context.AuthUser = AuthUser;

const AuthUserSerialized = AuthUser.serialize();
let returnData = {props: {AuthUserSerialized}};
if(getServerSidePropsFunc) {
let returnData = { props: { AuthUserSerialized } };

if (getServerSidePropsFunc) {
// a getServerSideProps function is passed
const composedProps = (await getServerSidePropsFunc(context)) || {};
if(composedProps){
if(composedProps.props){
returnData = { ...composedProps }
returnData.props.AuthUserSerialized = AuthUserSerialized
} else if(composedProps.notFound || composedProps.redirect) {
if (composedProps) {
if (composedProps.props) {
returnData = { ...composedProps };
returnData.props.AuthUserSerialized = AuthUserSerialized;
} else if (composedProps.notFound || composedProps.redirect) {
// If composedProps returned a 'notFound' or 'redirect' key
// (as per official doc: https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props)
// it means it contains a custom dynamic routing logic that should not be overwritten
returnData = {...composedProps}
returnData = { ...composedProps };
}
}
}
return returnData;
}
};

export const withFirebaseAuthUserSSR = (options) => (getServerSidePropsFunc) => async (context) => {
if(initAuthHelper.getInitAuthResult().success){
if (initAuthHelper.getInitAuthResult().success) {
return withAuthUserSSR(options)(getServerSidePropsFunc)(context);
} else {
// firebase is uninitialised due to some error
return (await handleFBNotInitError(context,getServerSidePropsFunc));
return await handleFBNotInitError(context, getServerSidePropsFunc);
}
}
};

export const withFirebaseAuthUserTokenSSR = (options) => (getServerSidePropsFunc) => async (context) => {
if(initAuthHelper.getInitAuthResult().success){
return withAuthUserTokenSSR(options)(getServerSidePropsFunc)(context);
} else {
// firebase is uninitialised due to some error
return (await handleFBNotInitError(context,getServerSidePropsFunc));
}
}
export const withFirebaseAuthUserTokenSSR =
(options) => (getServerSidePropsFunc) => async (context) => {
if (initAuthHelper.getInitAuthResult().success) {
return withAuthUserTokenSSR(options)(getServerSidePropsFunc)(context);
} else {
// firebase is uninitialised due to some error
return await handleFBNotInitError(context, getServerSidePropsFunc);
}
};

export default {
getInitAuthResult,
Expand All @@ -183,5 +195,5 @@ export default {
useFirebaseAuthUser,
withFirebaseAuthUser,
withFirebaseAuthUserSSR,
withFirebaseAuthUserTokenSSR
withFirebaseAuthUserTokenSSR,
};
Loading