如何建立注销用户的路由并从mongodb数据库中删除
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何建立注销用户的路由并从mongodb数据库中删除相关的知识,希望对你有一定的参考价值。
嗨,我正在学习制作基于网络的聊天应用程序,我已经定义了登录和主页的路由,并使用Angularjs sattelizer方法$ auth.logout并从本地存储中删除令牌以注销用户,现在我的要求是一旦用户注销我也想从数据库中删除用户对象,所以请让我知道如何制作后端路由以注销用户
这是My Server.js代码
var express = require('express');
var socketIO = require('socket.io');
var http = require('http');
var bcrypt = require('bcryptjs');
var bodyParser = require('body-parser');
var cors = require('cors');
var jwt = require('jwt-simple');
var moment = require('moment');
var mongoose = require('mongoose');
var path = require('path');
var request = require('request');
var config = require('./config');
var User = require('./models/user');
mongoose.connect(config.db);
var port = process.env.PORT || 3000;
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, '../public')));
function isAuthenticated(req, res, next){
if(!(req.headers && req.headers.authorization)){
return res.status(400).send({ message: 'You did not provide a JSON web token in the authorization header' });
}
var header = req.headers.authorization.split(' ');
var token = header[1];
var payload = jwt.decode(token, config.tokenSecret);
var now = moment().unix();
if(now > payload.exp){
return res.status(401).send({ message: 'Token has expired.' });
}
User.findById(payload.sub, function(err, user){
if(!user){
return res.status(400).send({ message: 'User no longer exists.' })
}
req.user = user;
next();
})
};
function createToken(user) {
var payload = {
exp: moment().add(14, 'days').unix(),
iat: moment().unix(),
sub: user._id
};
return jwt.encode(payload, config.tokenSecret);
};
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, '../public', 'index.html'));
});
app.post('/auth/login', function(req, res){
User.findOne({email: req.body.email}, '+password', function(err, user){
if(!user){
return res.status(401).send({message: { email: 'Incorrect email'}});
}
bcrypt.compare(req.body.password, user.password, function(err, isMatch){
if(!isMatch){
return res.status(401).send({message: {password: 'Incorrect password'}});
}
user = user.toObject();
delete user.password;
var token = createToken(user);
res.send({token: token, user: user});
})
})
})
app.post('/auth/signup', function(req, res){
User.findOne({email: req.body.email}, function(err, existingUser){
if(existingUser){
return res.status(409).send({ message: 'Email is already taken'});
}
var user = new User({
email: req.body.email,
password: req.body.password
});
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(user.password, salt, function(err, hash){
user.password = hash;
user.save(function(){
var token = createToken(user);
res.send({ token: token, user:user });
})
})
})
})
});
app.post('/auth/instagram', function(req, res){
var accessTokenUrl = 'https://api.instagram.com/oauth/access_token';
var params = {
client_id: req.body.clientId,
redirect_uri: req.body.redirectUri,
client_secret: config.clientSecret,
code: req.body.code,
grant_type: 'authorization_code'
};
request.post({ url: accessTokenUrl, form: params, json: true }, function(error, response, body){
if(req.headers.authorization){
User.findOne({ instagramId: body.user.id }, function(err, existingUser){
var token = req.headers.authorization.split(' ')[1];
var payload = jwt.decode(token, config.tokenSecret);
User.findById(payload.sub, '+password', function(err, localUser){
if(!localUser){
return res.status(400).send({message: 'User not found.'});
}
if(existingUser){
existingUser.email = localUser.email;
existingUser.password = localUser.password;
localUser.remove();
existingUser.save(function(){
var token = createToken(existingUser);
return res.send({ token: token, user: existingUser });
})
}else{
localUser.instagramId = body.user.id;
localUser.username = body.user.username;
localUser.fullName = body.user.full_name;
localUser.picture = body.user.profile_picture;
localUser.accessToken = body.access_token;
localUser.save(function(){
var token = createToken(localUser);
res.send({ token: token, user: localUser });
});
}
})
});
} else{
User.findOne({ instagramId: body.user.id }, function(err, existingUser){
if(existingUser){
var token = createToken(existingUser);
return res.send({ token: token, user: existingUser })
}
var user = new User({
instagramId: body.user.id,
username: body.user.username,
fullName: body.user.full_name,
picture: body.user.profile_picture,
accessToken: body.access_token
});
user.save(function(){
var token = createToken(user);
res.send({ token: token, user: user });
});
});
}
});
});
app.get('/api/chat', isAuthenticated, function(req, res){
console.log(User._id);
User.find({}, function(err, users){
var userMap = {};
users.forEach(function(user){
userMap[user] = user;
});
res.send(userMap);
});
});
app.get('/api/logout', isAuthenticated, function(req, res){
});
server.listen(port, function(){
console.log(`server is running on ${port}`);
})
model.js
var mongoose = require('mongoose');
var userSchema = mongoose.model('User', new mongoose.Schema({
instagramId: { type: String, index: true },
email: { type: String, unique: true, lowercase: true },
password: { type: String, select: false },
username: String,
fullName: String,
picture: String,
accessToken: String
}));
module.exports = ('User', userSchema);
答案
您可以使用mongoose findByIdAndRemove来实现此目的。登录用户必须存在于req对象中。您可以通过req.user._id访问他的猫鼬对象ID。使用上述方法按ID删除用户。
app.get('/api/logout', isAuthenticated, function(req, res){
console.log('User Id', req.user._id);
User.findByIdAndRemove(req.user._id, function(err){
if(err) res.send(err);
res.json({ message: 'User Deleted!'});
})
});
You can see the documentation from here
另一答案
我们可以使用.findOneAndRemove()
或.findByIdAndRemove()
的mongoose
app.get('/api/logout', isAuthenticated, function(req, res){
User.findOneAndRemove({email:email-data}, callback(err, res){})
});
我们可以从客户端发送电子邮件或文档ID,并替换硬编码的电子邮件
以上是关于如何建立注销用户的路由并从mongodb数据库中删除的主要内容,如果未能解决你的问题,请参考以下文章
谷歌驱动API的Android如何登录并从硬编码我的硬盘帐户注销无需用户交互?