initial commit

This commit is contained in:
2018-09-10 18:14:33 +02:00
commit 5e2c8ffb31
22 changed files with 8528 additions and 0 deletions

47
src/App.js Normal file
View File

@@ -0,0 +1,47 @@
import React, { Component } from 'react';
/*
* Functions import
*/
/*
* Components import
*/
import Loading from './components/Loading';
import Main from './pages/Main';
const App = inject("rootStore") ( observer(
class App extends Component {
constructor(props) {
super(props);
//Stored information
this.stores = this.props.rootStore.stores;
}
componentDidMount() {
//Overwrite body design
const body = document.getElementsByTagName('body')[0];
body.style.margin = '0';
body.style.padding = '0';
body.style.overflow = 'hidden';
//Load app
this.stores.rootStore.loadApp();
}
render() {
if(this.stores.rootStore.isLoaded.app === true) {
if(this.stores.authStore.userData.uid !== null) {
return(<Main />);
} else {
return(<Login />);
}
} else {
return(<Loading />);
}
);
}
));
export default App;

9
src/App.test.js Normal file
View File

@@ -0,0 +1,9 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});

7
src/index.js Normal file
View File

@@ -0,0 +1,7 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

View File

@@ -0,0 +1,117 @@
// In production, we register a service worker to serve assets from local cache.
// 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 the "N+1" visit to a page, since previously
// cached resources are updated in the background.
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.
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 default function register() {
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);
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/facebookincubator/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. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl);
// 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://goo.gl/SC7cgQ'
);
});
} else {
// Is not local host. Just register service worker
registerValidSW(swUrl);
}
});
}
}
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
} 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.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl);
}
})
.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();
});
}
}

156
src/stores/authStore.js Normal file
View File

@@ -0,0 +1,156 @@
import { observable } from 'mobx';
import alertify from 'alertify.js';
//Firebase
var firebase = require('./fb').fb
var firebase_orig = require('./fb').firebase
// Initialize Cloud Firestore through Firebase
var db = firebase.firestore();
class AuthStore {
/*#######################################################
## Vars
##
## userData
/*#######################################################*/
//Authentification information, for example user data of logged in user
//auth is userData result from auth().onAuthStateChanged()
//User information of logged in user
userData = observable({
uid: null,
userData: null
});
/*#######################################################
## Functions
##
## load
## getUserInfo
## verifyPhone
## signOut
/*#######################################################*/
load() {
//Load all auth related things
console.info("Loading authStore");
this.stores.rootStore.isLoaded.app = false;
firebase.auth().onAuthStateChanged((user) => {
if (user) {
//Logged in
console.info("Logged in as " + user.uid);
Object.assign(this.userData, {
uid: user.uid
});
console.info("AuthStore loaded");
this.stores.rootStore.isLoaded.app = true;
} else {
//Logged out
console.info("Logged out");
Object.assign(this.userData, {
uid: null
});
console.info("AuthStore loaded");
this.stores.rootStore.isLoaded.app = true;
}
});
}
getUserInfo(userId) {
//Returns all user info from firestore.
//Param: userId
//Returns a promise
return new Promise(function (resolve, reject) {
var docRef = db.collection("users").doc(userId);
return docRef.get().then((doc) => {
if (doc.exists) {
resolve(doc.data());
} else {
// doc.data() will be undefined in this case
alertify.delay(0).error("Base Web doesn't support signing up yet. Please install the mobile app to sign up! Refresh Base Web after!");
console.error("User with id " + userId + " not found in user db!");
reject()
}
}).catch(function(error) {
console.error("Error getting document:", error);
reject()
});
});
}
createSignInRecaptcha(phoneNumber) {
firebase.auth().useDeviceLanguage();
window.recaptchaVerifier = new firebase_orig.auth.RecaptchaVerifier('sign-in-button', {
'size': 'invisible',
'callback': (response) => {
// reCAPTCHA solved, allow signInWithPhoneNumber.
this.signIn();
}
});
window.recaptchaVerifier.render().then(function(widgetId) {
window.recaptchaWidgetId = widgetId;
});
}
signIn(){
//Verify phone number and then sign in
console.info("Verify phone number");
const phoneNumber = this.userData.phoneCode + this.userData.phoneNumber;
alertify.log("....Sending verification code....");
firebase_orig.auth().signInWithPhoneNumber(phoneNumber, window.recaptchaVerifier).then(function (confirmationResult) {
//Code verification prompt
alertify.log("You will receive a SMS with a verification code soon.");
alertify.prompt("You will receive a SMS with a verification code soon. Please check your SMS on your phone. Enter the code below:",
function (val, ev) {
ev.preventDefault();
//Confirm code
confirmationResult.confirm(val).then(function (result){
alertify.success("Successfully signed in");
}).catch(function () {
alertify.error("Wrong code!");
});
},
function(ev) {
ev.preventDefault();
alertify.error("You've cancelled the phone verification");
}
);
})
.catch(function (error) {
window.recaptchaVerifier.reset(window.recaptchaWidgetId);
alertify.delay(0).error("Base Web doesn't support signing up yet. Please install the mobile app to sign up! Refresh Base Web after!");
console.error(error.code);
});
}
signOut(){
//Signes user out
firebase_orig.auth().signOut().then(function(){
}).catch(function(error){
console.error(error);
});
}
}
export default AuthStore;

48
src/stores/fb.js Normal file
View File

@@ -0,0 +1,48 @@
/*
* Firebase initializeApp START -------------------------
*/
var firebase = require('firebase/app');
require("firebase/auth");
require("firebase/firestore");
require("firebase/storage");
var config = {
apiKey: "AIzaSyCjWyrIzayUmEBcMcQyPvcXjNDkQONfJA8",
authDomain: "base-6d44c.firebaseapp.com",
databaseURL: "https://base-6d44c.firebaseio.com",
projectId: "base-6d44c",
storageBucket: "base-6d44c.appspot.com"
};
/*var config = {
apiKey: "AIzaSyDHnDObdPUAOFJfRpgC1tOG59NhheQYUmk",
authDomain: "netwoko-staging.firebaseapp.com",
databaseURL: "https://netwoko-staging.firebaseio.com",
projectId: "netwoko-staging",
storageBucket: "netwoko-staging.appspot.com"
};*/
var fb;
try {
fb = firebase.app();
//const auth = firebase.auth();
//console.log(auth);
}
catch (err) {
fb = firebase.initializeApp(config);
const firestore = firebase.firestore();
const settings = {timestampsInSnapshots: true};
firestore.settings(settings);
}
module.exports = {
fb,
firebase
}
/*
* Firebase initializeApp END --------------------------
*/

View File

@@ -0,0 +1,17 @@
const createId = function() {
//Creates a unique id for each chat bubble so that the animation can be triggered
var random = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < 10; i++)
random += possible.charAt(Math.floor(Math.random() * possible.length));
while(true) {
if(!document.getElementById(random)) {
return random;
}
}
}
export default createId;

View File

@@ -0,0 +1,3 @@
import { createBrowserHistory } from 'history';
export default createBrowserHistory();

View File

@@ -0,0 +1,19 @@
const promiseAll = function(promises) {
var results = [];
var completedPromises = 0;
return new Promise(function (resolve, reject) {
promises.forEach(function(promise, index) {
promise.then(function (value) {
results[index] = value;
completedPromises += 1;
if(completedPromises === promises.length) {
resolve(results);
}
}).catch(function (error) {
reject(error);
});
});
});
}
export default promiseAll;

52
src/stores/rootStore.js Normal file
View File

@@ -0,0 +1,52 @@
import { observable } from 'mobx';
import browser from 'browser-detect';
import alertify from 'alertify.js';
//Import stores
import AuthStore from './authStore';
class RootStore {
constructor() {
this.stores = {
rootStore: this,
authStore: new AuthStore()
}
//Pass stores down each store
this.stores.authStore.stores = this.stores;
}
/*#######################################################
## Vars
##
## isLoaded
/*#######################################################*/
//Includes all loading vars to test whether specific data is loaded or not
isLoaded = observable({
app: false
});
/*#######################################################
## Functions
##
## loadApp
## promiseAll
/*#######################################################*/
loadApp() {
console.log("Your browser: " + browser());
if(navigator.cookiesEnabled) {
alertify.delay(0).error("Please activate cookies in your browser! Refresh after");
}
//Load auth store
this.stores.authStore.load();
}
}
export default RootStore;