Skip to content

Commit

Permalink
✨ finish sms module
Browse files Browse the repository at this point in the history
  • Loading branch information
ileostar committed Jul 14, 2024
1 parent 578d218 commit eebe3c5
Show file tree
Hide file tree
Showing 9 changed files with 245 additions and 49 deletions.
2 changes: 2 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
{
"cSpell.words": [
"aliyuncs",
"autoincrement",
"autorestart",
"ctsx",
"Dysmsapi",
"EDITMSG",
"gitmoji",
"ianvs",
Expand Down
5 changes: 5 additions & 0 deletions apps/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@
},
"devDependencies": {
"@alicloud/sms-sdk": "^1.1.6",
"@alicloud/tea-typescript": "^1.7.1",
"@alicloud/dysmsapi20170525": "3.0.0",
"@alicloud/openapi-client": "^0.4.8",
"@alicloud/tea-console": "^1.0.0",
"@alicloud/tea-util": "^1.4.7",
"@nestjs/cli": "^10.0.0",
"@nestjs/schematics": "^10.0.0",
"@nestjs/testing": "^10.0.0",
Expand Down
37 changes: 37 additions & 0 deletions apps/server/src/common/sms.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// This file is auto-generated, don't edit it
// 依赖的模块可通过下载工程中的模块依赖文件或右上角的获取 SDK 依赖信息查看
import Dysmsapi20170525, * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525';
import * as $OpenApi from '@alicloud/openapi-client';
import * as $Util from '@alicloud/tea-util';

export default class Client {
/**
* 使用AK&SK初始化账号Client
* @return Client
* @throws Exception
*/
static createClient(): Dysmsapi20170525 {
// 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
// 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378664.html。
let config = new $OpenApi.Config({
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
});
// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
config.endpoint = `dysmsapi.aliyuncs.com`;
return new Dysmsapi20170525(config);
}

static async main(SMSSendConfig): Promise<void> {
try {
} catch (error) {
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
console.log();
// 诊断地址
console.log(error.data['Recommend']);
}
}
}
25 changes: 0 additions & 25 deletions apps/server/src/config/sms.ts

This file was deleted.

2 changes: 1 addition & 1 deletion apps/server/src/sms/dto/sms.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export class SendCodeBySMSDto {
@ApiProperty({
description: '电话号码列表,这里仅为示例,实际可能支持多个号码',
type: String,
example: '1500000000',
example: '14709723891',
})
readonly phone: string;
}
31 changes: 16 additions & 15 deletions apps/server/src/sms/sms.service.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,31 @@
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import SMSClient from '@alicloud/sms-sdk';
import { SMSClientConfig, SMSSendConfig } from '../config/sms';
import { Injectable } from '@nestjs/common';
import { SendCodeBySMSDto } from './dto/sms.dto';
import { generateVerificationCode } from 'src/utils';
import { CacheService } from 'src/cache/cache.service';
import { ResponseData } from 'src/response/ResponseFormat';
import Client from 'src/common/sms';
import * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525';
import * as $Util from '@alicloud/tea-util';

@Injectable()
export class SmsService {
constructor(private cacheService: CacheService) {}
async sendCodeBySMS(dto: SendCodeBySMSDto) {
try {
const code = generateVerificationCode();
const smsClient = new SMSClient(SMSClientConfig);
this.cacheService.setCache(dto.phone, code);
const res = smsClient.sendSMS(
{
PhoneNumbers: dto.phone,
SignName: SMSSendConfig.SignName,
TemplateCode: SMSSendConfig.TemplateCode,
TemplateParam: JSON.stringify({ code }),
},
{ method: 'POST' },
);
return res.Code === 'OK' ? res : false;
let client = Client.createClient();
let sendSmsRequest = new $Dysmsapi20170525.SendSmsRequest({
signName: process.env.SignName,
templateCode: process.env.TemplateCode,
phoneNumbers: dto.phone,
templateParam: JSON.stringify({ code }),
});
let runtime = new $Util.RuntimeOptions({});
await client.sendSmsWithOptions(sendSmsRequest, runtime);
return ResponseData.ok(null, '短信发送成功');
} catch (error) {
new HttpException('sendCodeBySMS error', HttpStatus.BAD_REQUEST);
return ResponseData.fail(error.message);
}
}
}
31 changes: 29 additions & 2 deletions apps/server/src/user/user.controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,34 @@
import { Body, Controller, Get, Patch, Post, UseGuards } from '@nestjs/common';
import {
Body,
Controller,
Get,
Inject,
Patch,
Post,
UseGuards,
} from '@nestjs/common';
import { UserService } from './user.service';
import { ApiBody, ApiOperation } from '@nestjs/swagger';
import { DefaultLoginDto } from 'src/auth/dto/auth.dto';
import { CreateUserDto } from './dto/user.dto';
import { DB, DbType } from 'src/global/providers/db.provider';
import { user } from '@poster-craft/schema';
import { ResponseData } from 'src/response/ResponseFormat';

@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) {}
constructor(
private readonly userService: UserService,
@Inject(DB) private db: DbType,
) {}

@Post('test')
@ApiOperation({ summary: '测试', description: '测试' })
async testAdd() {
const [res] = await this.db.insert(user).values({
phone: '14709723891',
username: 'demo',
});
return ResponseData.ok(res);
}
}
9 changes: 7 additions & 2 deletions apps/server/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import crypto from 'crypto';

/** 生成随机验证码 */
export function generateVerificationCode(): string {
return crypto.randomInt(100000, 1000000).toString().slice(0, 6);
export function generateVerificationCode() {
let code = '';
for (let i = 0; i < 6; i++) {
// 生成 0-9 之间的数字,并将其转换为字符串后追加到 code
code += Math.floor(Math.random() * 10);
}
return code;
}

/** 生成随机用户名 */
Expand Down
Loading

0 comments on commit eebe3c5

Please sign in to comment.