I am trying to implement a persistent login for an angular application. By persistent I mean I am able to redirect to a new page or refresh without being logged out. This is kind of a two part question.
1) I am pretty sure my login is working but my logout button gives me a POST http://localhost:3000/api/sessions 500 (Internal Server Error)
2) I am now having trouble keeping the username showing in the top right corner of my app after a refresh or after a redirect for third party authentication. (I should also mention I am doing this with the getUser() and get a GET http://localhost:3000/api/users 401 (Unauthorized)
back
my code is:
html
<section class="top-bar-section" ng-controller="LoginCtrl">
<ul class="right">
<li>
<a ui-sref="dashboard">Dashboard</a>
</li>
<li class="pink">
<a ui-sref="post-item">Post New Item!</a>
</li>
<li>
<a ng-click='logout()'>Logout</a>
</li>
<li class="has-dropdown">
<a href=""><span ng-if="currentUser">{{ currentUser.username }}</span></a>
<ul class="dropdown">
<li><a href="http://google.com">Settings</a></li>
<li><a ng-click="logout()">Logout</a></li>
</ul>
</li>
</ul>
</section>
routes.js
app.post('/api/sessions', function(req, res, next) {
User.findOne({username: req.body.username})
.select('password').select('username')
.exec( function(err, user){
if (err) {return next(err)}
if (!user) {return res.send(401)}
bcrypt.compare(req.body.password, user.password, function (err, valid){
if (err) {return next(err)}
if (!valid) {return res.send(401)}
var token = jwt.encode({username: user.username}, config.secret)
res.send(token)
})
})
})
app.get('/api/users', function(req, res, next) {
if(!req.headers['x-auth']){
return res.send(401)
}
var auth = jwt.decode(req.headers['x-auth'], config.secret)
User.findOne({username: auth.username}, function (err,user){
if (err) {return next(err)}
res.json(user)
})
})
app.post('/api/users', function(req, res, next) {
var user = new User({username: req.body.username})
bcrypt.hash(req.body.password, 10, function (err, hash){
if (err) {return next (err)}
user.password = hash
user.save(function (err){
res.send(201)
})
})
})
angular.js
app.service('UserSvc', function($http, $window){
var svc = this;
svc.getUser = function() {
return $http.get('/api/users',{
headers: { 'X-Auth': this.token }
})
}
svc.login = function(username, password){
return $http.post('/api/sessions', {
username: username, password: password
}).then(function(val){
svc.token = val.data
// window.localStorage.token = val.data
return svc.getUser()
})
}
svc.logout = function() {
$http.post('/api/sessions', {
username: null, password: null
}).then(function(val){
svc.token = null
// window.localStorage.token = val.data
})
}
})
app.controller('LoginCtrl', function($scope, $location, UserSvc){
$scope.login = function(username, password) {
UserSvc.login(username, password)
.then(function(response) {
$scope.$emit('login', response.data)
$location.path('/dashboard');
})
}
$scope.logout = function() {
UserSvc.logout();
$scope.$emit('logout')
}
});
app.controller('ApplicationCtrl', function($scope, UserSvc) {
angular.element(document).ready(function () {
$scope.currentUser = UserSvc.getUser();
})
$scope.modalShown = true;
$scope.$on('login', function (_, user){
$scope.currentUser = user;
})
$scope.$on('logout', function (){
$scope.currentUser = null;
})
});
if anyone has any pointers please let me know! I have spent way to much time on this :(
1) When you logout, your /api/sessions
endpoint is looking for a user with the username of null
in your database, with something a query of User.findOne({username: null})
2) getUser() is setting headers with 'X-Auth'
(note the capitals) but you're checking for lowercase at your users endpoint with !req.headers['x-auth']
To make client side persistence I'd save the token in local storage using the $cookieStore service in angular. Its a key-value storage. To store the token in storage use:
$cookieStore.put('token', data.token)
and to retrieve it back use:
$cookieStore.get('token')
Hope that helped
@XxscurvyxX: You can also use $window.sessionStorage which works on the key/value pair basis and gives getter and setters.
Syntax:
$window.sessionStorage.setItem(key, value) // key: String value: String
$window.sessionStorage.getItem(key) // key: String
The key/value pairs stores in the session Storage until you close the tab or close the browser.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.