目录结构
搭建服务器
express框架 mongoose连接数据库 配置passport 方便后面的token验证 server.js
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const passport = require('passport');
const users = require('./routes/api/users');
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const dbUrl = require('./config/keys').mongoURI;
mongoose.connect(dbUrl, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('数据库连接成功');
})
.catch(err => {
console.log('数据库连接失败', err);
})
app.use(passport.initialize());
require('./config/passport')(passport);
app.use('/api/users', users)
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
})
注册
使用bcrypt对密码加密
const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
const User = require('../../models/User');
router.post('/register', (req, res) => {
User.findOne({ email: req.body.email })
.then((user) => {
if (user) {
return res.status(400).json('邮箱已经被注册')
} else {
var avatar = gravatar.url(req.body.email, { s: '200', r: 'pg', d: 'mm' });
const newUser = new User({
name: req.body.name,
email: req.body.email,
avatar,
identity: req.body.identity,
password: req.body.password
})
bcrypt.genSalt(10, function (err, salt) {
bcrypt.hash(newUser.password, salt, function (err, hash) {
if (err) throw err;
newUser.password = hash;
newUser.save()
.then(user => res.json(user))
.catch(err => console.log(err))
});
});
}
})
})
登录
先使用bcrypt校验密码是否正确 使用jsonwebtokne 生成token jsonwebtoken
const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
const gravatar = require('gravatar');
const User = require('../../models/User');
const jwt = require('jsonwebtoken');
const Keys = require('../../config/keys');
router.post('/login', (req, res) => {
const email = req.body.email;
const password = req.body.password;
User.findOne({ email })
.then(user => {
if (!user) {
return res.status(404).json('邮箱不存在')
}
bcrypt.compare(password, user.password)
.then(isMatch => {
if (isMatch) {
const rule = { id: user.id, name: user.name, avatar: user.avatar, identity: user.identity };
jwt.sign(rule, Keys.secretOrKey, { expiresIn: 3600 }, (err, token) => {
if (err) throw err;
res.json({
success: true,
token: 'Bearer ' + token
})
})
} else {
return res.status(400).json('密码不匹配')
}
})
})
.catch(err => console.log(err))
})
携带Token获取信息
在server.js里面需要引入 passport并初始化、配置
router.get('/current', passport.authenticate('jwt', { session: false }), (req, res) => {
res.json({
id: req.user.id,
name: req.user.name,
email: req.user.email,
identity: req.user.identity
})
})
passport配置 config / passport.js
const JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
const opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
const mongoose = require('mongoose');
const User = mongoose.model('users');
const keys = require('../config/keys');
opts.secretOrKey = keys.secretOrKey;
module.exports = passport => {
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
User.findById(jwt_payload.id)
.then(user => {
if (user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => {
console.log(err);
})
}));
}
不携带token 携带token
|