feat:完成登录功能

This commit is contained in:
橙子
2023-03-16 21:34:52 +08:00
parent a73920f4c3
commit 5f603e6652
17 changed files with 310 additions and 90 deletions

View File

@@ -14,6 +14,7 @@
"highlight": "^0.2.4",
"marked": "^4.2.12",
"mavon-editor": "^3.0.0",
"nprogress": "^0.2.0",
"pinia": "^2.0.32",
"vue": "^3.2.47",
"vue-router": "^4.1.6",
@@ -2806,6 +2807,11 @@
"resolved": "https://registry.npmmirror.com/normalize-wheel-es/-/normalize-wheel-es-1.2.0.tgz",
"integrity": "sha512-Wj7+EJQ8mSuXr2iWfnujrimU35R2W4FAErEyTmJoJ7ucwTn2hOUSsRehMb5RSYkxXGTM7Y9QpvPmp++w5ftoJw=="
},
"node_modules/nprogress": {
"version": "0.2.0",
"resolved": "https://registry.npmmirror.com/nprogress/-/nprogress-0.2.0.tgz",
"integrity": "sha512-I19aIingLgR1fmhftnbWWO3dXc0hSxqHQHQb3H8m+K3TnEn/iSeTZZOyvKXWqQESMwuUVnatlCnZdLBZZt2VSA=="
},
"node_modules/path-parse": {
"version": "1.0.7",
"resolved": "https://registry.npmmirror.com/path-parse/-/path-parse-1.0.7.tgz",
@@ -5948,6 +5954,11 @@
"resolved": "https://registry.npmmirror.com/normalize-wheel-es/-/normalize-wheel-es-1.2.0.tgz",
"integrity": "sha512-Wj7+EJQ8mSuXr2iWfnujrimU35R2W4FAErEyTmJoJ7ucwTn2hOUSsRehMb5RSYkxXGTM7Y9QpvPmp++w5ftoJw=="
},
"nprogress": {
"version": "0.2.0",
"resolved": "https://registry.npmmirror.com/nprogress/-/nprogress-0.2.0.tgz",
"integrity": "sha512-I19aIingLgR1fmhftnbWWO3dXc0hSxqHQHQb3H8m+K3TnEn/iSeTZZOyvKXWqQESMwuUVnatlCnZdLBZZt2VSA=="
},
"path-parse": {
"version": "1.0.7",
"resolved": "https://registry.npmmirror.com/path-parse/-/path-parse-1.0.7.tgz",

View File

@@ -14,6 +14,7 @@
"highlight": "^0.2.4",
"marked": "^4.2.12",
"mavon-editor": "^3.0.0",
"nprogress": "^0.2.0",
"pinia": "^2.0.32",
"vue": "^3.2.47",
"vue-router": "^4.1.6",

View File

@@ -1,11 +1,61 @@
import myaxios from '@/utils/request'
export function login(username, password){
return myaxios({
url: '/Account/login',
method: 'post',
data: {
username,
password
}
import request from '@/utils/request'
// 登录方法
export function login(username, password, code, uuid) {
const data = {
username,
password,
code,
uuid
}
return request({
url: '/account/login',
headers: {
isToken: false
},
method: 'post',
data: data
})
};
}
// 注册方法
export function register(data) {
return request({
url: '/register',
headers: {
isToken: false
},
method: 'post',
data: data
})
}
// 获取用户详细信息
export function getInfo() {
return request({
url: '/account',
method: 'get'
})
}
// 退出方法
export function logout() {
return request({
url: '/account/logout',
method: 'post'
})
}
// 获取验证码
export function getCodeImg() {
return request({
url: '/account/captcha-image',
headers: {
isToken: false
},
method: 'get',
timeout: 20000
})
}

View File

@@ -5,6 +5,7 @@
@node-click="handleNodeClick"
:expand-on-click-node="false"
node-key="id"
:default-expand-all='true'
>
<template #default="{ node, data }">

View File

@@ -3,6 +3,7 @@
:default-active="activeIndex"
class="el-menu-demo"
mode="horizontal"
ellipsis="false"
@select="handleSelect"
>
@@ -31,24 +32,32 @@
<div class="flex-grow" />
<RouterLink to="/discuss"> <el-menu-item index="5">搜索</el-menu-item></RouterLink>
<el-menu-item index="6">分享</el-menu-item>
<el-sub-menu index="7">
<template #title>学习</template>
<template #title>个人中心</template>
<el-menu-item index="7-1">学习 one</el-menu-item>
<el-menu-item index="7-2">学习 two</el-menu-item>
<el-menu-item index="7-3">学习 three</el-menu-item>
<el-menu-item index="7-3" @click="logout">登出</el-menu-item>
</el-sub-menu>
<el-menu-item index="6">分享</el-menu-item>
</el-menu>
</template>
<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import useUserStore from '@/stores/user.js'
const router = useRouter()
const userStore =useUserStore();
const activeIndex = ref('1')
const handleSelect = (key, keyPath) => {
console.log(key, keyPath)
}
const logout=async ()=>{
await userStore.logOut();
router.push("/login");
}
</script>
<style scoped>

View File

@@ -8,6 +8,7 @@ import './assets/main.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import directive from './directive' // directive
import "./permission"
const app = createApp(App)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {

View File

@@ -0,0 +1,65 @@
import router from './router'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isRelogin } from '@/utils/request'
import useUserStore from '@/stores/user'
NProgress.configure({ showSpinner: false });
const whiteList = ['/login', '/auth-redirect', '/bind', '/register'];
router.beforeEach((to, from, next) => {
NProgress.start()
if (getToken()) {
// to.meta.title && useSettingsStore().setTitle(to.meta.title)
/* has token*/
if (to.path === '/login') {
next({ path: '/' })
NProgress.done()
} else {
if (useUserStore().roles.length === 0)
{
isRelogin.show = true
// 判断当前用户是否已拉取完user_info信息
useUserStore().getInfo().then(() => {
isRelogin.show = false
//这里不需要动态路由
// usePermissionStore().generateRoutes().then(accessRoutes => {
// // 根据roles权限生成可访问的路由表
// accessRoutes.forEach(route => {
// if (!isHttp(route.path)) {
// router.addRoute(route) // 动态添加可访问路由表
// }
// })
// next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
// })
next({ ...to, replace: true })
}).catch(err => {
useUserStore().logOut().then(() => {
ElMessage.error(err)
next({ path: '/' })
})
})
} else {
next()
}
}
} else {
// 没有token
if (whiteList.indexOf(to.path) !== -1) {
// 在免登录白名单,直接进入
next()
} else {
next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
NProgress.done()
}
}
})
router.afterEach(() => {
NProgress.done()
})

View File

@@ -41,7 +41,7 @@ const router = createRouter({
},
{
name:'article',
path: '/article/:discussId',
path: '/article/:discussId/:articleId?',
component: () => import('../views/Article.vue')
},
{

View File

@@ -1,21 +1,77 @@
import { ref, computed } from 'vue'
import { login, logout, getInfo } from '@/apis/accountApi'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { defineStore } from 'pinia'
const useUserStore = defineStore('user',
{
state: () => ({
id:'',
token: '',
token: getToken(),
name: '登录用户',
icon: null,
roles: ['admin'],
roles: [],
permissions: ['*:*:*']
}),
getters: {
},
actions: {
increment() {
this.counter+=10
}
// 登录
login(userInfo) {
const userName = userInfo.userName.trim()
const password = userInfo.password
const code = userInfo.code
const uuid = userInfo.uuid
return new Promise((resolve, reject) => {
login(userName, password, code, uuid).then(res => {
setToken(res.token);
this.token = res.token;
resolve(res);
}).catch(error => {
reject(error)
})
})
},
// 获取用户信息
getInfo() {
return new Promise((resolve, reject) => {
getInfo().then(response => {
const res=response;
const user = res.user
const avatar = (user.icon == "" || user.icon == null) ? "" : import.meta.env.VITE_APP_BASE_API + "/file/"+user.icon;
if (res.roleCodes && res.roleCodes.length > 0) { // 验证返回的roles是否是一个非空数组
this.roles = res.roleCodes
this.permissions = res.permissionCodes
// this.roles = ["admin"];
// this.permissions=["*:*:*"]
} else {
this.roles = ['ROLE_DEFAULT']
}
// this.roles = ["admin"];
// this.permissions=["*:*:*"]
this.name = user.userName
this.avatar = avatar;
resolve(res)
}).catch(error => {
reject(error)
})
})
},
// 退出系统
logOut() {
return new Promise((resolve, reject) => {
logout().then(() => {
this.token = ''
this.roles = []
this.permissions = []
removeToken()
resolve()
}).catch(error => {
reject(error)
})
})
}
},
})
export default useUserStore;

View File

@@ -0,0 +1,13 @@
const TokenKey = 'Admin-Token'
export function getToken() {
return localStorage.getItem(TokenKey)
}
export function setToken(token) {
return localStorage.setItem(TokenKey, token)
}
export function removeToken() {
return localStorage.removeItem (TokenKey)
}

View File

@@ -1,5 +1,7 @@
import axios from 'axios';
import { getToken } from '@/utils/auth'
export let isRelogin = { show: false };
// import JsonBig from 'json-bigint'
const myaxios = axios.create({
baseURL:import.meta.env.VITE_APP_BASEAPI,
@@ -17,12 +19,12 @@ const myaxios = axios.create({
// }
// }
// }],
headers: {
'Authorization': 'Bearer ' + ""
},
})
// 请求拦截器
myaxios.interceptors.request.use(function (config) {
if (getToken()) {
config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
}
return config;
}, function (error) {
return Promise.reject(error);

View File

@@ -7,20 +7,12 @@
<el-col :span="24">
<InfoCard header="主题信息" text="展开" hideDivider="true">
<template #content>
<el-button style="width: 100%; margin-bottom: 0.8rem"
@click="loadDiscuss"
>首页</el-button
>
<el-button
v-hasPer="['bbs:article:add']"
@click="addArticle(0)"
type="primary"
style="width: 100%; margin-bottom: 0.8rem; margin-left: 0"
>添加子文章</el-button
>
<!--目录在这里 -->
<TreeArticleInfo :data="articleData" @remove="delArticle" @update="updateArticle"
@create="addNextArticle" @handleNodeClick="handleNodeClick" />
<el-button style="width: 100%; margin-bottom: 0.8rem" @click="loadDiscuss(true)">首页</el-button>
<el-button v-hasPer="['bbs:article:add']" @click="addArticle(0)" type="primary"
style="width: 100%; margin-bottom: 0.8rem; margin-left: 0">添加子文章</el-button>
<!--目录在这里 -->
<TreeArticleInfo :data="articleData" @remove="delArticle" @update="updateArticle" @create="addNextArticle"
@handleNodeClick="handleNodeClick" />
</template>
</InfoCard>
</el-col>
@@ -44,11 +36,7 @@
<el-col :span="14">
<el-row class="left-div">
<el-col :span="24">
<AvatarInfo
:size="50"
:showWatching="true"
:time="'2023-03-08 21:09:02'"
></AvatarInfo>
<AvatarInfo :size="50" :showWatching="true" :time="'2023-03-08 21:09:02'"></AvatarInfo>
<el-divider />
<h2>{{ discuss.title }}</h2>
@@ -71,29 +59,16 @@
<el-col :span="5">
<el-row class="right-div">
<el-col :span="24">
<InfoCard
class="art-info-right"
header="文章信息"
text="更多"
hideDivider="true"
>
<InfoCard class="art-info-right" header="文章信息" text="更多" hideDivider="true">
<template #content>
<div>
<ul class="art-info-ul">
<li>
<el-button
type="primary"
size="default"
@click="updateHander(route.params.discussId)"
>编辑</el-button
>
<el-button
style="margin-left: 1rem"
type="danger"
@click="delHander(route.params.discussId)"
>删除</el-button
>
<el-button type="primary" size="default"
@click="updateHander(route.params.discussId)">编辑</el-button>
<el-button style="margin-left: 1rem" type="danger"
@click="delHander(route.params.discussId)">删除</el-button>
</li>
<li>分类 <span>文章</span></li>
标签
@@ -110,12 +85,8 @@
<div>
<ul class="art-info-ul">
<li v-for="(item, i) in catalogueData" :key="i">
<el-button
style="width: 100%; justify-content: left"
type="primary"
text
>{{ `${i + 1} ${item}` }}</el-button
>
<el-button style="width: 100%; justify-content: left" type="primary" text>{{ `${i + 1} ${item}`
}}</el-button>
</li>
</ul>
</div>
@@ -151,7 +122,7 @@ import TreeArticleInfo from "@/components/TreeArticleInfo.vue";
import { useRoute, useRouter } from "vue-router";
import { get as discussGet, del as discussDel } from "@/apis/discussApi.js";
import {all as articleall,del as articleDel} from "@/apis/articleApi.js";
import { all as articleall, del as articleDel, get as articleGet } from "@/apis/articleApi.js";
//数据定义
const route = useRoute();
const router = useRouter();
@@ -160,7 +131,7 @@ const items = [{ user: "用户1" }, { user: "用户2" }, { user: "用户3" }];
//子文章数据
const articleData =ref([]);
const articleData = ref([]);
//主题内容
const discuss = ref({});
@@ -168,27 +139,37 @@ const discuss = ref({});
const catalogueData = ref([]);
//子文章初始化
const loadArticleData=async()=>
{
articleData.value= await articleall(route.params.discussId);
const loadArticleData = async () => {
articleData.value = await articleall(route.params.discussId);
}
//主题初始化
const loadDiscuss = async () => {
const loadDiscuss = async (isRewrite) => {
if (isRewrite) {
//跳转路由
router.push(`/article/${route.params.discussId}`);
}
discuss.value = await discussGet(route.params.discussId);
if (route.params.articleId != undefined) {
const respose = await articleGet(route.params.articleId);
discuss.value.content = respose.content;
}
ContentHander();
};
//加载文章及目录
const ContentHander=()=>{
//加载目录
var reg = /(#{1,6})\s(.*)/g;
const ContentHander = () => {
//加载目录
var reg = /(#{1,6})\s(.*)/g;
if(discuss.value.content)
{
var myArray = discuss.value.content.match(reg);
if (myArray != null) {
catalogueData.value = myArray.map((x) => {
return x.replace(/#/g, "").replace(/\s/g, "");
});
}
}
}
//添加树型子文章
const addArticle = (parentArticleId) => {
@@ -236,7 +217,7 @@ const updateHander = (discussId) => {
};
//跳转添加子菜单
const addNextArticle=(node,data)=>{
const addNextArticle = (node, data) => {
//跳转路由
var routerPer = {
path: "/editArt",
@@ -251,7 +232,7 @@ const addNextArticle=(node,data)=>{
}
//跳转更新子菜单
const updateArticle=(node,data)=>{
const updateArticle = (node, data) => {
//跳转路由
var routerPer = {
path: "/editArt",
@@ -260,27 +241,31 @@ const updateArticle=(node,data)=>{
artType: "article",
discussId: data.discussId,
parentArticleId: data.parentId,
articleId:data.id
articleId: data.id
},
};
router.push(routerPer);
}
//单机节点
const handleNodeClick=(data)=>{
discuss.value.content=data.content;
const handleNodeClick = (data) => {
//跳转路由
router.push(`/article/${route.params.discussId}/${data.id}`);
discuss.value.content = data.content;
ContentHander();
}
//删除子文章
const delArticle=( node,data)=>{
ElMessageBox.confirm(`确定是否删除编号[${data.id}]的子文章吗?`, "警告", {
const delArticle = (node, data) => {
ElMessageBox.confirm(`确定是否删除编号[${data.id}]的子文章吗?`, "警告", {
confirmButtonText: "确认",
cancelButtonText: "取消",
type: "warning",
}).then(async () => {
await articleDel(data.id);
await loadArticleData();
await articleDel(data.id);
await loadArticleData();
ElMessage({
type: "success",
message: "删除成功",
@@ -297,6 +282,7 @@ onMounted(async () => {
.comment {
height: 40rem;
}
.art-info-left .el-col {
margin-bottom: 1rem;
}

View File

@@ -1,3 +1,28 @@
<template>
这个是登录页面
</template>
<el-input v-model="loginForm.userName" placeholder="用户名" />
<el-input v-model="loginForm.password" placeholder="密码" />
<el-button type="primary" @click="login">登录</el-button>
</template>
<script setup>
import { reactive } from 'vue';
import { useRouter } from 'vue-router';
import useUserStore from '@/stores/user.js'
const userStore=useUserStore();
const router=useRouter();
const loginForm=reactive({
userName:"",
password:"",
uuid:"",
code:""
})
const login=async ()=>{
const response= await userStore.login(loginForm);
if( response.code==undefined)
{
router.push("/index")
}
}
</script>

View File

@@ -6,5 +6,5 @@ namespace Yi.Framework.Data.Auditing;
public interface IHasCreationTime
{
DateTime CreationTime { get; }
DateTime CreationTime { get; set; }
}

View File

@@ -14,7 +14,7 @@ namespace Yi.RBAC.Domain.Logs.Entities
{
[SugarColumn(ColumnName = "Id", IsPrimaryKey = true)]
public long Id { get; set; }
public DateTime CreationTime { get; }
public DateTime CreationTime { get; set; }
/// <summary>
/// 登录用户