密码及登录
Posted galaxy2490781718
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了密码及登录相关的知识,希望对你有一定的参考价值。
后端接口
const mongoose = require(‘mongoose‘) const bcrypt = require(‘bcrypt‘) const schema = new mongoose.Schema({ name: { type: String }, pwd: { type: String, select: false, // 密码不查询 set(val) { return bcrypt.hashSync(val, 10) // 存入数据库时加密 } } }) module.exports = mongoose.model(‘AdminUser‘, schema)
module.exports = app => { const AdminUser = require(‘../models/User‘) // 用户数据库 const jwt = require(‘jsonwebtoken‘) const bcrypt = require(‘bcrypt‘) const assert = require(‘http-assert‘) // assert(value, code, message)处理响应错误 app.post(‘/admin/api/login‘, async(req, res) => { const { name, pwd } = req.body // 1.根据用户名找用户 const user = await User.findOne({name}).select(‘+pwd‘) // select() + - assert(user, 422, ‘用户不存在‘) // 2.校验密码 const isValid = bcrypt.compareSync(pwd, user.pwd) assert(isValid, 422, ‘密码错误‘) // 3.返回token const token = jwt.sign({ id: user._id }, app.get(‘secret‘)) res.send({token}) }) // 登录拦截 app.use(‘/admin/api/rest‘, async(req, res, next) => { const token = String(req.headers.authorization || ‘‘).split(‘ ‘).pop() // 请求头authorization去除‘Bearer ‘ assert(token, 401, ‘请先登录‘) // 没有token let info jwt.verify(token, app.get(‘secret‘), (err, token) => { assert(token, 401, ‘非法登录‘) // 非法token(修改浏览器localStorage) info = token }) req.user = await User.findById(info.id) assert(req.user, 401, ‘登陆失败‘) await next() }) // 错误拦截 app.use(async(err, req, res, next) => { res.status(err.statusCode || 500).send({ message: err.message }) }) }
前端
import axios from ‘axios‘ import Vue from ‘vue‘ import router from ‘./router‘ const http = axios.create({ baseURL: ‘http://localhost:3000/admin/api‘ }) // axios响应拦截 http.interceptors.response.use(res => { return res }, err => { err.response.data.message && Vue.prototype.$message.error(err.response.data.message) if (err.response.status === 401) { router.push(‘/login‘) } return Promise.reject(err) }) // axios请求拦截 http.interceptors.request.use(config => { if (localStorage.token) { config.headers.Authorization = ‘Bearer ‘ + localStorage.token } return config }, err => { return Promise.reject(err) }) export default http
methods: { async login () { const { data: res } = await this.$http.post(‘/login‘, this.model) localStorage.token = res.token this.$message.success(‘登录成功‘) this.$router.push(‘/‘) } }
以上是关于密码及登录的主要内容,如果未能解决你的问题,请参考以下文章