Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: 前后端登录功能修复 & 联调 #146

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ export class AuthController {
@Post('logout')
@UseGuards(AuthGuard)
async logout(@Body() body: LogoutAuthDto) {
return this.authService.logout(body.email);
return this.authService.logout(body.token);
}
}
GaoNeng-wWw marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { encry, User } from '@app/models';
import { Repository } from 'typeorm';
import { JwtService } from '@nestjs/jwt';
import { RedisService } from '../../libs/redis/redis.service';
import {HttpException, HttpStatus, Injectable} from '@nestjs/common';
import {CreateAuthDto} from './dto/create-auth.dto';
import {InjectRepository} from '@nestjs/typeorm';
import {encry, User} from '@app/models';
import {Repository} from 'typeorm';
import {JwtService} from '@nestjs/jwt';
import {RedisService} from '../../libs/redis/redis.service';

@Injectable()
export class AuthService {
Expand All @@ -13,21 +13,24 @@ export class AuthService {
private user: Repository<User>,
private jwtService: JwtService,
private readonly redisService: RedisService
) {}
) {
}

async getToken(userId: string): Promise<string | null> {
return this.redisService.getUserToken(`user:${userId}:token`);
}

async logout(email: string): Promise<void> {
async logout(token: string): Promise<void> {
//通过token解析email
const decoded = await this.jwtService.verify(token);
//退出登录后,将token从Redis删除
await this.redisService.delUserToken(`user:${email}:token`);
await this.redisService.delUserToken(`user:${decoded.email}:token`);
return;
}

async login(dto: CreateAuthDto) {
const { email, password } = dto;
const userInfo = await this.user.findOne({ where: { email } });
const {email, password} = dto;
const userInfo = await this.user.findOne({where: {email}});
if (userInfo === null || userInfo.deleteAt != 0) {
throw new HttpException('该用户不存在', HttpStatus.NOT_FOUND);
}
Expand All @@ -44,6 +47,8 @@ export class AuthService {
await token,
await parseInt(process.env.REDIS_SECONDS)
);
return token;
return {
token: await token,
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ import { IsNotEmpty } from 'class-validator';

export class LogoutAuthDto {
@IsNotEmpty()
email: string;
token: string;
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { IsOptional } from 'class-validator';

import { Transform} from 'class-transformer';
import * as process from "process";
export class PaginationQueryDto {
@IsOptional()
page?: number;
@Transform(value => isNaN(Number(value)) ? 1 : Number(value))
page?: number = Number(process.env.PAGITION_PAGE);

@IsOptional()
limit?: number;
@Transform(value => isNaN(Number(value)) ? 10 : Number(value))
limit?: number = Number(process.env.PAGITION_PAGE);
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export class UserService {
}

async getUserInfo(email: string, relations: string[] = []) {
return this.userRep.findOne({
return await this.userRep.findOne({
where: { email, deleteAt: 0 },
select: [
'id',
Expand Down
6 changes: 3 additions & 3 deletions packages/toolkits/pro/template/tinyvue/.env
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
VITE_CONTEXT=/vue-pro/
VITE_BASE_API=/api
VITE_SERVER_HOST= http://127.0.0.1:7001
VITE_USE_MOCK= true
VITE_MOCK_IGNORE= /api/user/userInfo,/api/user/login,/api/user/register,/api/employee/getEmployee
VITE_SERVER_HOST= http://127.0.0.1:3000
VITE_USE_MOCK= false
VITE_MOCK_IGNORE= /api/user/userInfo,/api/user/login,/api/user/register,/api/employee/getEmployee
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const proxyConfig = {
target: loadEnv('', process.cwd()).VITE_SERVER_HOST,
changeOrigin: true,
logLevel: 'debug',
rewrite: (path) =>
rewrite: (path: string) =>
path.replace(
new RegExp(`${loadEnv('', process.cwd()).VITE_BASE_API}`),
''
Expand Down
10 changes: 1 addition & 9 deletions packages/toolkits/pro/template/tinyvue/src/api/interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,7 @@ axios.interceptors.request.use(
// add response interceptors
axios.interceptors.response.use(
(response: AxiosResponse<HttpResponse>) => {
const res = response.data;
if (res.code !== '0') {
res.errMsg &&
Modal.message({
message: res.errMsg,
status: 'error',
});
return Promise.reject(new Error(res.errMsg || 'Error'));
}
const res = response;
return res;
},
(error) => {
Expand Down
31 changes: 26 additions & 5 deletions packages/toolkits/pro/template/tinyvue/src/api/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,19 @@ import axios from 'axios';
import { UserInfo } from '@/store/modules/user/types';

export interface LoginData {
email: string;
password: string;
}

export interface LogoutData {
token: string | null;
}

export interface RegisterData {
username: string;
email: string;
password: string;
roleIds: number[];
}

export interface LoginDataMail {
Expand All @@ -28,18 +39,28 @@ export interface UserData {
}

export function login(data: LoginData) {
return axios.post<LoginRes>('/api/user/login', data);
return axios.post<LoginRes>('/api/auth/login', data);
}
export function loginMail(data: LoginDataMail) {
return axios.post<LoginRes>('/api/mail/login', data);
}

export function logout() {
return axios.post<LoginRes>('/api/user/logout');
export function logout(data: LogoutData) {
return axios.post<LoginRes>('/api/auth/logout', data);
}

// 获取全部用户
export function getAllUser() {
return axios.get<UserInfo>(`/api/user`);
}

// 获取单个用户
export function getUserInfo(email: string) {
return axios.get<UserInfo>(`/api/user/info/${email}`);
}

export function getUserInfo() {
return axios.get<UserInfo>(`/api/user/userInfo`);
export function delUser(email: string) {
return axios.delete<UserInfo>(`/api/user/${email}`);
}

export function updateUserInfo(data: UserInfo) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ export default function setupPermissionGuard(router: Router) {
crossroads();
} else {
try {
await userStore.info();
crossroads();
} catch (error) {
next({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
import { defineStore } from 'pinia';
import {defineStore} from 'pinia';
import {
login as userLogin,
loginMail as userLoginMail,
getUserInfo,
updateUserInfo,
logout as userLogout,
LoginData,
LoginDataMail,
loginMail as userLoginMail,
updateUserInfo,
getUserInfo,
getAllUser,
} from '@/api/user';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { UserState, UserInfo } from './types';
import {clearToken, getToken, setToken} from '@/utils/auth';
import {removeRouteListener} from '@/utils/route-listener';
import {UserInfo, UserState} from './types';

const useUserStore = defineStore('user', {
state: (): UserState => ({
userId: '10000',
username: 'admin',
id: '10000',
name: 'admin',
email: '[email protected]',
department: 'Tiny-Vue-Pro',
employeeType: 'social recruitment',
job: 'Front end',
Expand Down Expand Up @@ -66,12 +69,6 @@ const useUserStore = defineStore('user', {
this.filterType = [];
},

// Get user's information
async info() {
const res = await getUserInfo();
this.setInfo(res.data);
},

async updateInfo(data: UserInfo) {
const res = await updateUserInfo(data);
this.setInfo(res.data);
Expand All @@ -81,8 +78,17 @@ const useUserStore = defineStore('user', {
async login(loginForm: LoginData) {
try {
const res = await userLogin(loginForm);
const { token, userInfo } = res.data;
const { token } = res.data;
setToken(token);
const userRes = await getUserInfo(loginForm.email)
const userInfo = {
id: userRes.data.id,
name:userRes.data.name,
role:userRes.data.role[0].name,
createTime:userRes.data.createTime,
updateTime:userRes.data.updateTime,
email:userRes.data.email,
}
this.setInfo(userInfo);
} catch (err) {
clearToken();
Expand All @@ -102,6 +108,10 @@ const useUserStore = defineStore('user', {

// Logout
async logout() {
const data = {
token:getToken()
}
await userLogout(data);
GaoNeng-wWw marked this conversation as resolved.
Show resolved Hide resolved
this.resetInfo();
clearToken();
removeRouteListener();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
export type RoleType = '' | '*' | 'admin' | 'user';
export interface UserInfo {
userId: string;
username: string;
id: string;
name: string;
email: string;
department?: string;
employeeType?: string;
job?: string;
Expand All @@ -13,6 +14,8 @@ export interface UserInfo {
address?: string;
status?: string;
role: RoleType;
updateTime?: any;
createTime?: any;
}
export interface UserFilterData {
sort?: number;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,6 @@

const userStore = useUserStore();

onMounted(() => {
userStore.info();
});
</script>

<style scoped lang="less">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@

try {
await userStore.login({
username: loginInfo.username,
email: loginInfo.username,
password: loginInfo.password,
});
Modal.message({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@
});

const loginMail = reactive({
mailname: 'admin@example.com',
mailname: 'admin@no-reply.com',
mailpassword: 'admin',
rememberPassword: true,
});
Expand All @@ -117,7 +117,7 @@

try {
await userStore.login({
username: loginMail.mailname,
email: loginMail.mailname,
password: loginMail.mailpassword,
});
Modal.message({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export default {
'login.banner.subSlogan3': '实现灵活的区块式开发',
'login.icon.language': '语言',
'login.tip.info': '用户名:admin,密码 admin',
'login.tip.mail': "用户名:admin{'@'}example.com,密码 admin",
'login.tip.mail': "用户名:admin{'@'}no-reply.com,密码 admin",
'login.tip.right': '请输入正确的用户名密码',
'login.main.text': 'TinyPro 中后台前端解决方案',
};