Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@
"dotenv": "^2.0.0",
"express": "^4.14.0",
"express-bearer-token": "^2.1.0",
"jsonwebtoken": "^7.1.6"
"jsonwebtoken": "^7.1.8"
}
}
17 changes: 13 additions & 4 deletions public/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ app.config(function ($httpProvider) {
})
.service('jwtInterceptor', function jwtInterceptor(){
//TODO: Attach the token to every request.
return {
request: function(config) {
if (localStorage.jwt) {
config.headers.Authorization = 'Bearer ' + localStorage.jwt;
}
return config;
}
}
})

app.controller('jwtController',['$scope','$http', function($scope,$http) {
Expand All @@ -14,15 +22,16 @@ app.controller('jwtController',['$scope','$http', function($scope,$http) {
$scope.login = function() {
$http.get('/login').then(function (res) {
//TODO:Store token in localstorage
localStorage.jwt = res.data.token;
});
};

$scope.protected = function () {
$http.get('/protected').then(function successfulCallback(response) {
$scope.view.response = response.data;
}, function errorCallback(response) {
$scope.view.response = "ERROR";
console.log(response);
console.log(response.data)
if (localStorage.jwt) {
$scope.view.response = response.data;
}
});
}
}]);
12 changes: 12 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,23 @@ app.use(express.static('public'));

app.get('/login',function (req,res,next) {
//TODO: Return a token
var user = {
name: 'Sam'
}
// console.log(localStorage)
res.json({token:jwt.sign(user,process.env.SECRET)});
});

app.use(function (req,res,next) {
//TODO: Implement app level middleware to protect the /protected route
//TODO: Verify the token before allowing access to /protected
jwt.verify(req.token, process.env.SECRET, function(err, decoded) {
if (!err) {
next();
} else {
res.status(400).send('Bad request');
}
})
});

app.get('/protected',function (req,res,next) {
Expand Down