用Nest.js搭建用户管理系统-简单好用的实战技巧
2023-12-14 07:07:51
如何使用 Nest.js 实现用户管理:注册、登录和 JWT 认证
一、用户注册
用户注册是用户管理系统中一项基本的功能。在 Nest.js 中,我们可以利用 @nestjs/typeorm
模块轻松实现用户注册功能。首先,我们在 src/user/user.entity.ts
文件中定义用户实体:
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@Column()
password: string;
}
接下来,我们在 src/user/user.service.ts
文件中定义用户服务:
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
) {}
async register(username: string, password: string) {
const user = new User();
user.username = username;
user.password = password;
return await this.userRepository.save(user);
}
}
最后,我们在 src/user/user.controller.ts
文件中定义用户控制器:
import { Controller, Post, Body } from '@nestjs/common';
import { UserService } from './user.service';
@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) {}
@Post('register')
async register(@Body() body: any) {
return await this.userService.register(body.username, body.password);
}
}
这样,我们就完成了用户注册功能的实现。
二、微信扫码登录
微信扫码登录是一种流行的登录方式,它可以方便用户快速登录系统。在 Nest.js 中,我们可以使用 @nestjs/passport
模块实现微信扫码登录功能。首先,我们在 src/main.ts
文件中配置 @nestjs/passport
模块:
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
@Module({
imports: [PassportModule.register({ defaultStrategy: 'wechat' })],
})
export class AppModule {}
接下来,我们在 src/auth/wechat.strategy.ts
文件中定义微信扫码登录策略:
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-wechat-oauth2';
@Injectable()
export class WechatStrategy extends PassportStrategy(Strategy, 'wechat') {
constructor() {
super({
clientID: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
callbackURL: 'http://localhost:3000/auth/wechat/callback',
scope: ['snsapi_userinfo'],
});
}
async validate(
accessToken: string,
refreshToken: string,
profile: any,
done: (err: Error | null, user: any, info?: any) => void,
) {
if (!profile.openid) {
return done(new UnauthorizedException(), false);
}
const user = {
openid: profile.openid,
nickname: profile.nickname,
headimgurl: profile.headimgurl,
};
done(null, user);
}
}
最后,我们在 src/auth/auth.controller.ts
文件中定义微信扫码登录控制器:
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Get('wechat')
@UseGuards(AuthGuard('wechat'))
async wechat() {
return this.authService.wechatLogin();
}
@Get('wechat/callback')
@UseGuards(AuthGuard('wechat'))
async wechatCallback(@Request() req) {
return this.authService.wechatLoginCallback(req.user);
}
}
这样,我们就实现了微信扫码登录功能。
三、JWT 认证
JWT(JSON Web Token)是一种流行的认证方式,它可以方便用户在不同的系统之间进行登录。在 Nest.js 中,我们可以使用 @nestjs/jwt
模块实现 JWT 认证功能。首先,我们在 src/auth/jwt.strategy.ts
文件中定义 JWT 策略:
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { AuthService } from './auth.service';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'YOUR_SECRET_KEY',
});
}
async validate(payload: any) {
return this.authService.validateUser(payload.sub);
}
}
接下来,我们在 src/auth/auth.module.ts
文件中配置 JWT 模块:
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
import { WechatStrategy } from './wechat.strategy';
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: 'YOUR_SECRET_KEY',
signOptions: { expiresIn: '1h' },
}),
],
providers: [AuthService, JwtStrategy, WechatStrategy],
})
export class AuthModule {}
最后,我们在 src/auth/auth.service.ts
文件中定义 JWT 服务:
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from '../user/user.service';
@Injectable()
export class AuthService {
constructor(
private readonly userService: UserService,
private readonly jwtService: JwtService,
) {}
async validateUser(username: string) {
return this.userService.findOne(username);
}
async login(user: any) {
const payload = { sub: user.id, username: user.username };
return {
access_token: this.jwtService.sign(payload),
};
}
async wechatLogin() {
return 'YOUR_WECHAT_LOGIN_URL';
}
async wechatLoginCallback(user: any) {
return this.login(user);
}
}
这样,我们就实现了 JWT 认证功能。
四、总结
在本文中,我们使用 Nest.js 实现了用户管理系统中常用的用户注册、微信扫码登录和 JWT 认证功能。希望本文能对您有所帮助。如果您有任何问题,欢迎在评论区留言。
常见问题解答
- 什么是 Nest.js?
Nest.js 是一个流行的 Node.js 框架,用于构建高效、可扩展和可测试的服务器端应用程序。
- 如何配置
@nestjs/passport
模块?
在 src/main.ts
文件中导入 PassportModule
并调用 PassportModule.register()
方法。
- 如何实现微信扫码登录回调?
在 src/auth/auth.controller.ts
文件中定义 wechatCallback
方法,使用 @UseGuards(AuthGuard('wechat'))
保护该路由,并在方法中调用 authService.wechatLoginCallback(req.user)
。
- 如何配置
@nestjs/jwt
模块?
在 src/auth/auth.module.ts
文件中导入 JwtModule
并调用 JwtModule.register()
方法。
- 如何在 Nest.js 中使用 JWT?
在 src/auth/auth.service.ts
文件中定义 AuthService
,并使用 JwtService
签发和验证 JWT 令牌。