Skip to content

Instantly share code, notes, and snippets.

@simply-alliv
Created July 25, 2020 14:04
Show Gist options
  • Save simply-alliv/6e75d75bb2da2b4661f13d0de4938d21 to your computer and use it in GitHub Desktop.
Save simply-alliv/6e75d75bb2da2b4661f13d0de4938d21 to your computer and use it in GitHub Desktop.
/**
* Code removed for brevity.
*/
import Paseto from 'paseto.js';
class AuthenticationService {
...
public async register(userData: CreateUserDto) {
if (await this.user.findOne({ email: userData.email })) {
throw new UserWithThatEmailAlreadyExistsException(userData.email);
}
const hashedPassword = await bcrypt.hash(userData.password, 10);
const user = await this.user.create({
...userData,
password: hashedPassword,
});
user.password = undefined;
const tokenData = await this.createToken(user);
const cookie = this.createCookie(tokenData);
return {
cookie,
user,
};
}
...
public async createToken(
user: User,
isSecondFactorAuthenticated = false,
): Promise<TokenData> {
const expiresIn = 60 * 60; // an hour
const dataStoredInToken: DataStoredInToken = {
isSecondFactorAuthenticated,
_id: user._id,
};
const encoder = new Paseto.V2();
const symmetricKey = await encoder.symmetric();
const token = await encoder.encrypt(dataStoredInToken, symmetricKey);
return {
expiresIn,
token,
};
}
}
export default AuthenticationService;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment