我有这个例子的nest.js +亚马逊网络服务认知登录https://medium.com/weekly-webtips/token-validation-with-aws-cognito-and-nestjs-6f9e4088393c,我想发送的代码,通过邮件来确认我的用户,我不知道我是否必须修改它的注册用户服务或创建其他方法的服务和控制器。
import { AuthConfig } from './auth.config';
import { Inject, Injectable } from '@nestjs/common';
import {
AuthenticationDetails,
CognitoUser,
CognitoUserPool,
CognitoUserAttribute,
} from 'amazon-cognito-identity-js';
@Injectable()
export class AuthService {
private userPool: CognitoUserPool;
private sessionUserAttributes: {};
constructor(
@Inject('AuthConfig')
private readonly authConfig: AuthConfig,
) {
this.userPool = new CognitoUserPool({
UserPoolId: this.authConfig.userPoolId,
ClientId: this.authConfig.clientId,
});
}
registerUser(registerRequest: {
name: string;
email: string;
password: string;
}) {
const { name, email, password } = registerRequest;
return new Promise((resolve, reject) => {
return this.userPool.signUp(
name,
password,
[new CognitoUserAttribute({ Name: 'email', Value: email })],
null,
(err, result) => {
if (!result) {
reject(err);
} else {
resolve(result.user);
}
},
);
});
}
authenticateUser(user: { name: string; password: string }) {
const { name, password } = user;
const authenticationDetails = new AuthenticationDetails({
Username: name,
Password: password,
});
const userData = {
Username: name,
Pool: this.userPool,
};
const newUser = new CognitoUser(userData);
return new Promise((resolve, reject) => {
return newUser.authenticateUser(authenticationDetails, {
onSuccess: result => {
resolve(result);
},
onFailure: err => {
reject(err);
},
});
});
}
}
import { BadRequestException, Body, Controller, Post } from '@nestjs/common';
import { AuthService } from './auth.service';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Post('register')
async register(
@Body() registerRequest: { name: string; password: string; email: string },
) {
return await this.authService.registerUser(registerRequest);
}
@Post('login')
async login(@Body() authenticateRequest: { name: string; password: string }) {
try {
return await this.authService.authenticateUser(authenticateRequest);
} catch (e) {
throw new BadRequestException(e.message);
}
}
}发布于 2021-08-03 20:45:39
我可以解决这个问题,我在服务中添加了一个新的方法,并在控制器中调用。
confirmUser(user: { username: string; confirmationCode: string }) {
const { username, confirmationCode } = user;
const userData = {
Username: username,
Pool: this.userPool,
};
const cognitoUser = new CognitoUser(userData);
return new Promise((resolve, reject) => {
cognitoUser.confirmRegistration(confirmationCode, true, function (err, result) {
if (err) {
console.log(err);
reject(err);
} else {
resolve(result);
}
});
});
}@Post('confirm')
async confirm(@Body() confirmUser: { username: string; confirmationCode: string }) {
try {
return await this.authService.confirmUser(confirmUser);
} catch (e) {
throw new BadRequestException(e.message);
}
}https://stackoverflow.com/questions/68628730
复制相似问题