Keycloak connection error using kcAdminClient and NestJS - nestjs

I am working with keycloak and using this package https://www.npmjs.com/package/#keycloak/keycloak-admin-client to implement user edit functionality for every user. Backend is written on Nest.JS. This is app.service.ts code
import { Injectable } from '#nestjs/common';
import KcAdminClient from '#keycloak/keycloak-admin-client';
#Injectable()
export class AppService {
private adminClient: KcAdminClient;
constructor() {
this.getAdminProperties().then(admin => {
this.adminClient = admin;
})
}
async getAdminProperties() {
const kcAdminClient = new KcAdminClient();
await kcAdminClient.auth({
username: 'user',
password: 'user',
grantType: 'password',
clientId: 'admin-cli',
});
kcAdminClient.setConfig({
realmName: 'space-realm',
});
return kcAdminClient;
}
updateUser(body: any, id: number): any {
this.adminClient.users.update({ id: id.toString() }, body)
}
}
And after this all code I am getting this annoying error:
(node:732) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:8080
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16)
(node:732) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
Maybe I am doing something wrong?

The problem was inside KcAdminClient() constructor, so for dev version I just added baseUrl with static IP of my Docker container of keycloak. For dev version this approach is fine, for public also, because you will use url of you web application. Good luck!

Related

What am I doing wrong with Sequelize?

I'm trying to use Sequelize for my simple Typescript application. I simply want to connect to Postgres db via Sequelize (I can) and create a simple table Book (I can't)
I've the file interface.ts within which I've the interface book:
export interface book{
title: string;
author: string;
price: number;
id: number;
}
Then I've the database.ts file:
import { Dialect, Sequelize } from 'sequelize'
import {book, purchases, user} from "../interface"
import { DataTypes, Model, Optional } from 'sequelize'
const dbName = process.env.DB_NAME as string
const dbUser = process.env.DB_USER as string
const dbHost = process.env.DB_HOST
const dbDriver = process.env.DB_DRIVER as Dialect
const dbPassword = process.env.DB_PASSWORD
export const sequelizeConnection = new Sequelize(dbName, dbUser, dbPassword, {
host: dbHost,
dialect: "postgres"
});
class Book extends Model<book> {
id!: number;
author!: string;
price!: number;
title!: string;
}
export function dbInit (){
Book.sync({force: true});
}
In the main file, index.ts:
async function Start() {
try {
await sequelizeConnection.sync();
dbInit();
app.listen(configuration.server_port, (): void => {
console.log("Server listening on port " + configuration.server_port);
});
} catch (error) {
console.log("Error occured: " + error);
}
}
Start();
The error I obtain is:
Executing (default): SELECT 1+1 AS result
Server listening on port 3000
(node:577) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'hooks' of undefined
at getHooks (/mnt/c/Users/raffa/Desktop/esercitazione_ts/node_modules/sequelize/src/hooks.js:70:26)
at Function.runHooks (/mnt/c/Users/raffa/Desktop/esercitazione_ts/node_modules/sequelize/src/hooks.js:98:15)
at Function.sync (/mnt/c/Users/raffa/Desktop/esercitazione_ts/node_modules/sequelize/src/model.js:1339:18)
at dbInit (/mnt/c/Users/raffa/Desktop/esercitazione_ts/src/config/dabatase.ts:25:8)
at /mnt/c/Users/raffa/Desktop/esercitazione_ts/src/index.ts:18:11
at step (/mnt/c/Users/raffa/Desktop/esercitazione_ts/src/index.ts:56:23)
at Object.next (/mnt/c/Users/raffa/Desktop/esercitazione_ts/src/index.ts:37:53) at fulfilled (/mnt/c/Users/raffa/Desktop/esercitazione_ts/src/index.ts:28:58)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:577) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block,
or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:577) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
What am I doing wrong?

NestJS - Microservices - Kafka Exception Handling

I'm using NestJS to implement a microservice architecture, I'm using CLIENT app using NestJS,
The client app receives a rest request and sends to Kafka to get the result
try {
const pattern = 'findDoctors';
const payload = body;
const doctors = await lastValueFrom(
this.client.send(pattern, payload).pipe(timeout(50000)),
);
return doctors;
} catch (e) {
console.log(e);
throw new Error(e);
}
And in the microservice side (Hybrid Application for now, will remove the rest apis later)
#MessagePattern('findDoctors')
findDoctors(#Payload() message): any {
return this.doctorService.searchForDoctors(message.value);
}
async searchForDoctors(data): Promise<any[]> {
this.logger.info('Started search for doctors job');
throw 'Not Found';
}
After i throw the exception i get in the logs
node:17720) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received an instance of Object
at Function.from (buffer.js:330:9)
at ServerKafka.assignErrorHeader (C:\Users\Desktop\Projects\node_modules\#nestjs\microservices\server\server-kafka.js:137:73)
at ServerKafka.sendMessage (C:\Users\Desktop\Projects\node_modules\#nestjs\microservices\server\server-kafka.js:119:14)
at C:\Users\Desktop\Projects\node_modules\#nestjs\microservices\server\server-kafka.js:81:31
at C:\Users\Desktop\node_modules\#nestjs\microservices\server\server.js:46:31
at processTicksAndRejections (internal/process/task_queues.js:79:11)
(node:17720) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:17720) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
and the client side just waits to timeout and never receive an exception response from the micro service
Tried using RpcException but it's the same
Found the answer
used
return new RpcException('not found');
instead of
throw new RpcException('not found')
throwing the exception needs an exception filter to catch it
#Catch(RpcException)
export class ExceptionFilter implements RpcExceptionFilter<RpcException> {
catch(exception: RpcException, host: ArgumentsHost): Observable<any> {
return throwError(exception.getError());
}
}
and in the client side you can catch the error when using filters and return a normal http exception, or use filters on that too
#Post('/search')
async findAll(#Body() body) {
console.log('Sending kafka msg');
try {
const doctors = await this.doctorService.findDoctors(body);
return doctors;
} catch (e) {
console.log(e)
throw new HttpException({
status: '500',
error: e.message,
}, 500)
}
}

I am getting always TypeError: Cannot read property 'userService' of undefined

How can i fix this error ? In below my codes
IUserRepository and UserRepository:
import User from "./entity/User";
export default interface IUserRepository{
findAll():Promise<User[]>
}
import User from "./entity/User";
import IUserRepository from './IUserRepo';
export default class UserRepository implements IUserRepository{
public async findAll(): Promise<User[]>{
return await User.findAll()
}
}
IUserService and UserService:
import User from "./entity/User";
export default interface IUserRepository{
findAll():Promise<User[]>
}
import User from './entity/User';
import IUserService from './IUserService';
import IUserRepository from './IUserRepo';
export default class UserService implements IUserService{
public userRepo: IUserRepository
public constructor(userRepo:IUserRepository){
this.userRepo = userRepo
}
public async findAll(): Promise<User[]> {
return await this.userRepo.findAll()
}
}
UserController:
import { Request, Response } from 'express';
import IUserService from './IUserService';
export default class UserController{
public userService:IUserService
public constructor(UserService:IUserService){
this.userService = UserService
}
public async findAll(req:Request, res:Response){
const allUser = await this.userService.findAll()
res.send(allUser)
}
}
server:
import express, { Application, Request, Response } from 'express'
import UserController from './UserController';
import UserService from './UserService';
import UserRepository from './UserRepository';
const app: Application = express()
const port = 3000
const userCont = new UserController(new UserService(new UserRepository()))
app.use(express.json());
app.get('/', userCont.findAll)
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`)
})
error:
(node:21576) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'userService' of undefined
at C:\Users\hasan\OneDrive\Masaüstü\type-orm\src\UserController.ts:11:36
at step (C:\Users\hasan\OneDrive\Masaüstü\type-orm\src\UserController.ts:33:23)
at Object.next (C:\Users\hasan\OneDrive\Masaüstü\type-orm\src\UserController.ts:14:53)
at C:\Users\hasan\OneDrive\Masaüstü\type-orm\src\UserController.ts:8:71
at new Promise (<anonymous>)
at __awaiter (C:\Users\hasan\OneDrive\Masaüstü\type-orm\src\UserController.ts:4:12)
at UserController.findAll (C:\Users\hasan\OneDrive\Masaüstü\type-orm\src\UserController.ts:44:16)
at Layer.handle [as handle_request] (C:\Users\hasan\OneDrive\Masaüstü\type-orm\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\hasan\OneDrive\Masaüstü\type-orm\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\hasan\OneDrive\Masaüstü\type-orm\node_modules\express\lib\router\route.js:112:3)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:21576) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:21576) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process
with a non-zero exit code.
(node:21576) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'userService' of undefined
at C:\Users\hasan\OneDrive\Masaüstü\type-orm\src\UserController.ts:11:36
at step (C:\Users\hasan\OneDrive\Masaüstü\type-orm\src\UserController.ts:33:23)
at Object.next (C:\Users\hasan\OneDrive\Masaüstü\type-orm\src\UserController.ts:14:53)
at C:\Users\hasan\OneDrive\Masaüstü\type-orm\src\UserController.ts:8:71
at new Promise (<anonymous>)
at __awaiter (C:\Users\hasan\OneDrive\Masaüstü\type-orm\src\UserController.ts:4:12)
at UserController.findAll (C:\Users\hasan\OneDrive\Masaüstü\type-orm\src\UserController.ts:44:16)
at Layer.handle [as handle_request] (C:\Users\hasan\OneDrive\Masaüstü\type-orm\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\hasan\OneDrive\Masaüstü\type-orm\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\hasan\OneDrive\Masaüstü\type-orm\node_modules\express\lib\router\route.js:112:3)
(node:21576) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
I have got this error for 4 day, i will become mad becouse of this error. Please help meeee.
btw sorry for my bad english. if i write less i cant share this post becouse of sory for this xxx spam
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
You should not pass a function of object, because you loose context
Use arrow function instead:
app.get('/', (req, res) => userCont.findAll(req,res))
Could you post the stack trace or error? I think you forgot to put that.

Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead

I am learning typeorm with expressjs. Here I am trying to implement login user function where if user exist it will send an access token. I have already implemented Register function but while adding login I get error in console saying this. I have no idea what this means.
(node:8536) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(node:8536) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'isValidPassword' of undefined
at Object.<anonymous> (C:\Users\adity\Desktop\dev\restapi\src\controllers\AuthController.ts:43:15)
at step (C:\Users\adity\Desktop\dev\restapi\src\controllers\AuthController.ts:32:23)
at Object.throw (C:\Users\adity\Desktop\dev\restapi\src\controllers\AuthController.ts:13:53)
at rejected (C:\Users\adity\Desktop\dev\restapi\src\controllers\AuthController.ts:5:65)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:8536) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:8536) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Here is my code.
AuthController.ts
static login = async (req: Request, res: Response) => {
const { email, password } = req.body;
if (!(email && password)) {
res.status(400).send();
}
const userRepository = getRepository(User);
let user: User;
try {
user = await userRepository.findOneOrFail({ where: email });
} catch (error) {
res.status(401).send(error);
}
if (!user.isValidPassword(password)) {
res.status(401).send("Incorrect Password");
return;
}
const token = jwt.sign({ id: user.id, email: user.email }, "secret", {
expiresIn: "1h",
});
res.send(token);
};
Entity/User.ts
import * as bcrypt from "bcryptjs";
#Entity()
export class User extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#Column()
email: string;
#Column()
#Length(4, 100)
password: string;
#Column()
#CreateDateColumn()
createdAt: Date;
#Column()
#UpdateDateColumn()
updatedAt: Date;
isValidPassword = (password: string) => {
return bcrypt.compareSync(password, this.password);
};
setPassword = (password: string) => {
return (this.password = bcrypt.hashSync(password, 8));
};
}
This NodeJS error usually happens when its detecting an asynchronous function somewhere in your code whose error is not being handled.
If getRepositry(user) is an async function, you could try attaching a catch block it like so:
const userRepository = await getRepository(User).catch(err=>console.log(err));
This should take care of unhandled promise rejection error.
This is happening because in case findOneOrFail could not find any user it will through error that you are catching but it will result in user value equal to undefined.
Then the method isValidPassword will not work as it is not defined on the undefined but on the user model
if (!user.isValidPassword(password)) {
res.status(401).send("Incorrect Password");
return;
}
you should move above code in the try block or you can place a type guard in front like this
if (user && !user.isValidPassword(password)) {
res.status(401).send("Incorrect Password");
return;
}

`newSession` not found when using local capabilities

I'm facing this error when trying to use BrowserStack local capability:
(node:67602) UnhandledPromiseRejectionWarning: UnsupportedOperationError: newSession: Not Found
at parseHttpResponse (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:578:11)
at Executor.execute (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:489:26)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:67602) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:67602) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:67602) UnhandledPromiseRejectionWarning: UnsupportedOperationError: newSession: Not Found
at parseHttpResponse (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:578:11)
at Executor.execute (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:489:26)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:67602) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)
My code is pretty simple:
const webdriver = require('selenium-webdriver');
const browserstack = require('browserstack-local');
const runTestSuite = () => {
const capabilities = {
browserName: 'Chrome',
browser_version: '80.0 beta',
os: 'OS X',
os_version: 'Catalina',
resolution: '1024x768',
'browserstack.user': '<user>',
'browserstack.key': '<key>',
'browserstack.local': true,
'browserstack.localIdentifier': 'ardotest',
// 'browserstack.use_w3c': true,
acceptSslCerts: true,
name: 'Bstack-[Node] Sample Test-OS X Catalina-Chrome 80',
};
// https://www.browserstack.com/question/663
const driver = new webdriver.Builder()
.usingServer('http://localhost:3000') // tried using the IP that I got from Network settings on my machine, it spat out the same error
.withCapabilities(capabilities)
.build();
console.log('quit');
driver.quit();
};
// creates an instance of Local
const bsLocal = new browserstack.Local();
// replace <browserstack-accesskey> with your key. You can also set an environment variable - "BROWSERSTACK_ACCESS_KEY".
const bsLocalArgs = { key: '<browserstack-accesskey>' };
// https://github.com/browserstack/browserstack-local-nodejs/blob/master/lib/Local.js
// starts the Local instance with the required arguments
bsLocal.start(bsLocalArgs, function(err) {
if (err) {
console.error(err);
return;
}
if (!bsLocal.isRunning()) {
return;
}
try {
runTestSuite();
} catch (e) {
console.error(e);
} finally {
// stop the Local instance
bsLocal.stop(function(err) {
if (err) {
console.error(err);
}
console.log('===== BrowserStack tunnel stopped =====');
});
}
});
Versions:
"selenium-webdriver": "^4.0.0-alpha.5",
"browserstack-local": "^1.4.5",
My local environment:
"node": "10.16.3",
"npm": "6.8.0",
macOS 10.14.6
Looking through the code, it's clear that it's trying to hit /session url to create a new session or something. I'm not sure whether I should support /session manually, or I'm just missing something that's really stupid here?
It seems that BrowserStack provides it's own Hub URL for the test executions. You may try changing the hub URL from localhost:3000 to BrowserStacks hub url.
Referring to this code -> .usingServer('http://localhost:3000')
This document has more details: https://www.browserstack.com/local-testing/automate
You just need to make sure to have the same localIdentifier arg in both capabilities AND bsLocalArgs.
That is, both in .withCapabilities(<here>) and new browserstack.Local().start(<here>, ...)

Resources