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

Update setup_script to fetch landing page #101

Merged
merged 6 commits into from
May 7, 2021
Merged
Show file tree
Hide file tree
Changes from 5 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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ An item with no filter value is returned in all cases, and is thus also public.
## Local Development Environment
In order to quickly setup a development environment, make use of the `setup_script.sh` script. This will setup the project, initialize and seed the database configurations, import routes and initialize environment config files and generate the keys required.

First clone the <a href = "https://github.com/camicroscope/Caracal/tree/backup-dev">Caracal (backup-dev branch)</a>, <a href = "https://github.com/camicroscope/caMicroscope">caMicroscope</a> and the <a href = "https://github.com/camicroscope/Distro">Distro</a> repositories and make sure that all of them are in the same parent directory.

Run the script with `./setup_script` or `bash ./setup_script.sh`

The script is configured to load a database named "`camic`" from server at "`127.0.0.1`". In order to specify different name and host, simply pass the two while calling the script, like `./setup_script custom_host custom_database_name`

Run `npm start` to start the application and see it running at `localhost:4010`
12 changes: 10 additions & 2 deletions caracal.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ const Model = require('./handlers/modelTrainer.js');
const DataTransformationHandler = require('./handlers/dataTransformationHandler.js');
// TODO validation of data

const {connector} = require("./service/database/connector")

var WORKERS = process.env.NUM_THREADS || 4;

var PORT = process.env.PORT || 4010;
Expand Down Expand Up @@ -196,7 +198,13 @@ var startApp = function(app) {

throng(WORKERS, startApp(app));

const handler = new DataTransformationHandler(MONGO_URI, './json/configuration.json');
handler.startHandler();
/** initialize DataTransformationHandler only after database is ready */
connector.init().then(() => {
const handler = new DataTransformationHandler(MONGO_URI, './json/configuration.json');
handler.startHandler();
}).catch((e) => {
console.error("error connecting to database");
process.exit(1);
});

module.exports = app; // for tests
12 changes: 7 additions & 5 deletions service/database/connector.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ class MongoDBConnector {
*/
constructor() {
/** connection specifics */
const connectionString = process.env.MONGO_URI || "mongodb://127.0.0.1:27017";
const connectionString =
process.env.MONGO_URI || "mongodb://127.0.0.1:27017";
const databaseName = process.env.MONGO_DB || "camic";
const url = `${connectionString}/${databaseName}`;

Expand All @@ -42,10 +43,10 @@ class MongoDBConnector {

/** initialize an instance of mongoDB connection and kill process if connection fails */
const connector = new MongoDBConnector();
connector.init().catch((e) => {
console.error("error connecting to database");
process.exit(1);
});
// connector.init().catch((e) => {
// console.error("error connecting to database");
// process.exit(1);
// });
Copy link
Contributor

@YashKumarVerma YashKumarVerma May 7, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do not think these lines are needed anymore as this is being done in caracal.js

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, you are right! They have been commented out.


/**
* to load connection instances in database operations
Expand All @@ -58,4 +59,5 @@ const getConnection = (databaseName = "camic") => {
/** export the connector to be used by utility functions */
module.exports = {
getConnection,
connector,
};
72 changes: 72 additions & 0 deletions setup_script.sh
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,78 @@ if ! command -v "node" &>/dev/null; then
exit
fi

###
# check for the existence of required files in the Distro and camicroscope repository
###
echo "Checking for required files"

#if [[ ! -d ../Distro/db ]]
#then echo "../Distro/db does not exist"
# exit
#fi

if [[ ! -d ../Distro/config ]]
then echo "../Distro/config does not exist"
exit
fi

if [[ ! -d ../Distro/jwt_keys ]]
then echo "../Distro/jwt_keys does not exist"
exit
fi

if [[ ! -d ../caMicroscope ]]
then echo "../caMicroscope does not exist"
exit
fi
birm marked this conversation as resolved.
Show resolved Hide resolved

echo "Required files exist."

echo "Copying files..."

#if [[ ! -d ../data ]]
#then
# mkdir ../data
# cp -r ../Distro/db ../data/
#fi

if [[ ! -d ../config ]]
then
mkdir ../config
cp -r ../Distro/config ../config/
fi

if [[ ! -d ./static ]]
then
mkdir ./static
cp ../Distro/config/login.html ./static/login.html
fi

if [[ ! -d ./keys/jwt_keys ]]
then
cp -r ../Distro/jwt_keys ./keys/
fi

if [[ ! -f ./contentSecurityPolicy.json ]]
then
cp ../Distro/config/contentSecurityPolicy.json ./contentSecurityPolicy.json
fi

if [[ ! -f ./static/additional_links.json ]]
then
cp ../Distro/config/additional_links.json ./static/additional_links.json
fi

if [[ ! -d ./camicroscope ]]
then
cp -r ../caMicroscope ./camicroscope
fi

echo "Copying files complete!"




###
## try connecting to mongodb instance
###
Expand Down
8 changes: 8 additions & 0 deletions static/additional_links.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[
{
"displayName":"Bug Report",
"url":"https://goo.gl/forms/mgyhx4ADH0UuEQJ53",
"icon": "bug_report",
"openInNewTab": true
}
]
218 changes: 150 additions & 68 deletions static/login.html
Original file line number Diff line number Diff line change
@@ -1,77 +1,159 @@
<!DOCTYPE html>
<html>
<meta name="google-signin-client_id" content="XXX.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<a href="#" onclick="signOut();">Sign out</a>
<script>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
</script>
<script>
// google's jwk is here: https://www.googleapis.com/oauth2/v3/certs
function randomString(length) {
var bytes = new Uint8Array(length);
var random = window.crypto.getRandomValues(bytes);
var result = [];
var charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._~'
random.forEach(function (c) {
result.push(charset[c % charset.length]);
});
return result.join('');
}
<head>
<title>CaMicroscope</title>
<meta charset="utf-8" />
<meta name="google-signin-client_id" content="539699277901-buh78f048405grejogqbrskj233rt0d0.apps.googleusercontent.com">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="./apps/landing/main.css" />
<script type="text/javascript" src="./common/util.js"></script>
</head>
<body>
<header id="header">
<label style="color:white;padding:0 15px;font-size:20px;position:relative;">CaMicroscope<a target="_blank" style="position:absolute;right:2vw;" href="https://docs.google.com/forms/d/e/1FAIpQLScL91LxrpAZjU88GBZP9gmcdgdf8__uNUwhws2lzU6Lr4qNwA/viewform">Feedback</a></label>
<nav id="nav">
<ul>
<!-- <li><a target="_blank" href="https://docs.google.com/forms/d/e/1FAIpQLScL91LxrpAZjU88GBZP9gmcdgdf8__uNUwhws2lzU6Lr4qNwA/viewform">Feedback</a></li> -->
<!-- <li><a href="./login.html?logout=true">Sign Out</a></li> -->
</ul>
</nav>
</header>
<section id="main" class="wrapper" style="padding:3em;">
<div class="inner">
<header class="major">
<h2 style="margin:0;">caMicroscope</h2>
</header>
<!-- Content -->

function getUrlParam(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&#]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
<div class="content">
<p><strong>caMicroscope</strong> is a tool to view, label, and annotate biomedical images.</p>
<a href="#" class="image fit"><img src="./apps/landing/banner1.jpg" alt="" /></a>

function onSignIn(googleUser) {
var id_token = googleUser.getAuthResponse().id_token;
console.info(id_token)
// trade for camic token
var cookie_name = "token" // "token" is expected by elevate router
var base_deployment_url = window.location.toString().split("/").slice(0,-1).join("/")
var redirect_uri = base_deployment_url + "/login.html"
var default_redirect = base_deployment_url + "/apps/table.html"
var state
if (getUrlParam("state"))
{
state = decodeURIComponent(getUrlParam("state"))
}
if (!state){
state = default_redirect
}
</div>

if (id_token){
document.cookie = cookie_name + "=" + id_token;
fetch("./auth/Token/check",
{headers: {
'Authorization': "Bearer " + id_token
}}
).then(x=>x.json()).then(x=>{
console.log("{id provider", id_token)
console.log("{auth service}", x)
if (x.hasOwnProperty('token')){
document.cookie = cookie_name + "=" + x.token;
window.location = state
<div class="posts" style="justify-content: center;">
<!-- Organizer -->
<section class="post">
<a href="#" class="image"><img src="./apps/landing/camic.jpg" alt=""/></a>
<div class="content">
<h3>Please Sign In With Your Google Account</h3>
<div id="google-signin2"></div>
</div>
</section>
</div>
</section>

<script>
function onSuccess(googleUser) {
// don't if we're logging out
if (getUrlParam("logout")) {
removeUserConsentAcceptance(getUserId());
signOut();
deleteCookies();
console.log("logging out");
window.location.href = "./login.html";
} else {
window.alert("User not added")
window.location = "./apps/signup/signup"
var id_token = googleUser.getAuthResponse().id_token;
// console.info(id_token);
// trade for camic token
var cookie_name = "token"; // "token" is expected by elevate router
var base_deployment_url = window.location
.toString()
.split("/")
.slice(0, -1)
.join("/");
var redirect_uri = base_deployment_url + "/login.html";
var default_redirect = base_deployment_url + "/apps/table.html";
var state;
if (getUrlParam("state")) {
state = decodeURIComponent(getUrlParam("state"));
}
if (!state) {
state = default_redirect;
}
if (id_token) {
document.cookie = cookie_name + "=" + id_token;
fetch("./auth/Token/check", {
headers: {
Authorization: "Bearer " + id_token
}
})
.then(x => x.json())
.then(x => {
if (x.hasOwnProperty("token")) {
document.cookie = cookie_name + "=" + x.token;
let token_data = parseJwt(x.token);
window.location = "./apps/landing/landing.html";
} else {
window.alert("User not added");
window.location = "./apps/signup/signup.html";
}
});
}
}
}

})
}
}
function onFailure(error) {
console.error(error);
}

function renderButton() {
gapi.signin2.render('google-signin2', {
'scope': 'profile email',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': onSuccess,
'onfailure': onFailure
});
}

</script>
<html>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function() {
console.log("User signed out.");
});
}

function deleteCookies() {
var allcookies = document.cookie.split(";");
for (var i = 0; i < allcookies.length; i++) {
var cookie = allcookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;";
}
}

// google's jwk is here: https://www.googleapis.com/oauth2/v3/certs
function randomString(length) {
var bytes = new Uint8Array(length);
var random = window.crypto.getRandomValues(bytes);
var result = [];
var charset =
"0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._~";
random.forEach(function(c) {
result.push(charset[c % charset.length]);
});
return result.join("");
}

function getUrlParam(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&#]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return "";
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</script>

<script src="https://apis.google.com/js/platform.js?onload=renderButton" async defer></script>

<script>

</script>
</body>
</html>