This repository has been archived on 2024-11-11. You can view files and clone it, but cannot push or open issues or pull requests.
socketio-jwt/example/socketsio-auth0-sample/views/index.pug
2016-07-21 18:14:59 +03:00

79 lines
2.7 KiB
Plaintext

extends layout
block content
script(src="https://cdn.auth0.com/js/lock/10.0/lock.min.js")
script(src="/socket.io/socket.io.js")
script(src="http://code.jquery.com/jquery-1.12.4.js")
div#login
button.btn Login
div#chat
ul#messages
form(id="chatForm" action="")
input(id="m" autocomplete="off")
button.btn Send
script.
var userProfile;
var userToken;
var lock = new Auth0Lock('#{env.AUTH0_CLIENT_ID}', '#{env.AUTH0_DOMAIN}');
var id_token = localStorage.getItem('id_token');
$('#chat').hide();
$('#login button').click(function (e) {
e.preventDefault();
lock.show();
});
lock.on('authenticated', function(authResult) {
lock.getProfile(authResult.idToken, function(error, profile) {
if (error) {
// Handle error
return;
}
console.log('connected and authenticated');
localStorage.setItem('id_token', authResult.idToken);
localStorage.setItem('profile', JSON.stringify(profile));
userProfile = profile;
id_token = authResult.idToken;
openChat();
});
});
if (id_token) {
lock.getProfile(id_token, function (err, profile) {
if (err) {
return alert('There was an error getting the profile: ' + err.message);
}
userProfile = profile;
openChat();
});
}
function openChat() {
var socket = io();
socket
.on('connect', function (msg) {
console.log("connected");
socket.emit('authenticate', {token: id_token}); // send the jwt
})
.on('authenticated', function () {
//Do
$('#login').hide();
$('#chat').show();
$('form').submit(function (event) {
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
})
.on('unauthorized', function(msg){
console.log("unauthorized: " + JSON.stringify(msg.data));
throw new Error(msg.data.type);
})
.on('chat message', function (msg) {
console.log("msg");
$('#messages').append($('<li>').text(msg));
});
};