Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
extractCredentials(request: Request): BasicAuthenticationStrategyCredentials {
if (!request.headers.authorization) {
throw new HttpErrors.Unauthorized(`Authorization header not found.`);
}
// for example : Basic Z2l6bW9AZ21haWwuY29tOnBhc3N3b3Jk
const authHeaderValue = request.headers.authorization;
if (!authHeaderValue.startsWith('Basic')) {
throw new HttpErrors.Unauthorized(
`Authorization header is not of type 'Basic'.`,
);
}
//split the string into 2 parts. We are interested in the base64 portion
const parts = authHeaderValue.split(' ');
if (parts.length !== 2)
throw new HttpErrors.Unauthorized(
`Authorization header value has too many parts. It must follow the pattern: 'Basic xxyyzz' where xxyyzz is a base64 string.`,
);
const encryptedCredentails = parts[1];
// decrypt the credentials. Should look like : 'username:password'
const decryptedCredentails = Buffer.from(
encryptedCredentails,
'base64',
async generateToken(userProfile: UserProfile): Promise {
if (!userProfile) {
throw new HttpErrors.Unauthorized(
'Error generating token : userProfile is null',
);
}
const userInfoForToken = {
id: userProfile[securityId],
name: userProfile.name,
email: userProfile.email,
};
// Generate a JSON Web Token
let token: string;
try {
token = await signAsync(userInfoForToken, this.jwtSecret, {
expiresIn: Number(this.jwtExpiresIn),
});
} catch (error) {
throw new HttpErrors.Unauthorized(`Error encoding token : ${error}`);
} else if (payload.userId) {
user = await this.userRepo.findById(payload.userId);
}
if (!user) {
throw new HttpErrors.Unauthorized(
AuthenticateErrorKeys.UserDoesNotExist,
);
}
const userTenant = await this.userTenantRepo.findOne({
where: {
userId: user.getId(),
tenantId: user.defaultTenant,
},
});
if (!userTenant) {
throw new HttpErrors.Unauthorized(
AuthenticateErrorKeys.UserDoesNotExist,
);
} else if (userTenant.status !== 'active') {
throw new HttpErrors.Unauthorized(AuthenticateErrorKeys.UserInactive);
}
// Create user DTO for payload to JWT
const authUser: AuthUser = new AuthUser(user);
authUser.tenant = await this.userTenantRepo.tenant(userTenant.id);
const role = await this.userTenantRepo.role(userTenant.id);
const utPerms = await this.utPermsRepo.find({
where: {
userTenantId: userTenant.id,
},
fields: {
permission: true,
allowed: true,
it('user service verifyCredentials() fails with user not found', async () => {
const credentials = {email: 'idontexist@example.com', password: 'p4ssw0rd'};
const expectedError = new HttpErrors.Unauthorized(
'Invalid email or password.',
);
await expect(userService.verifyCredentials(credentials)).to.be.rejectedWith(
expectedError,
);
});
throw new HttpErrors.Unauthorized(`'credentials.username' is null`);
}
if (!credentials.password) {
throw new HttpErrors.Unauthorized(`'credentials.password' is null`);
}
const foundUser = this.userRepository.find(credentials.username);
if (!foundUser) {
throw new HttpErrors['Unauthorized'](
`User with username ${credentials.username} not found.`,
);
}
if (credentials.password !== foundUser.password) {
throw new HttpErrors.Unauthorized('The password is not correct.');
}
return foundUser;
}
convertToUserProfile(user: User): UserProfile {
if (!user) {
throw new HttpErrors.Unauthorized(`'user' is null`);
}
if (!user.id) {
throw new HttpErrors.Unauthorized(`'user id' is null`);
}
return this.userProfileFactory(user);
}
}
strategy.fail = function(challenge: string) {
reject(new HttpErrors.Unauthorized(challenge));
};
private async createJWT(
payload: ClientAuthCode,
authClient: AuthClient,
): Promise {
try {
let user: User | undefined;
if (payload.user) {
user = payload.user;
} else if (payload.userId) {
user = await this.userRepo.findById(payload.userId);
}
if (!user) {
throw new HttpErrors.Unauthorized(
AuthenticateErrorKeys.UserDoesNotExist,
);
}
const userTenant = await this.userTenantRepo.findOne({
where: {
userId: user.getId(),
tenantId: user.defaultTenant,
},
});
if (!userTenant) {
throw new HttpErrors.Unauthorized(
AuthenticateErrorKeys.UserDoesNotExist,
);
} else if (userTenant.status !== 'active') {
throw new HttpErrors.Unauthorized(AuthenticateErrorKeys.UserInactive);
}
if (count) return;
} else if (type === SecuredType.HAS_ROLES && roles.length) {
const userRoles = await this.userRoleRepository.find({where: {userId: username}});
const roleIds = userRoles.map(ur => ur.roleId);
let valid = true;
for (const role of roles)
if (!roleIds.includes(role)) {
valid = false;
break;
}
if (valid) return;
}
throw new HttpErrors.Unauthorized('Invalid authorization');
}
}
async verifyToken(token: string): Promise {
if (!token) {
throw new HttpErrors.Unauthorized(
`Error verifying token : 'token' is null`,
);
}
const decryptedToken = await verifyAsync(token, TokenServiceConstants.TOKEN_SECRET_VALUE);
let userProfile = _.pick(decryptedToken, ['id', 'email', 'name', `permissions`]);
return userProfile;
}