Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async validateToken(auth: string) {
if (auth.split(' ')[0] !== 'Bearer') {
throw new HttpException('Invalid token', HttpStatus.UNAUTHORIZED);
}
const token = auth.split(' ')[1];
try {
const decoded: any = await jwt.verify(token, environment.secret);
return decoded;
} catch (err) {
const message = 'Token error: ' + (err.message || err.name);
throw new HttpException(message, HttpStatus.UNAUTHORIZED);
}
}
}
async updateRole(id: string, role: RoleRepresentation, realm: string): Promise {
try {
const result = await (await this.getKeycloakClient()).roles.updateById({ id, realm }, role);
return result;
} catch (e) {
throw new HttpException(e, (e.response && e.response.status) || e.status || 500);
}
}
async register(registerVm: RegisterVm): Promise {
const { username, password, email } = registerVm;
try {
let exist = await this._userRepository.findOne({ username });
if (exist) {
throw new HttpException(
`${username} is already in use`,
HttpStatus.BAD_REQUEST,
);
}
exist = await this._userRepository.findOne({ email });
if (exist) {
throw new HttpException(
`This mail is already associated with an username`,
HttpStatus.BAD_REQUEST,
);
}
const newUser = this._userRepository.create(registerVm);
const salt = await genSalt();
newUser.password = await hash(password, salt);
const result = await this._userRepository.save(newUser);
return result;
} catch (e) {
throw e;
}
}
const qb = this.userRepo.createQueryBuilder('user')
.leftJoinAndSelect('user.roles', 'roles')
.where('roles.id = :roleId', { roleId })
.andWhere('user.recycle = false');
let users;
let count;
if (pageNumber && pageSize) {
const usersAndCount = await qb.skip((pageNumber - 1) * pageSize).take(pageSize).getManyAndCount();
users = usersAndCount[0];
count = usersAndCount[1];
}
else {
users = await qb.getMany();
}
if (!users.length) {
throw new common_1.HttpException(i18n_1.__('No users belong to this role'), 404);
}
const usersInfo = await this.findUserInfoById(users.map(user => user.id));
return { usersInfo, count };
}
async findByOrganizationId(organizationId, pageNumber, pageSize) {
async register(@Body() vm: RegisterVm): Promise {
const { username, password } = vm;
if (!username) {
throw new HttpException('Username is required', HttpStatus.BAD_REQUEST);
}
if (!password) {
throw new HttpException('Password is required', HttpStatus.BAD_REQUEST);
}
let exist;
try {
exist = await this._userService.findOne({ username });
} catch (e) {
throw new HttpException(e, HttpStatus.INTERNAL_SERVER_ERROR);
}
if (exist) {
throw new HttpException(`${username} exists`, HttpStatus.BAD_REQUEST);
}
async recycleArticleByIds(ids: number[]) {
const articles: number[] = [];
await this.artRepo.findByIds(ids).then(art => {
art.map((key, value) => {
articles.push(key.id);
});
});
const noExist = _.difference(ids, articles);
if (noExist.length > 0) {
throw new HttpException(`id为${noExist}的文章不存在`, 404);
}
await this.artRepo.update(ids, { recycling: true });
}
options?: FindOneOptions,
permissions?: (DefaultRoles.public | DefaultRoles.authenticated | DefaultRoles.admin | string)[],
): Promise {
options = options || {};
options.relations = options.relations || getRelationsName(this.repository.metadata.columns);
const result = await this.repository.findOne(id, options);
if (
permissions &&
permissions.indexOf(DefaultRoles.owner) >= 0 &&
SessionUtil.getUserRoles.indexOf(DefaultRoles.admin) < 0 &&
result.__meta.dataOwner !== SessionUtil.getAccountId
) {
throw new HttpException(`Only ${DefaultRoles.admin} or owner of this data can read`, 403);
}
if (!result) {
throw new HttpException(`${this.constructor.name} FindById with id: (${id}) Not Found`, 404);
}
if (result.isDeleted) {
throw new HttpException(`${this.constructor.name} record with id: "${id}" Has Been Deleted`, 404);
}
return this.mapper.entityToDto(result);
}
async getCurrentUser(@Req() req: Request) {
try {
req.res.send(
await this._authService.deSerializeToken(req.get('Authorization')),
);
} catch (error) {
throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
async create(userDTO: RegisterDTO) {
const { username } = userDTO;
const user = await this.userModel.findOne({ username });
if (user) {
throw new HttpException('User already exists', HttpStatus.BAD_REQUEST);
}
const createdUser = new this.userModel(userDTO);
await createdUser.save();
return this.sanitizeUser(createdUser);
}
validateRegister(register: RegisterVm): RegisterVm {
try {
const { username, password, email, role } = register;
if (!username) {
throw new HttpException('name is required', HttpStatus.BAD_REQUEST);
}
if (!password) {
throw new HttpException('password is required', HttpStatus.BAD_REQUEST);
}
if (!email) {
throw new HttpException('mail is required', HttpStatus.BAD_REQUEST);
}
if (!role) register.role = 'Customer';
register.role = role.toUpperCase();
register.username = username.toLowerCase();
register.email = email.toLowerCase();
return register;
} catch (e) {
throw e;
}
}
}