Skip to content

Commit a879fc7

Browse files
committed
feat: 守卫中修改为单点登录
1 parent c2e428f commit a879fc7

File tree

4 files changed

+52
-69
lines changed

4 files changed

+52
-69
lines changed

src/decorators/current.user.ts

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,9 @@ export const CurrentUser = createParamDecorator((data: string, ctx: ExecutionCon
1414
*/
1515
export interface ICurrentUserType {
1616
id: number;
17-
username?: string;
18-
mobile?: string;
19-
email?: string;
20-
isSuper?: number;
21-
platform?: number;
22-
iat: number;
23-
exp: number;
17+
username: string;
18+
email: string;
19+
mobile: string;
20+
isSuper: number;
21+
platform: number;
2422
}

src/guard/auth/auth.guard.ts

Lines changed: 14 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,13 @@ import {
66
HttpStatus,
77
Logger,
88
} from '@nestjs/common';
9-
import * as jwt from 'jsonwebtoken';
109
import { getUrlQuery } from '@src/utils';
1110
import { CodeEnum, CodeMessage } from '@src/enums/code.enum';
1211
import { API_AUTH_KEY } from '@src/constants';
1312
import { ApiAuthService } from '@src/modules/shared/services/api-auth/api-auth.service';
14-
15-
const SECRET = process.env.SECRET as string;
13+
import { AccountTokenEntity } from '@src/modules/admin/system/account/entities/account.token.entity';
14+
import moment from 'moment';
15+
import { ICurrentUserType } from '@src/decorators/current.user';
1616

1717
@Injectable()
1818
export class AuthGuard implements CanActivate {
@@ -30,17 +30,22 @@ export class AuthGuard implements CanActivate {
3030
console.log(methodAuth, classAuth, '守卫中', request.method, request.url);
3131
if (token) {
3232
try {
33-
const user = await this.verifyToken(token, SECRET);
34-
console.log(user, '当前用户');
35-
if (user) {
36-
request.user = user;
33+
// 1.从数据库查询是否存在记录
34+
const accountInfo: Extract<AccountTokenEntity, ICurrentUserType> | undefined =
35+
await AccountTokenEntity.findOne({
36+
where: { token },
37+
select: ['userId', 'username', 'mobile', 'expireTime', 'platform', 'email', 'isSuper'],
38+
});
39+
const isExpire: boolean = moment(accountInfo?.expireTime).isAfter(new Date());
40+
console.log(isExpire, '是否过期');
41+
if (accountInfo && isExpire) {
42+
const user: ICurrentUserType = { ...accountInfo, id: accountInfo.userId };
43+
request.user = accountInfo;
3744
if (methodAuth || classAuth) {
38-
console.log('11走资源守卫');
3945
const method = request.method;
4046
const url = request.url;
4147
return this.apiAuthService.apiAuth(user, method, url);
4248
} else {
43-
console.log('11不走资源守卫');
4449
return true;
4550
}
4651
} else {
@@ -63,28 +68,4 @@ export class AuthGuard implements CanActivate {
6368
);
6469
}
6570
}
66-
67-
/**
68-
* @Author: 水痕
69-
* @Date: 2021-03-22 11:13:07
70-
* @LastEditors: 水痕
71-
* @Description: 校验用户传递过来的token
72-
* @param {string} token
73-
* @param {string} secret
74-
* @return {*}
75-
*/
76-
private verifyToken(token: string, secret: string): Promise<any> {
77-
return new Promise((resolve) => {
78-
jwt.verify(token, secret, (error, payload) => {
79-
if (error) {
80-
console.log('-----------error start--------------');
81-
console.log(error);
82-
console.log('-----------error end--------------');
83-
throw new HttpException('token不合法', HttpStatus.OK);
84-
} else {
85-
resolve(payload);
86-
}
87-
});
88-
});
89-
}
9071
}

src/modules/admin/system/account/services/login/login.service.ts

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,8 @@ import { AccountTokenEntity } from '../../entities/account.token.entity';
1111
import { ConfigService, InjectConfig } from 'nestjs-config';
1212
import moment from 'moment';
1313
import { usernameReg } from '@src/constants';
14+
import { ICurrentUserType } from '@src/decorators/current.user';
1415

15-
interface IAccount {
16-
id: number;
17-
username: string;
18-
email: string;
19-
mobile: string;
20-
isSuper: number;
21-
platform: number;
22-
}
2316
@Injectable()
2417
export class LoginService {
2518
private logger: Logger = new Logger(LoginService.name);
@@ -45,7 +38,7 @@ export class LoginService {
4538
async adminLogin(loginDto: LoginDto, ipAddress: string): Promise<LoginVo> {
4639
try {
4740
const { username, password } = loginDto;
48-
type TypeAccountFindResult = Extract<AccountEntity, IAccount> | undefined;
41+
type TypeAccountFindResult = Extract<AccountEntity, ICurrentUserType> | undefined;
4942
let findAccount: TypeAccountFindResult;
5043
const queryBuilder = this.queryLoginBuilder;
5144
// 根据手机号码查询
@@ -148,10 +141,10 @@ export class LoginService {
148141
* @Date: 2021-07-26 10:15:17
149142
* @LastEditors: 水痕
150143
* @Description: 过来字段
151-
* @param {IAccount} accountInfo
144+
* @param {ICurrentUserType} accountInfo
152145
* @return {*}
153146
*/
154-
private filterAccountField(accountInfo: IAccount): IAccount {
147+
private filterAccountField(accountInfo: ICurrentUserType): ICurrentUserType {
155148
const { username, mobile, email } = accountInfo;
156149
const _mobile = isMobilePhone(mobile, 'zh-CN') ? mobile : '';
157150
const _email = isEmail(email) ? email : '';

src/modules/shared/services/api-auth/api-auth.service.ts

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -26,33 +26,44 @@ export class ApiAuthService {
2626
*/
2727
public async apiAuth(user: ICurrentUserType, method: string, url: string): Promise<boolean> {
2828
const { isSuper, id } = user;
29+
console.log(user, '11');
2930
// 1.如果是超级管理员就直接返回true
3031
if (isSuper) {
3132
return true;
3233
} else {
34+
console.log(user, '222');
3335
// 2.根据当前账号id获取当前账号拥有的角色id
34-
const authRoleList: AccountRoleEntity[] = await this.accountRoleRepository.find({
35-
where: { accountId: id },
36-
select: ['roleId'],
37-
});
38-
const authRoleIdList: number[] = authRoleList.map((item: AccountRoleEntity) => item.roleId);
39-
console.log(authRoleList, '授权的角色列表');
36+
const authRoleList: Pick<AccountRoleEntity, 'roleId'>[] =
37+
await this.accountRoleRepository.find({
38+
where: { accountId: id },
39+
select: ['roleId'],
40+
});
41+
console.log(authRoleList, '333');
42+
const authRoleIdList: number[] = authRoleList.map(
43+
(item: Pick<AccountRoleEntity, 'roleId'>) => item.roleId,
44+
);
45+
console.log(authRoleIdList, '授权的角色列表44');
46+
if (!authRoleIdList.length) {
47+
throw new HttpException(`当前账号没操作:${method}-${url}的权限`, HttpStatus.OK);
48+
}
4049
// 3.根据角色ID列表获取当前账号拥有的资源id
41-
const authAccessList = await getConnection()
42-
.createQueryBuilder(RoleAccessEntity, 'role_access')
43-
.select(['role_access.accessId', 'role_access.type'])
44-
.where('role_access.roleId in (:...roleId)', { roleId: authRoleIdList })
45-
.getMany();
46-
console.log(authAccessList, '授权的资源列表'); // [ RoleAccessEntity { accessId: 5, type: 3 } ]
50+
const authAccessList: Pick<RoleAccessEntity, 'accessId' | 'type'>[] | undefined =
51+
await getConnection()
52+
.createQueryBuilder(RoleAccessEntity, 'role_access')
53+
.select(['role_access.accessId', 'role_access.type'])
54+
.where('role_access.roleId in (:...roleId)', { roleId: authRoleIdList })
55+
.getMany();
56+
console.log(authAccessList, '授权的资源列表55'); // [ RoleAccessEntity { accessId: 5, type: 3 } ]
4757
const formatUrl = this.formatUrl(method, url);
4858
// 4.根据请求方式和路径去查询数据
49-
const accessResult: AccessEntity | undefined = await this.accessRepository.findOne({
50-
where: { method, url: formatUrl },
51-
select: ['id', 'type'],
52-
});
53-
console.log(accessResult, '当前请求的资源');
59+
const accessResult: Pick<AccessEntity, 'id' | 'type'> | undefined =
60+
await this.accessRepository.findOne({
61+
where: { method, url: formatUrl },
62+
select: ['id', 'type'],
63+
});
64+
console.log(accessResult, '当前请求的资源66');
5465
const isExist = authAccessList.find(
55-
(item: RoleAccessEntity) =>
66+
(item: Pick<RoleAccessEntity, 'accessId' | 'type'>) =>
5667
item.accessId === accessResult?.id && Number(item.type) === Number(accessResult?.type),
5768
);
5869
if (isExist) {

0 commit comments

Comments
 (0)