Skip to content

Instantly share code, notes, and snippets.

@jacobdo2
Last active June 17, 2020 12:27
Show Gist options
  • Save jacobdo2/5d688a9cd3d2df94dea1d8d0cfef99ed to your computer and use it in GitHub Desktop.
Save jacobdo2/5d688a9cd3d2df94dea1d8d0cfef99ed to your computer and use it in GitHub Desktop.
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,
(error, result) => {
if (!result) {
reject(error);
} 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);
},
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment