Skip to content

Instantly share code, notes, and snippets.

@BrianAdams
Created August 4, 2016 19:15
Show Gist options
  • Save BrianAdams/3e528f315f93dc6ac0b9e104596c5dd5 to your computer and use it in GitHub Desktop.
Save BrianAdams/3e528f315f93dc6ac0b9e104596c5dd5 to your computer and use it in GitHub Desktop.
openscience-auth-question
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OpenScience</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="script.js"></script>
<!-- Auth0Lock script -->
<script src="//cdn.auth0.com/js/lock/10.0/lock.min.js"></script>
<!-- Setting the right viewport -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<!--leaflet!-->
<link rel="stylesheet" href="https://npmcdn.com/leaflet@1.0.0-rc.2/dist/leaflet.css" />
<script src="https://npmcdn.com/leaflet@1.0.0-rc.2/dist/leaflet.js"></script>
<!--data tables-->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs-3.3.6/jqc-1.12.3/dt-1.10.12/b-1.2.1/b-colvis-1.2.1/cr-1.3.2/fh-3.1.2/r-2.1.0/sc-1.4.2/se-1.2.0/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/bs-3.3.6/jqc-1.12.3/dt-1.10.12/b-1.2.1/b-colvis-1.2.1/cr-1.3.2/fh-3.1.2/r-2.1.0/sc-1.4.2/se-1.2.0/datatables.min.js"></script>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<nav class="navbar navbar-inverse" role="navigation">
<class="navbar-left">
<a class="navbar-brand" rel="home" href="">
<img style="max-width:200px; margin-top: -7px;"
src="/images/OpenROV.png">
</a>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li class="active"><a href="/">Home<span class="sr-only">(current)</span></a></li>
<li><a href="/about.html">About</a></li>
<li><input id="btn-login" class="btn btn-primary btn-login" type="submit" value="Login"/></li>
</ul>
</div>
</nav>
<div class="txt">
<h2> Welcome to OpenWater.</h2>
<h4> Use the following initial filters to get the data sets you want. </h4>
</div>
<div class="container col-xs-4">
<form class="form-vertical" role="form" style="width: 100%;">
<div class="form-group">
<label for="sel1">Start Month:</label>
<select class="form-control" id="sel1">
<option value=''>All</option>
<option value=1>January</option>
<option value=2>February</option>
<option value=3>March</option>
<option value=4>April</option>
<option value=5>May</option>
<option value=6>June</option>
<option value=7>July</option>
<option value=8>August</option>
<option value=9>September</option>
<option value=10>October</option>
<option value=11>November</option>
<option value=12>December</option>
</select>
</div>
<div class="form-group">
<label for="sel2">End Month:</label>
<select class="form-control" id="sel2">
<option value=''>All</option>
<option value=1>January</option>
<option value=2>February</option>
<option value=3>March</option>
<option value=4>April</option>
<option value=5>May</option>
<option value=6>June</option>
<option value=7>July</option>
<option value=8>August</option>
<option value=9>September</option>
<option value=10>October</option>
<option value=11>November</option>
<option value=12>December</option>
</select>
</div>
<div class="form-group">
<label for="sel3">Start Year:</label>
<select class="form-control" id="sel3">
<option value=''>All</option>
<option value=2015>2015</option>
<option value=2016>2016</option>
<option value=2017>2017</option>
</select>
</div>
<div class="form-group">
<label for="sel4">End Year:</label>
<select class="form-control" id="sel4">
<option value=''>All</option>
<option value=2015>2015</option>
<option value=2016>2016</option>
<option value=2017>2017</option>
</select>
</div>
<div class="form-group">
<label for="sel5">Continent:</label>
<select class="form-control" id="sel5">
<option value=''>All</option>
<option value="Africa">Africa</option>
<option value="Australia">Australia</option>
<option value="North America">North America</option>
<option value="South America">South America</option>
<option value="Europe">Europe</option>
<option value="Asia">Asia</option>
<option value="Antarctica">Antarctica</option>
</select>
</div>
<div class="form-group">
<label>Type of Data (results contain all checked types):</label> <br/>
<label class="checkbox-inline"><input type="checkbox" id="d" value="depth">Depth</label>
<label class="checkbox-inline"><input type="checkbox" id="t" value="temp">Temperature</label>
<label class="checkbox-inline"><input type="checkbox" id ="l" value="light">Light</label>
</div>
<div class="form-group">
<button id="submit" type="button" class="btn btn-primary"
onclick="sendData()" >Find Data</button>
</div>
</div>
</div>
</form>
</div>
<div class="container col-xs-7">
<div style="margin-top:-55px;" id="dtable" class="hide">
<table id="test" class="display">
<caption>Click on a row to download data file.</caption>
<thead>
<tr>
<th>Dive Date</th>
<th>Types of Data</th>
<th>Location</th>
<th>Max Depth (m)</th>
<th>Session ID</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script>
$(document).ready( function () {
$('#test').DataTable(
{
scrollY:'50vh',
scrollCollapse: true,
paging: false,
"columns": [{"name": "first", "orderable": true},
{"name": "second", "orderable": true},
{"name": "third", "orderable": true},
{"name": "fourth", "orderable": true},
{"name": "fifth", "visible": false}]});
});
//HAVE BRIAN CHECK THIS.
var lock = new Auth0Lock('BWcCxwJdMnHP7Y3pKCNtbp5IA6o5lKlb', 'openrov.auth0.com');
var myToken = localStorage.getItem('id_token');
var myProf = localStorage.getItem('id_profile');
var socketiourl = JSON.parse(myProf).dataOpenROVcom.service_url + '/socket.io.js';
//jquery documentation for load script command... script load or load script.
$.getScript(socketiourl);
var socket = io(JSON.parse(myProf).dataOpenROVcom.service_url, {
path: '/dataapi_10',
'multiplex': false,
query: 'token=' + myToken,
transports: ['websocket'],
reconnection:false,
timeout:30000,
"force new connection": true,
"connect timeout" : 5000});
document.getElementById('btn-login').addEventListener('click', function() {
lock.show({ authParams: { scope: 'openid profile offline_access' },icon:'https://s3.amazonaws.com/openrov-com-assets/openrov_community_banner_690x138.png',socialBigButtons: true },function (err, profile, token, access_token, state, refresh_token) {
if (err){
console.alert('Error logging in:', JSON.stringify(err));
self.eventEmitter.emit('cloudprofile-status',{loggedIn:false,profile:null});
localStorage.removeItem('id_profile');
self.loggedIn=false;
return; //TODO: Better handling of canceling
}
localStorage.setItem('id_token', token);
var jwt = jwt_decode(token)
var e = new Date(jwt.exp*1000);
localStorage.setItem('id_token_expires', e);
localStorage.setItem('refresh_token',refresh_token);
self.loggedIn=true;
localStorage.setItem('id_profile', JSON.stringify(profile));
self.profilePictureURL=profile.picture;
console.log(JSON.stringify(profile));
self.eventEmitter.emit('cloudprofile-status',{loggedIn:true,profile:profile});
});
});
lock.on("authenticated", function(authResult) {
lock.getProfile(authResult.idToken, function(error, profile) {
if (error) {
// Handle error
return;
}
localStorage.setItem('id_token', authResult.idToken);
localStorage.setItem('profile', JSON.stringify(profile));
});
});
//retrieve the profile:
var id_token = localStorage.getItem('id_token');
if (id_token) {
lock.getProfile(id_token, function (err, profile) {
if (err) {
return alert('There was an error getting the profile: ' + err.message);
}
document.getElementById('name').textContent = profile.name;
});
}
//WHAT IS HAPPENING UP TO HERE?
function sendData () {
var a = document.getElementById("sel1");
var b = document.getElementById("sel2");
var c = document.getElementById("sel3");
var d = document.getElementById("sel4");
var e = document.getElementById("sel5");
var sensors = [];
if (document.getElementById("d").checked) {
sensors.push("depth");
}
if (document.getElementById("t").checked) {
sensors.push("temp");
}
if (document.getElementById("l").checked) {
sensors.push("light");
}
var json = {"startMonth": a.options[a.selectedIndex].value,
"endMonth": b.options[b.selectedIndex].value,
"startYear": c.options[c.selectedIndex].value,
"endYear": d.options[d.selectedIndex].value,
"continent": e.options[e.selectedIndex].value,
"typesOfData": sensors};
socket.emit('query-session', json);
// console.dir(json);
// alert("You want data sets from the months " + a.options[a.selectedIndex].value +
// " to "+ b.options[b.selectedIndex].value + ", during the years "+
// c.options[c.selectedIndex].value +" to " + d.options[d.selectedIndex].value +
// ", on the continent " + json.continent + ", containing information about: " + sensors);
var tempObj = [{"name": "Megs", //also only on the file
"sensorTypes":["temp", "depth"],
"sensorSpec": ["TE: MS5837-30BA", "TE: MS5837-30BA"], //only have this on the file that gets downloaded
"date": "6/23/12",
"region": "Mombasa, Kenya",
"cordinates": "30.5, 50.5",
"notes": "It was a beautiful cloudless day.",
"data": [{"depth": 5, "temp": 25.3}, //make this an identifier so the server
{"depth": 6, "temp": 22.4}, //can pass down a data set when button is pressed.
{"depth": 8, "temp": 20.3}],
"maxDepth": 20,
"id": "lkajsfkl34"},
{"name": "Gill",
"sensorTypes":["light", "depth"],
"sensorSpec": ["not a clue", "TE: MS5837-30BA"],
"date": "4/26/17",
"region": "Maine, USA",
"cordinates": "130.2, 20.5",
"notes": "Rather cloudy, stormy day - rained a little.",
"data": [{"depth": 5, "temp": 25.3},
{"depth": 4, "temp": 21.4},
{"depth": 2, "temp": 30.3}],
"maxDepth": 10,
"id": "jklsdfjldsk"},
{"name": "Blake",
"sensorTypes":["temp", "depth", "light"],
"sensorSpec": ["TE: MS5837-30BA", "TE: MS5837-30BA", "hell if I know"],
"date": "1/3/17",
"region": "Hiraido, Japan",
"cordinates": "30.5, 50.5",
"notes": "It was a beautiful cloudless day.",
"data": [{"depth": 5, "temp": 18.3},
{"depth": 6, "temp": 15.4},
{"depth": 8, "temp": 10.3}],
"maxDepth": 20,
"id": "oweirfksj3"},
{"name": "Megs",
"sensorTypes":["temp", "depth"],
"sensorSpec": ["TE: MS5837-30BA", "TE: MS5837-30BA"],
"date": "7/23/12",
"region": "Mombasa, Kenya",
"cordinates": "30.5, 50.5",
"notes": "It was a beautiful cloudless day.",
"data": [{"depth": 5, "temp": 25.3},
{"depth": 6, "temp": 22.4},
{"depth": 8, "temp": 20.3}],
"maxDepth": 20,
"id": "098rfsk3kd"},
{"name": "Gill",
"sensorTypes":["light", "depth"],
"sensorSpec": ["not a clue", "TE: MS5837-30BA"],
"date": "9/16/17",
"region": "Maine, USA",
"cordinates": "130.2, 20.5",
"notes": "Rather cloudy, stormy day - rained a little.",
"data": [{"depth": 5, "temp": 25.3},
{"depth": 4, "temp": 21.4},
{"depth": 2, "temp": 30.3}],
"maxDepth": 120,
"id": "2kjejqrj3"},
{"name": "Blake",
"sensorTypes":["temp", "depth", "light"],
"sensorSpec": ["TE: MS5837-30BA", "TE: MS5837-30BA", "hell if I know"],
"date": "2/3/17",
"region": "Hiraido, Japan",
"cordinates": "30.5, 50.5",
"notes": "It was a beautiful cloudless day.",
"data": [{"depth": 5, "temp": 18.3},
{"depth": 6, "temp": 15.4},
{"depth": 8, "temp": 10.3}],
"maxDepth": 100,
"id": "lkfjds49"},
{"name": "Megs",
"sensorTypes":["temp", "depth"],
"sensorSpec": ["TE: MS5837-30BA", "TE: MS5837-30BA"],
"date": "3/23/12",
"region": "Mombasa, Kenya",
"cordinates": "30.5, 50.5",
"notes": "It was a beautiful cloudless day.",
"data": [{"depth": 5, "temp": 25.3},
{"depth": 6, "temp": 22.4},
{"depth": 8, "temp": 20.3}],
"maxDepth": 22,
"id": "984mdfjksdf"},
{"name": "Gill",
"sensorTypes":["light", "depth"],
"sensorSpec": ["not a clue", "TE: MS5837-30BA"],
"date": "8/16/17",
"region": "Maine, USA",
"cordinates": "130.2, 20.5",
"notes": "Rather cloudy, stormy day - rained a little.",
"data": [{"depth": 5, "temp": 25.3},
{"depth": 4, "temp": 21.4},
{"depth": 2, "temp": 30.3}],
"maxDepth": 10,
"id": "8dfksjkj3"},
{"name": "Blake",
"sensorTypes":["temp", "depth", "light"],
"sensorSpec": ["TE: MS5837-30BA", "TE: MS5837-30BA", "hell if I know"],
"date": "6/3/17",
"region": "Hiraido, Japan",
"cordinates": "30.5, 50.5",
"notes": "It was a beautiful cloudless day.",
"data": [{"depth": 5, "temp": 18.3},
{"depth": 6, "temp": 15.4},
{"depth": 8, "temp": 10.3}],
"maxDepth": 0,
"id": "lkkjfsd98jk"}];
// makeTable(tempObj);
}
socket.on('query-session-results', function(jsonAr) {
document.getElementById('dtable').className="display";
var table = $('#test').DataTable();
table.clear();
jsonAr.forEach(function(d) {
var typeOfData = d.sensorTypes;
if (typeOfData == undefined) {
typeOfData = "unknown";
} else {
console.log(typeOfData.join([separator = ' ']));
dataTypesStr = typeOfData.join([separator = ' '])
}
var eventDate = d.date;
if (eventDate == undefined) {
eventDate = "unknown";
}
var location = d.region;
if (location == undefined) {
location = "unknown";
}
var mDepth = d.maxDepth;
if (mDepth == undefined) {
mDepth = "unknown";
}
var sesID = d.sessionID;
if (sesID == undefined) {
sesID = "";
}
table.row.add([eventDate, dataTypesStr, location, mDepth, sesID]).draw();
})});
$('#test tbody').on( 'click', 'tr', function () {
var r = table.row(this);
socket.emit('get-data-file', r.data()[4]);
});
socket.on('data-file-results', function(data) {
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF
link.click(); // This will download the data file named "my_data.csv".
});
socket.on("error", function(error) {
if (error.type == "UnauthorizedError" || error.code == "invalid_token") {
// redirect user to login page perhaps?
log("User's token has expired");
}
resolve(new Error(error.message));});
socket.on('close', function() {
if (isSyncing){
log_trace('sync socket.io closed');
isSyncing=false;
reject(new Error('socket.io connection closed'));
}});
socket.on('connect_timeout',function(){
reject(new Error('Connection timed out'));
});
</script>
</body>
</html>
@BrianAdams
Copy link
Author

@mmalpani

Same problem here:
https://gist.github.com/BrianAdams/3e528f315f93dc6ac0b9e104596c5dd5#file-index-html-L179-L180

local storage is empty at this point. It is only set the first time after the user has gone through the login flow. Try this:

When your page starts, have the search feature buttons "disabled".
Create a "start" function that takes in the profile and token as a value and then connects to socket.io and enables the search buttons
When the page starts, check if you have a valid token in local storage. If you do, get the profile and token and call the "start" function above
After a successful login from Auth0, get the profile and token and call the "start" function above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment