Up to date CRA Started by Patrick Fic

This commit is contained in:
Patrick Fic
2020-09-29 14:06:16 -07:00
commit cc82bcc810
34 changed files with 13681 additions and 0 deletions

0
.env.development Normal file
View File

0
.env.production Normal file
View File

106
.gitignore vendored Normal file
View File

@@ -0,0 +1,106 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
client/node_modules
client/.pnp
client.pnp.js
admin/node_modules
admin/.pnp
admin.pnp.js
# testing
/coverage
client/coverage
admin/coverage
# production
/build
client/build
admin/build
# misc
.DS_Store
.env
client/.env
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
client/npm-debug.log*
client/yarn-debug.log*
client/yarn-error.log*
admin/npm-debug.log*
admin/yarn-debug.log*
admin/yarn-error.log*
#Firebase Ignore
# Logs
firebase/logs
firebase/*.log
firebase/npm-debug.log*
firebase/yarn-debug.log*
firebase/yarn-error.log*
firebase/firebase-debug.log*
# Firebase cache
firebase/.firebase/
# Firebase config
# Uncomment this if you'd like others to create their own Firebase project.
# For a team working on the same Firebase project(s), it is recommended to leave
# it commented so all members can deploy to the same project(s) in .firebaserc.
# .firebaserc
# Runtime data
firebase/pids
firebase/*.pid
firebase/*.seed
firebase/*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
firebase/lib-cov
# Coverage directory used by tools like istanbul
firebase/coverage
# nyc test coverage
firebase/.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
firebase/.grunt
# Bower dependency directory (https://bower.io/)
firebase/bower_components
# node-waf configuration
firebase/.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
firebase/build/Release
# Dependency directories
firebase/node_modules/
# Optional npm cache directory
firebase/.npm
# Optional eslint cache
firebase/.eslintcache
# Optional REPL history
firebase/.node_repl_history
# Output of 'npm pack'
firebase/*.tgz
# Yarn Integrity file
firebase/.yarn-integrity
# dotenv environment variables file
firebase/.env

68
README.md Normal file
View File

@@ -0,0 +1,68 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `yarn build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

49
package.json Normal file
View File

@@ -0,0 +1,49 @@
{
"name": "bodyshop",
"version": "0.1.0001",
"private": true,
"dependencies": {
"antd": "^4.6.1",
"co": "^4.6.0",
"dotenv": "^8.2.0",
"fingerprintjs2": "^2.1.2",
"node-sass": "^4.14.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-redux": "^7.2.1",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.3",
"redux": "^4.0.5",
"redux-persist": "^6.0.0",
"redux-saga": "^1.1.3",
"reselect": "^4.0.0",
"socket.io-client": "^2.3.0"
},
"scripts": {
"analyze": "source-map-explorer 'build/static/js/*.js'",
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.3",
"redux-logger": "^3.0.6"
}
}

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 766 B

35
public/index.html Normal file
View File

@@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#002366" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<!-- <link rel="apple-touch-icon" href="logo192.png" /> -->
<link rel="apple-touch-icon" href="logo240.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>New Web App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

13
public/logo.svg Normal file
View File

@@ -0,0 +1,13 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg
xmlns="http://www.w3.org/2000/svg"
id="etuajo-oikeus"
width="450"
height="450">
<path d="M 0,225 L 225,0 L 450,225 L 225,450" fill="#000000" />
<path d="M 225,431.25 L 18.75,225 L 225,18.75 L 431.25,225" fill="#ffffff" />
<path d="M 56.25,225 L 225,56.25 L 393.75,225 L 225,393.75" fill="#000000" />
<path d="M 225,386.25 L 63.75,225 L 225,63.75 L 386.25,225" fill="#ffd90f" />
</svg>

After

Width:  |  Height:  |  Size: 552 B

BIN
public/logo192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

BIN
public/logo512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

27
public/manifest.json Normal file
View File

@@ -0,0 +1,27 @@
{
"short_name": "ImEX Online",
"name": "ImEX Online",
"description": "The ultimate bodyshop management system.",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo240.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo1024.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#fff",
"background_color": "#fff",
"gcm_sender_id": "103953800507"
}

2
public/robots.txt Normal file
View File

@@ -0,0 +1,2 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *

21
src/App/App.jsx Normal file
View File

@@ -0,0 +1,21 @@
import { Layout } from "antd";
import React from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
const mapStateToProps = createStructuredSelector({});
const mapDispatchToProps = (dispatch) => ({});
export function App() {
return (
<Layout>
<Layout.Header>
<div> Header</div>
</Layout.Header>
<Layout.Content>
<div>Welcome to your new react app.</div>
</Layout.Content>
</Layout>
);
}
export default connect(mapStateToProps, mapDispatchToProps)(App);

0
src/App/App.styles.scss Normal file
View File

BIN
src/assets/logo192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

View File

@@ -0,0 +1,116 @@
import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
import "firebase/database";
import "firebase/analytics";
import "firebase/messaging";
import { store } from "../redux/store";
const config = JSON.parse(process.env.REACT_APP_FIREBASE_CONFIG);
firebase.initializeApp(config);
export const auth = firebase.auth();
export const firestore = firebase.firestore();
export const analytics = firebase.analytics();
export default firebase;
export const getCurrentUser = () => {
return new Promise((resolve, reject) => {
const unsubscribe = auth.onAuthStateChanged((userAuth) => {
unsubscribe();
resolve(userAuth);
}, reject);
});
};
export const updateCurrentUser = (userDetails) => {
return new Promise((resolve, reject) => {
const unsubscribe = auth.onAuthStateChanged((userAuth) => {
userAuth.updateProfile(userDetails).then((r) => {
unsubscribe();
resolve(userAuth);
});
}, reject);
});
};
let messaging;
try {
messaging = firebase.messaging();
// Project Settings => Cloud Messaging => Web Push certificates
messaging.usePublicVapidKey(process.env.REACT_APP_FIREBASE_PUBLIC_VAPID_KEY);
console.log("[FCM UTIL] FCM initialized successfully.");
} catch {
console.log("[FCM UTIL] Firebase Messaging is likely unsupported.");
}
export { messaging };
export const logImEXEvent = (eventName, additionalParams, stateProp = null) => {
const state = stateProp || store.getState();
const eventParams = {
shop:
(state.user && state.user.bodyshop && state.user.bodyshop.shopname) ||
null,
user:
(state.user && state.user.currentUser && state.user.currentUser.email) ||
null,
...additionalParams,
};
analytics.logEvent(eventName, eventParams);
};
if (messaging) {
messaging.onMessage(async (payload) => {
console.log("[FCM] UTILS Message received. ", payload);
navigator.serviceWorker.getRegistration().then((registration) => {
return registration.showNotification(
"[UTIL]" + payload.notification.title,
payload.notification
);
});
// if (!payload.clientId) return;
// // Get the client.
// const client = await clients.get(payload.clientId);
// // Exit early if we don't get the client.
// // Eg, if it closed.
// if (!client) return;
// // Send a message to the client.
// console.log("Posting to client.");
// client.postMessage({
// msg: "Hey I just got a fetch from you!",
// url: payload.request.url,
// });
// [START_EXCLUDE]
// Update the UI to include the received message.
//appendMessage(payload);
// [END_EXCLUDE]
});
messaging.onTokenRefresh(() => {
messaging
.getToken()
.then((refreshedToken) => {
console.log("[FCM] Token refreshed.");
// Indicate that the new Instance ID token has not yet been sent to the
// app server.
// setTokenSentToServer(false);
// // Send Instance ID token to app server.
// sendTokenToServer(refreshedToken);
// // [START_EXCLUDE]
// // Display new Instance ID token and clear UI of all previous messages.
// resetUI();
// [END_EXCLUDE]
})
.catch((err) => {
console.log("[FCM] Unable to retrieve refreshed token ", err);
// showToken("Unable to retrieve refreshed token ", err);
});
});
}

14
src/index.css Normal file
View File

@@ -0,0 +1,14 @@
body {
margin: 0;
height: 100%;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace;
}

21
src/index.js Normal file
View File

@@ -0,0 +1,21 @@
import "antd/dist/antd.css";
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { BrowserRouter } from "react-router-dom";
import { PersistGate } from "redux-persist/integration/react";
import App from "./App/App";
import "./index.css";
import { persistor, store } from "./redux/store";
require("dotenv").config();
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<PersistGate persistor={persistor}>
<App />
</PersistGate>
</BrowserRouter>
</Provider>,
document.getElementById("root")
);

View File

@@ -0,0 +1,30 @@
import ApplicationActionTypes from "./application.types";
export const setRooms = (rooms) => ({
type: ApplicationActionTypes.SET_ROOMS,
payload: rooms,
});
export const addRoom = (room) => ({
type: ApplicationActionTypes.ADD_ROOM,
payload: room,
});
export const addImages = ({ roomId, images }) => ({
type: ApplicationActionTypes.ADD_IMAGES_TO_ROOM,
payload: { roomId, images },
});
export const removeRoom = (roomId) => ({
type: ApplicationActionTypes.REMOVE_ROOM,
payload: roomId,
});
export const markNa = (roomId) => ({
type: ApplicationActionTypes.MARK_ROOM_NA,
payload: roomId,
});
export const joinRoom = (roomId) => ({
type: ApplicationActionTypes.JOIN_ROOM,
payload: roomId,
});

View File

@@ -0,0 +1,53 @@
import ApplicationActionTypes from "./application.types";
import _ from "lodash";
const INITIAL_STATE = {
rooms: [],
images: {
id: [],
},
};
const applicationReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case ApplicationActionTypes.SET_ROOMS:
return {
...state,
rooms: _.unionBy(state.rooms, action.payload, "id"),
};
case ApplicationActionTypes.ADD_ROOM:
return {
...state,
rooms: _.unionBy(state.rooms, [action.payload], "id"),
};
case ApplicationActionTypes.ADD_IMAGES_TO_ROOM:
return {
...state,
images: {
...state.images,
[action.payload.roomId]: _.unionBy(
state.images[action.payload.roomId] || [],
action.payload.images,
"filename"
),
},
};
case ApplicationActionTypes.REMOVE_ROOM:
return {
...state,
rooms: state.rooms.filter((r) => r.id !== action.payload),
};
case ApplicationActionTypes.MARK_ROOM_NA:
return {
...state,
rooms: state.rooms.map((room) =>
room.id === action.payload ? { ...room, na: true } : room
),
};
default:
return state;
}
};
export default applicationReducer;

View File

@@ -0,0 +1,40 @@
import { all, call, takeLatest } from "redux-saga/effects";
import ApplicationActionTypes from "./application.types";
export function* onJoinRoom() {
yield takeLatest(ApplicationActionTypes.JOIN_ROOM, joinRoom);
}
export function* joinRoom({ payload: roomId }) {
// console.log("function*joinRoom -> roomId", roomId);
// //TH eactual function
// const state = yield select();
// const room = state.application.rooms.filter((r) => r.id === roomId)[0];
// yield put(addImages({ roomId: null, images: [] }));
// if (room) {
// socket.emit(
// "join",
// {
// roomName: room.name,
// parentRoomName: room.parentName,
// password: Math.round(Math.random() * 1000).toString(),
// },
// co.wrap(function* (payload) {
// console.log("Checking Room", payload);
// if (payload.room && payload.room.id) {
// console.log("about to put");
// yield put(
// addImages({
// roomId: payload.room.id,
// images: payload.room.medias,
// })
// );
// } else {
// yield put(markNa(room.id));
// }
// })
// );
// }
}
export function* applicationSagas() {
yield all([call(onJoinRoom)]);
}

View File

@@ -0,0 +1,13 @@
import { createSelector } from "reselect";
const selectApplication = (state) => state.application;
export const selectRooms = createSelector(
[selectApplication],
(application) => application.rooms
);
export const selectImages = createSelector(
[selectApplication],
(application) => application.images
);

View File

@@ -0,0 +1,9 @@
const ApplicationActionTypes = {
SET_ROOMS: "SET_ROOMS",
ADD_ROOM: "ADD_ROOM",
ADD_IMAGES_TO_ROOM: "ADD_IMAGES_TO_ROOM",
REMOVE_ROOM: "REMOVE_ROOM",
MARK_ROOM_NA: "MARK_ROOM_NA",
JOIN_ROOM: "JOIN_ROOM",
};
export default ApplicationActionTypes;

18
src/redux/root.reducer.js Normal file
View File

@@ -0,0 +1,18 @@
import { combineReducers } from "redux";
import { persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import applicationReducer from "./application/application.reducer";
import userReducer from "./user/user.reducer";
const persistConfig = {
key: "root",
storage,
// blacklist: ["application"],
};
const rootReducer = combineReducers({
application: applicationReducer,
user: userReducer,
});
export default persistReducer(persistConfig, rootReducer);

6
src/redux/root.saga.js Normal file
View File

@@ -0,0 +1,6 @@
import { all, call } from "redux-saga/effects";
import { applicationSagas } from "./application/application.sagas";
export default function* rootSaga() {
yield all([call(applicationSagas)]);
}

33
src/redux/store.js Normal file
View File

@@ -0,0 +1,33 @@
import { createStore, applyMiddleware, compose } from "redux";
import { persistStore } from "redux-persist";
import { createLogger } from "redux-logger";
import createSagaMiddleware from "redux-saga";
import rootReducer from "./root.reducer";
import rootSaga from "./root.saga";
const sagaMiddleWare = createSagaMiddleware();
const middlewares = [sagaMiddleWare];
//if (process.env.NODE_ENV === "development") {
middlewares.push(createLogger({ collapsed: true, diff: true }));
//}
const composeEnhancers =
typeof window === "object" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
// Specify extensions options like name, actionsBlacklist, actionsCreators, serialize...
})
: compose;
const enhancer = composeEnhancers(
applyMiddleware(...middlewares)
// other store enhancers if any
);
export const store = createStore(rootReducer, enhancer);
sagaMiddleWare.run(rootSaga);
export const persistor = persistStore(store);
export default { store, persistStore };

View File

@@ -0,0 +1,84 @@
import UserActionTypes from "./user.types";
export const signInSuccess = (user) => ({
type: UserActionTypes.SIGN_IN_SUCCESS,
payload: user,
});
export const signInFailure = (errorMsg) => ({
type: UserActionTypes.SIGN_IN_FAILURE,
payload: errorMsg,
});
export const emailSignInStart = (emailAndPassword) => ({
type: UserActionTypes.EMAIL_SIGN_IN_START,
payload: emailAndPassword,
});
export const checkUserSession = () => ({
type: UserActionTypes.CHECK_USER_SESSION,
});
export const signOutStart = () => ({
type: UserActionTypes.SIGN_OUT_START,
});
export const signOutSuccess = () => ({
type: UserActionTypes.SIGN_OUT_SUCCESS,
});
export const signOutFailure = (error) => ({
type: UserActionTypes.SIGN_OUT_FAILURE,
payload: error,
});
export const unauthorizedUser = () => ({
type: UserActionTypes.UNAUTHORIZED_USER,
});
export const setUserLanguage = (language) => ({
type: UserActionTypes.SET_USER_LANGUAGE,
payload: language,
});
export const updateUserDetails = (userDetails) => ({
type: UserActionTypes.UPDATE_USER_DETAILS,
payload: userDetails,
});
export const updateUserDetailsSuccess = (userDetails) => ({
type: UserActionTypes.UPDATE_USER_DETAILS_SUCCESS,
payload: userDetails,
});
export const setLocalFingerprint = (fingerprint) => ({
type: UserActionTypes.SET_LOCAL_FINGERPRINT,
payload: fingerprint,
});
export const sendPasswordReset = (email) => ({
type: UserActionTypes.SEND_PASSWORD_RESET_EMAIL_START,
payload: email,
});
export const sendPasswordResetFailure = (error) => ({
type: UserActionTypes.SEND_PASSWORD_RESET_EMAIL_FAILURE,
payload: error,
});
export const sendPasswordResetSuccess = () => ({
type: UserActionTypes.SEND_PASSWORD_RESET_EMAIL_SUCCESS,
});
export const validatePasswordResetStart = (emailAndPin) => ({
type: UserActionTypes.VALIDATE_PASSWORD_RESET_START,
payload: emailAndPin,
});
export const validatePasswordResetSuccess = () => ({
type: UserActionTypes.VALIDATE_PASSWORD_RESET_SUCCESS,
});
export const validatePasswordResetFailure = (error) => ({
type: UserActionTypes.VALIDATE_PASSWORD_RESET_FAILURE,
payload: error,
});

View File

@@ -0,0 +1,90 @@
import UserActionTypes from "./user.types";
const INITIAL_STATE = {
currentUser: {
authorized: null,
//language: "en-US"
},
bodyshop: null,
fingerprint: null,
error: null,
conflict: false,
passwordreset: {
email: null,
error: null,
success: false,
},
authLevel: 0,
};
const userReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case UserActionTypes.SET_LOCAL_FINGERPRINT:
return { ...state, fingerprint: action.payload };
case UserActionTypes.VALIDATE_PASSWORD_RESET_START:
case UserActionTypes.SEND_PASSWORD_RESET_EMAIL_START:
return {
...state,
passwordreset: {
email: action.payload,
error: null,
success: false,
},
};
case UserActionTypes.VALIDATE_PASSWORD_RESET_FAILURE:
case UserActionTypes.SEND_PASSWORD_RESET_EMAIL_FAILURE:
return { ...state, passwordreset: { error: action.payload } };
case UserActionTypes.VALIDATE_PASSWORD_RESET_SUCCESS:
case UserActionTypes.SEND_PASSWORD_RESET_EMAIL_SUCCESS:
return {
...state,
passwordreset: { ...state.passwordreset, success: true },
};
case UserActionTypes.SIGN_IN_SUCCESS:
return {
...state,
currentUser: action.payload,
error: null,
};
case UserActionTypes.SIGN_OUT_SUCCESS:
return {
...state,
currentUser: { authorized: false },
error: null,
};
case UserActionTypes.UNAUTHORIZED_USER:
return {
...state,
error: null,
currentUser: { authorized: false },
};
case UserActionTypes.SET_USER_LANGUAGE:
return {
...state,
language: action.payload,
};
case UserActionTypes.UPDATE_USER_DETAILS_SUCCESS:
return {
...state,
currentUser: {
...state.currentUser,
...action.payload, //Spread current user details in.
},
};
case UserActionTypes.SIGN_IN_FAILURE:
case UserActionTypes.SIGN_OUT_FAILURE:
case UserActionTypes.EMAIL_SIGN_UP_FAILURE:
return {
...state,
error: action.payload,
};
default:
return state;
}
};
export default userReducer;

View File

@@ -0,0 +1,237 @@
import Fingerprint2 from "fingerprintjs2";
import LogRocket from "logrocket";
import { all, call, delay, put, select, takeLatest } from "redux-saga/effects";
import {
auth,
firestore,
getCurrentUser,
logImEXEvent,
updateCurrentUser,
} from "../../firebase/firebase.utils";
import {
checkInstanceId,
setInstanceConflict,
setInstanceId,
setLocalFingerprint,
signInFailure,
signInSuccess,
signOutFailure,
signOutSuccess,
unauthorizedUser,
updateUserDetailsSuccess,
sendPasswordResetFailure,
sendPasswordResetSuccess,
validatePasswordResetSuccess,
validatePasswordResetFailure,
setAuthlevel,
} from "./user.actions";
import UserActionTypes from "./user.types";
export function* onEmailSignInStart() {
yield takeLatest(UserActionTypes.EMAIL_SIGN_IN_START, signInWithEmail);
}
export function* signInWithEmail({ payload: { email, password } }) {
try {
logImEXEvent("redux_sign_in_attempt", { user: email });
const { user } = yield auth.signInWithEmailAndPassword(email, password);
yield put(
signInSuccess({
uid: user.uid,
email: user.email,
displayName: user.displayName,
photoURL: user.photoURL,
authorized: true,
})
);
} catch (error) {
yield put(signInFailure(error));
logImEXEvent("redux_sign_in_failure", { user: email, error });
}
}
export function* onCheckUserSession() {
yield takeLatest(UserActionTypes.CHECK_USER_SESSION, isUserAuthenticated);
}
export function* isUserAuthenticated() {
try {
logImEXEvent("redux_auth_check");
const user = yield getCurrentUser();
if (!user) {
yield put(unauthorizedUser());
return;
}
LogRocket.identify(user.email);
yield put(
signInSuccess({
uid: user.uid,
email: user.email,
displayName: user.displayName,
photoURL: user.photoURL,
authorized: true,
})
);
} catch (error) {
yield put(signInFailure(error));
}
}
export function* onSignOutStart() {
yield takeLatest(UserActionTypes.SIGN_OUT_START, signOutStart);
}
export function* signOutStart() {
try {
logImEXEvent("redux_sign_out");
yield auth.signOut();
yield put(signOutSuccess());
localStorage.removeItem("token");
} catch (error) {
yield put(signOutFailure(error.message));
}
}
export function* onUpdateUserDetails() {
yield takeLatest(UserActionTypes.UPDATE_USER_DETAILS, updateUserDetails);
}
export function* updateUserDetails(userDetails) {
try {
yield updateCurrentUser(userDetails.payload);
yield put(updateUserDetailsSuccess(userDetails.payload));
} catch (error) {
//yield put(signOutFailure(error.message));
//TODO error handling
}
}
export function* onSetInstanceId() {
yield takeLatest(UserActionTypes.SET_INSTANCE_ID, setInstanceIdSaga);
}
export function* setInstanceIdSaga({ payload: uid }) {
try {
const userInstanceRef = firestore.doc(`userInstance/${uid}`);
const fingerprint = Fingerprint2.x64hash128(
(yield Fingerprint2.getPromise({})).map((c) => c.value).join(""),
31
);
yield userInstanceRef.set({
timestamp: new Date(),
fingerprint,
});
yield put(setLocalFingerprint(fingerprint));
yield delay(5 * 60 * 1000);
if (process.env.NODE_ENV === "production") yield put(checkInstanceId(uid));
} catch (error) {
console.log("error", error);
//yield put(signOutFailure(error.message));
//TODO error handling
}
}
export function* onCheckInstanceId() {
yield takeLatest(UserActionTypes.CHECK_INSTANCE_ID, checkInstanceIdSaga);
}
export function* checkInstanceIdSaga({ payload: uid }) {
try {
const userInstanceRef = firestore.doc(`userInstance/${uid}`);
const snapshot = yield userInstanceRef.get();
let fingerprint = yield select((state) => state.user.fingerprint);
if (snapshot.data().fingerprint === fingerprint) {
yield delay(5 * 60 * 1000);
yield put(checkInstanceId(uid));
} else {
console.log("ERROR: Fingerprints do not match. Conflict detected.");
logImEXEvent("instance_confict");
yield put(setInstanceConflict());
}
} catch (error) {
console.log("error", error);
//TODO error handling
}
}
export function* onSignInSuccess() {
yield takeLatest(UserActionTypes.SIGN_IN_SUCCESS, signInSuccessSaga);
}
export function* signInSuccessSaga({ payload }) {
LogRocket.identify(payload.email);
if (!payload.email.includes("@imex.")) yield put(setInstanceId(payload.uid));
yield logImEXEvent("redux_sign_in_success");
}
export function* onSendPasswordResetStart() {
yield takeLatest(
UserActionTypes.SEND_PASSWORD_RESET_EMAIL_START,
sendPasswordResetEmail
);
}
export function* sendPasswordResetEmail({ payload }) {
try {
yield auth.sendPasswordResetEmail(payload, {
url: "https://imex.online/passwordreset",
});
console.log("Good should send.");
yield put(sendPasswordResetSuccess());
} catch (error) {
yield put(sendPasswordResetFailure(error.message));
}
}
export function* onValidatePasswordResetStart() {
yield takeLatest(
UserActionTypes.VALIDATE_PASSWORD_RESET_START,
validatePasswordResetStart
);
}
export function* validatePasswordResetStart({ payload: { password, code } }) {
try {
yield auth.confirmPasswordReset(code, password);
yield put(validatePasswordResetSuccess());
} catch (error) {
console.log("function*validatePasswordResetStart -> error", error);
yield put(validatePasswordResetFailure(error.message));
}
}
export function* onSetShopDetails() {
yield takeLatest(
UserActionTypes.SET_SHOP_DETAILS,
SetAuthLevelFromShopDetails
);
}
export function* SetAuthLevelFromShopDetails({ payload }) {
try {
const userEmail = yield select((state) => state.user.currentUser.email);
const authRecord = payload.associations.filter(
(a) => a.useremail === userEmail
);
yield put(setAuthlevel(authRecord[0] ? authRecord[0].authlevel : 0));
} catch (error) {
yield put(signInFailure(error.message));
}
}
export function* userSagas() {
yield all([
call(onEmailSignInStart),
call(onCheckUserSession),
call(onSignOutStart),
call(onUpdateUserDetails),
call(onSetInstanceId),
call(onCheckInstanceId),
call(onSignInSuccess),
call(onSendPasswordResetStart),
call(onValidatePasswordResetStart),
call(onSetShopDetails),
]);
}

View File

@@ -0,0 +1,18 @@
import { createSelector } from "reselect";
const selectUser = (state) => state.user;
export const selectCurrentUser = createSelector(
[selectUser],
(user) => user.currentUser
);
export const selectSignInError = createSelector(
[selectUser],
(user) => user.error
);
export const selectPasswordReset = createSelector(
[selectUser],
(user) => user.passwordreset
);

View File

@@ -0,0 +1,31 @@
const UserActionTypes = {
SET_CURRENT_USER: "SET_CURRENT_USER",
GOOGLE_SIGN_IN_START: "GOOGLE_SIGN_IN_START",
SIGN_IN_SUCCESS: "SIGN_IN_SUCCESS",
SIGN_IN_FAILURE: "SIGN_IN_FAILURE",
EMAIL_SIGN_IN_START: "EMAIL_SIGN_IN_START",
CHECK_USER_SESSION: "CHECK_USER_SESSION",
SIGN_OUT_START: "SIGN_OUT_START",
SIGN_OUT_SUCCESS: "SIGN_OUT_SUCCESS",
SIGN_OUT_FAILURE: "SIGN_OUT_FAILURE",
EMAIL_SIGN_UP_START: "EMAIL_SIGN_UP_START",
EMAIL_SIGN_UP_SUCCESS: "EMAIL_SIGN_UP_SUCCESS",
EMAIL_SIGN_UP_FAILURE: "EMAIL_SIGN_UP_FAILURE",
UNAUTHORIZED_USER: "UNAUTHORIZED_USER",
SET_USER_LANGUAGE: "SET_USER_LANGUAGE",
UPDATE_USER_DETAILS: "UPDATE_USER_DETAILS",
UPDATE_USER_DETAILS_SUCCESS: "UPDATE_USER_DETAILS_SUCCESS",
SET_SHOP_DETAILS: "SET_SHOP_DETAILS",
SET_INSTANCE_ID: "SET_INSTANCE_ID",
CHECK_INSTANCE_ID: "CHECK_INSTANCE_ID",
SET_INSTANCE_CONFLICT: "SET_INSTANCE_CONFLICT",
SET_LOCAL_FINGERPRINT: "SET_LOCAL_FINGERPRINT",
SEND_PASSWORD_RESET_EMAIL_START: "SEND_PASSWORD_RESET_EMAIL_START",
SEND_PASSWORD_RESET_EMAIL_FAILURE: "SEND_PASSWORD_RESET_EMAIL_FAILURE",
SEND_PASSWORD_RESET_EMAIL_SUCCESS: "SEND_PASSWORD_RESET_EMAIL_SUCCESS",
VALIDATE_PASSWORD_RESET_START: "VALIDATE_PASSWORD_RESET_START",
VALIDATE_PASSWORD_RESET_SUCCESS: "VALIDATE_PASSWORD_RESET_SUCCESS",
VALIDATE_PASSWORD_RESET_FAILURE: "VALIDATE_PASSWORD_RESET_FAILURE",
SET_AUTH_LEVEL: "SET_AUTH_LEVEL",
};
export default UserActionTypes;

149
src/serviceWorker.js Normal file
View File

@@ -0,0 +1,149 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === "localhost" ||
// [::1] is the IPv6 localhost address.
window.location.hostname === "[::1]" ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener("load", () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
"This web app is being served cache-first by a service " +
"worker. To learn more, visit https://bit.ly/CRA-PWA"
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then((registration) => {
// Start addition---
// https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#manual_updates
// Added code, as our application will be open for a long time and we are a SPA, we need
// to trigger checks for updates frequently
setInterval(() => {
console.log("Checking if service worker was updated in server");
registration.update();
}, 15 * 60 * 1000); // Every 15 mins check
// End addition---
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === "installed") {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
"New content is available and will be used when all " +
"tabs for this page are closed. See https://bit.ly/CRA-PWA."
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log("Content is cached for offline use.");
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch((error) => {
console.error("Error during service worker registration:", error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
console.log("Seeing if service worker cna be found.");
fetch(swUrl)
.then((response) => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get("content-type");
if (
response.status === 404 ||
(contentType != null && contentType.indexOf("javascript") === -1)
) {
// No service worker found. Probably a different app. Reload the page.
console.log("No service worker found. Unregistering.");
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
console.log("Service worker found. Registering.");
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
"No internet connection found. App is running in offline mode."
);
});
}
export function unregister() {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.ready.then((registration) => {
registration.unregister();
});
}
}

3
src/setupTests.js Normal file
View File

@@ -0,0 +1,3 @@
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });

12395
yarn.lock Normal file

File diff suppressed because it is too large Load Diff