后端
前端
欢迎来到172055110吕泽江的博客
{{ user.username }}
主页
发表博客
登录
退出
{{blog.title}}
{{blog.description}}
立即创建
重置
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
//全局参数属性
state: {
token: '',
userInfo: JSON.parse(sessionStorage.getItem("userInfo"))
},
//方法
mutations: {
// set方法
SET_TOKEN: (state, token) => {
state.token = token
//本地存储
localStorage.setItem("token", token)
},
SET_USERINFO: (state, userInfo) => {
state.userInfo = userInfo
//会话存储
sessionStorage.setItem("userInfo", JSON.stringify(userInfo))
},
REMOVE_INFO: (state) => {
state.token = ''
state.userInfo = {}
localStorage.setItem("token", '')
sessionStorage.setItem("userInfo", JSON.stringify(''))
}
},
getters: {
// get方法
getUser: state => {
return state.userInfo
}
},
actions: {
},
modules: {
}
})
import axios from 'axios'
import Element from 'element-ui'
import router from './router'
import store from './store'
//全局前缀url
axios.defaults.baseURL = "http://localhost:8081"
//前置拦截(请求访问)
axios.interceptors.request.use(config => {
return config
})
//后置拦截(弹窗提示)
axios.interceptors.response.use(response => {
let res = response.data;
//前
console.log("=================")
//内容
console.log(res)
//后
console.log("=================")
if (res.code === 200) {
//正常则返回并跳转至login登录
return response
} else {
//错误弹窗(element组件message消息提示),设置超时时间自动消失
Element.Message.error('错了哦,这是一条错误消息', {duration: 3 * 1000})
//阻止请求继续,结束login登录逻辑
return Promise.reject(response.data.msg)
}
},
//报错进入error逻辑
error => {
console.log(error)
if(error.response.data) {
//根据返回的信息赋值
error.message = error.response.data.msg
}
if(error.response.status === 401) {
store.commit("REMOVE_INFO")
router.push("/login")
}
//获取message信息,并阻止请求
Element.Message.error(error.message, {duration: 3 * 1000})
return Promise.reject(error)
}
)
立即创建
重置
{{ blog.title }}
编辑
import router from "./router";
//路由判断登录,根据路由配置文件的参数
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requireAuth)) { // 判断该路由是否需要登录权限
const token = localStorage.getItem("token")
console.log("------------" + token)
if (token) { // 判断当前的token是否存在;登录存入的token
if (to.path === '/login') {
} else {
next()
}
} else {
next({
path: '/login'
})
}
} else {
next()
}
})
package com.lvzejiang.controller;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lvzejiang.common.dto.LoginDto;
import com.lvzejiang.common.lang.Result;
import com.lvzejiang.entity.User;
import com.lvzejiang.service.UserService;
import com.lvzejiang.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
//登录接口设置
@RestController
public class AccountController {
@Autowired
UserService userService;
@Autowired
JwtUtils jwtUtils;
/**
* 默认账号:吕泽江
* 默认密码:55110
*
*/
@PostMapping("/login")
//body中获取loginDto
public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {
//查询用户
User user = userService.getOne(new QueryWrapper().eq("username", loginDto.getUsername()));
//Assert断言异常处理
Assert.notNull(user, "用户不存在");
//判断密码是否正确
if(!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
return Result.fail("密码不正确");
}
//密码正确则生成jwt(利用jwtUtils工具)
String jwt = jwtUtils.generateToken(user.getId());
//将jwt返回给Header
response.setHeader("Authorization", jwt);
response.setHeader("Access-control-Expose-Headers", "Authorization");
//封装结果
return Result.succ(MapUtil.builder()
.put("id", user.getId())
.put("username", user.getUsername())
.put("avatar", user.getAvatar())
.put("email", user.getEmail())
.map()
);
}
//退出接口设置
//认证权限
@RequiresAuthentication
@GetMapping("/logout")
public Result logout() {
SecurityUtils.getSubject().logout();
return Result.succ(null);
}
}
package com.lvzejiang.controller;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lvzejiang.common.lang.Result;
import com.lvzejiang.entity.Blog;
import com.lvzejiang.service.BlogService;
import com.lvzejiang.util.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
/**
*
* 前端控制器
*
* 博客接口
* @author 172055110吕泽江
* @since 2020-06-13
*/
@RestController
public class BlogController {
@Autowired
BlogService blogService;
//列表页(分页)
@GetMapping("/blogs")
public Result list(@RequestParam(defaultValue = "1") Integer currentPage){
//每页3条内容
Page page = new Page(currentPage, 3);
IPage pageData = blogService.page(page, new QueryWrapper().orderByDesc("created"));
return Result.succ(pageData);
}
//详情页(通过查询id)
@GetMapping("/blog/{id}")
public Result detail(@PathVariable(name = "id") Long id){
Blog blog = blogService.getById(id);
Assert.notNull(blog, "该文章已被删除");
return Result.succ(blog);
}
//编辑文章
//设置权限,登录之后才能编辑
@RequiresAuthentication
@PostMapping("/blog/edit")
public Result edit(@Validated @RequestBody Blog blog){
Blog temp = null;
//查询Id,有则为编辑状态,无则为添加状态
if(blog.getId() != null) {
temp = blogService.getById(blog.getId());
// 只能编辑自己的文章
System.out.println(ShiroUtil.getProfile().getId());
//调用ShiroUtil方法,返回Assert断言异常
Assert.isTrue(temp.getUserId().longValue() == ShiroUtil.getProfile().getId().longValue(), "没有权限编辑");
} else {
temp = new Blog();
temp.setUserId(ShiroUtil.getProfile().getId());
temp.setCreated(LocalDateTime.now());
temp.setStatus(0);
}
//编辑保存更新
BeanUtil.copyProperties(blog, temp, "id", "userId", "created", "status");
blogService.saveOrUpdate(temp);
return Result.succ(null);
}
}
package com.lvzejiang.controller;
import com.lvzejiang.common.lang.Result;
import com.lvzejiang.entity.User;
import com.lvzejiang.service.UserService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
*
* 前端控制器
*
*
* @author 172055110吕泽江
* @since 2020-06-13
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
//认证登录
@RequiresAuthentication
@GetMapping("/index")
public Result index() {
User user = userService.getById(1L); //查询id为1的用户
return Result.succ(user); //Result结果封装
}
@PostMapping("/save")
//Validated校验
public Result save(@Validated @RequestBody User user) {
return Result.succ(user);
}
}