I need some help to implement SAML 2.0 SSO with passport-saml, is used a different strategy to implement the app:
(is not my strategy and I'm not very used to nodejs, i read every documentation possible like: https://github.com/node-saml/passport-saml/blob/master/README.md
but i dont have any idea how to adapt it to this code)
app.ts:
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import dotenv from 'dotenv';
import Controller from '../controllers/controller';
dotenv.config();
class App {
public app: express.Application;
public port: number;
constructor(controllers: Controller[], port: number) {
this.app = express();
this.port = port;
this.initializeMiddlewares();
this.initializeControllers(controllers);
}
private initializeMiddlewares() {
this.app.use(bodyParser.urlencoded({extended : true}));
this.app.use(cors());
}
private initializeControllers(controllers: Controller[]) {
controllers.forEach((controller: Controller) => {
this.app.use('/', controller.router);
});
}
public listen() {
this.app.listen(this.port, () => {
console.log(`App listening on the port ${this.port}`);
});
}
}
export default App;
controller.ts
import { Request, Response, Router } from 'express';
import { GenericErrorResponse, GenericSuccessResponse } from '../models/response/response.model';
class Controller {
public path: string;
public router = Router();
constructor(path: string) {
this.path = path;
}
public generateErrorResponse(status: string, error: any) {
return new GenericErrorResponse(status, error);
}
public generateSuccessResponse(status: string, data: any) {
return new GenericSuccessResponse(status, data);
}
}
export default Controller;
server.ts
import App from './app';
import TestController from '../controllers/test.controller';
const app = new App(
[
new TestController('/test'),
],
parseInt(`${process.env.PORT}`, 10) || 3000
);
app.listen();
test.controller.ts(where I implement every route)
import { Request, Response } from 'express';
import Controller from './controller';
class TestController extends Controller {
constructor(path: string) {
super(path);
this.intializeRoutes();
}
private intializeRoutes() {
this.router.get(`${this.path}/general`, this.getGeneral);
}
getGeneral = (request: Request, response: Response) => {
response.status(200).json(this.generateSuccessResponse('Success', 'Success'));
}
}
export default TestController;
Related
I am trying to combine peer server with my nestjs application. Unfortunately it doesn't work as expected. I am creating a service containing the peer server instance and initialize it on application start. I also use this service to handle requests coming
in a specific controller. I did the configuration as follow:
main.ts
import { NestFactory } from '#nestjs/core';
import { NestExpressApplication } from '#nestjs/platform-express';
import { I18nMiddleware } from 'nestjs-i18n';
import { Logger, LoggerErrorInterceptor } from 'nestjs-pino';
import { AppModule } from './app.module';
import { PeerServerService } from './peer-server/peer-server.service';
import { PrismaService } from './prisma/prisma.service';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
bufferLogs: true,
});
app.useLogger(app.get(Logger));
app.useGlobalInterceptors(new LoggerErrorInterceptor());
app.use(I18nMiddleware);
const prismaService = app.get(PrismaService);
const peerServerService = app.get(PeerServerService);
prismaService.enableShutdownHooks(app);
peerServerService.enablePeerServer(app);
await app.listen(3000);
}
bootstrap();
peer-server.service.ts
import { Injectable } from '#nestjs/common';
import { NestExpressApplication } from '#nestjs/platform-express';
import { ExpressPeerServer, PeerServerEvents } from 'peer';
import { Express } from 'express';
#Injectable()
export class PeerServerService {
peerServer: Express & PeerServerEvents;
enablePeerServer(app: NestExpressApplication) {
this.peerServer = ExpressPeerServer(app.getHttpServer(), {
path: '/myapp',
});
console.log('peer server: ', this.peerServer);
this.peerServer.get('/test', (req, res) => {
res.send('hello');
});
}
}
peer-server.controller.ts
import { All, Controller, Next, Req, Res } from '#nestjs/common';
import { NextFunction, Request, Response } from 'express';
import { PeerServerService } from './peer-server.service';
#Controller('/peer-server')
export class PeerServerController {
constructor(private readonly peerServerService: PeerServerService) {}
#All('*')
server(
#Req() request: Request,
#Res() response: Response,
#Next() next: NextFunction,
) {
const entryPointPath = '/peer-server/';
request.url = request.url.replace(entryPointPath, '/');
console.log('in route peer: ', request.url);
this.peerServerService.peerServer(request, response, next);
}
}
I verified that the server is correctly forwarded to the peer service with this request
this.peerServer.get('/test', (req, res) => {
res.send('hello');
});
Sending a request to /peer-server/test works but /peer-server/myapp returns 404
Has anyone ever done that successfully ?
I want to implement SAML 2.0 SSO with passport-saml library but I don't know where to insert it.
I tried to follow this documentation: https://github.com/node-saml/passport-saml but i have no idea where to insert the saml strategy..
and here is my app:
app.ts:
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import dotenv from 'dotenv';
import Controller from '../controllers/controller';
dotenv.config();
class App {
public app: express.Application;
public port: number;
constructor(controllers: Controller[], port: number) {
this.app = express();
this.port = port;
this.initializeMiddlewares();
this.initializeControllers(controllers);
}
private initializeMiddlewares() {
this.app.use(bodyParser.urlencoded({extended : true}));
this.app.use(cors());
}
private initializeControllers(controllers: Controller[]) {
controllers.forEach((controller: Controller) => {
this.app.use('/', controller.router);
});
}
public listen() {
this.app.listen(this.port, () => {
console.log(`App listening on the port ${this.port}`);
});
}
}
export default App;
controller.ts:
import { Request, Response, Router } from 'express';
import { GenericErrorResponse, GenericSuccessResponse } from '../models/response/response.model';
class Controller {
public path: string;
public router = Router();
constructor(path: string) {
this.path = path;
}
public generateErrorResponse(status: string, error: any) {
return new GenericErrorResponse(status, error);
}
public generateSuccessResponse(status: string, data: any) {
return new GenericSuccessResponse(status, data);
}
}
export default Controller;
server.ts
import App from './app';
import TestController from '../controllers/test.controller';
const app = new App(
[
new TestController('/test'),
],
parseInt(`${process.env.PORT}`, 10) || 3000
);
app.listen();
test.controller.ts(where is implemented every route)
import { Request, Response } from 'express';
import Controller from './controller';
class TestController extends Controller {
constructor(path: string) {
super(path);
this.intializeRoutes();
}
private intializeRoutes() {
this.router.get(`${this.path}/general`, this.getGeneral);
}
getGeneral = (request: Request, response: Response) => {
response.status(200).json(this.generateSuccessResponse('Success', 'Success'));
}
}
export default TestController;
I'm using nodejs with typescript, typeorm and inversify to manage dependency injection and inversify express utils to handle controllers, when I send a response inside then or catch block only returns a 204 no content response, but if I send the response out of the promise it works, someone who has worked with inversify know what could be happening?
User Controller:
#controller("/user")
export class UserController implements interfaces.Controller {
constructor(#inject(TYPES.UserService) private _userService: IUserService) {}
#httpGet("/")
public GetAll(#request() req: Request, #response() res: Response) {
this._userService
.GetAll()
.then((users) => res.send(users))
.catch((error) => res.send(error));
}
}
User Service:
#injectable()
export class UserService implements IUserService {
private readonly _userRepository: IUserRepository;
constructor(#inject(TYPES.UserRepository) userRepository: IUserRepository) {
this._userRepository = userRepository;
}
public GetAll(): Promise<Array<User>> {
return this._userRepository.GetAll();
}
}
User repository:
#injectable()
export class UserRepository implements IUserRepository {
public GetAll(): Promise<Array<User>> {
const userRepository = getRepository(User);
return userRepository.find();
}
Container and server config:
export abstract class ServerConfig {
protected app: Application;
constructor() {
this.Config();
}
private Config(): void {
const container = new Container();
container.bind<IUserService>(TYPES.UserService).to(UserService);
container.bind<IUserRepository>(TYPES.UserRepository).to(UserRepository);
const server = new InversifyExpressServer(container);
server.setConfig((app) => {
app.use(cors());
app.use(helmet());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(morgan("dev"));
dotenv.config();
app.set("port", process.env.PORT || 8000);
});
this.app = server.build();
}
public Start(): void {
this.app.listen(this.app.get("port"), () => {
console.log(`Server on port ${this.app.get("port")}`);
});
}
}
you need to return the promise or just await the response from the service. Something like this:
#controller("/user")
export class UserController implements interfaces.Controller {
constructor(#inject(TYPES.UserService) private _userService: IUserService) {}
#httpGet("/")
public async GetAll(#request() req: Request, #response() res: Response): Response {
try {
const users = await this._userService.GetAll();
return res.status(200).json(users);
} catch(error) {
return res.status(500).json(error)
}
}
}
I have create push notification with angular and nodejs ..when I valid article i will send push notification to user will create article ... User1 create article and when admin valid this article user1 receive notification ... this is my code in general for receive notification but where is modification in my code for receive notification only for user1 .
code service angular:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
const SERVER_URL = 'http://localhost:3000/subscription';
#Injectable()
export class PushNotificationService {
constructor(private http: HttpClient) {}
public sendSubscriptionToTheServer(subscription: PushSubscription) {
return this.http.post(SERVER_URL, subscription);
}
}
code component:
import { Component, OnInit } from '#angular/core';
import { SwPush } from '#angular/service-worker';
import { PushNotificationService } from '../../services/push-notification.service';
const VAPID_PUBLIC = "BJPrg7jbhWkWZn5mhg0Wti8031cHjsLGyN1G4pmfeippmEsXHo53wnRiqqjApVkA1KQyIz0IYK4ln0ie7RLrsiI";
const PRIVATE = "D1njq6Y7ny2QexJ-JZXbUpufCkfIywLSMvO6s-iSNoQ";
#Component({
selector: 'app-test-component',
templateUrl: './test-component.component.html',
styleUrls: ['./test-component.component.scss']
})
export class TestComponentComponent implements OnInit {
constructor(public swPush: SwPush, public pushService: PushNotificationService) {
}
test(){
if (this.swPush.isEnabled) {
this.swPush
.requestSubscription({
serverPublicKey: VAPID_PUBLIC
})
.then(subscription => {
this.pushService.sendSubscriptionToTheServer(subscription).subscribe();
})
.catch(console.error);
}
}
ngOnInit() {
}
}
code nodejs:
const express = require('express');
const webpush = require('web-push');
const cors = require('cors');
const bodyParser = require('body-parser');
const PUBLIC_VAPID = 'BJPrg7jbhWkWZn5mhg0Wti8031cHjsLGyN1G4pmfeippmEsXHo53wnRiqqjApVkA1KQyIz0IYK4ln0ie7RLrsiI';
const PRIVATE_VAPID = 'D1njq6Y7ny2QexJ-JZXbUpufCkfIywLSMvO6s-iSNoQ';
const fakeDatabase = [];
const app = express();
app.use(cors());
app.use(bodyParser.json());
webpush.setVapidDetails('mailto:mailto#gmail.com', PUBLIC_VAPID, PRIVATE_VAPID);
app.post('/subscription', (req, res) => {
const subscription = req.body;
fakeDatabase.push(subscription);
const notificationPayload = {
notification: {
title: 'New Notification',
body: 'This is the body of the notification',
icon: 'assets/icons/icon-512x512.png'
}
};
const promises = [];
fakeDatabase.forEach(subscription => {
promises.push(webpush.sendNotification(subscription, JSON.stringify(notificationPayload)));
});
fakeDatabase.length =0
Promise.all(promises).then(() => res.sendStatus(200));
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
help me and thank you for advanced
I am creating an app with typescript express node typeorm. I am having this issue where when I make a call through a service class to the database using typeorm, I get connection default was not found. Here are my code snippets:
//dataservice class
import { Connection, getConnection, EntityManager, Repository,
getManager } from "typeorm";
export class LeaveDataService {
private _db: Repository<Leave>;
constructor() {
this._db = getManager().getRepository(Leave);
}
/**
* applyForLeave
*/
public applyForLeave(leave: Leave): void {
if(leave !== null) {
let entity: Leave = this._db.create(leave);
this._db.save(entity);
}
}
/**
* getAllLeaves
*/
public async getAllLeaves(): Promise<Array<Leave>> {
let leaves: Promise<Array<Leave>> = this._db.find({
select: ["leaveDays","casualLeaveDays","id","staff","leaveType","endorsedBy","approvedBy"],
relations: ["staff", "leaveType"],
skip: 5,
take: 15
});
return leaves;
}
this is my ormconfig.json
{
"type":"sqlite",
"entities": ["./models/*.js"],
"database": "./leaveappdb.sql"
}
and this is the "controller" that responds to requests by calling the service class which is the first snippet:
import { Request, Response } from "express";
import { LeaveDataService } from "../services/leaveDataService";
import { LeaveIndexApiModel } from '../ApiModels/leaveIndexApiModel';
const dataService: LeaveDataService = new LeaveDataService();
export let index = async (req: Request, res: Response) => {
let result = await dataService.getAllLeaves();
let viewresult = new Array<LeaveIndexApiModel>();
result.forEach(leave => {
let apmodel =
new LeaveIndexApiModel(leave.leaveType.name,
`${leave.staff.firstname} ${leave.staff.lastname}`, leave.id);
viewresult.push(apmodel);
});
return res.status(200).send(viewresult);
}
then this is where I bootstrap my app.
import express = require('express');
import bodyParser = require('body-parser');
import path = require('path');
import * as home from './controllers/home';
import { createConnection } from 'typeorm';
import * as leavectrl from "./controllers/leaveController";
//create express server
//create app db connection.
createConnection().then(async connection => {
const app = express();
console.log("DB online!");
const approot = './';
const appport = process.env.Port || 8001;
//setup express for json parsing even with urlencoding
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(approot,'dist')));
//serve and respond to routes by api
app.get('/home', home.home);
app.get('/login',home.login);
//routes for leave
app.get('/api/leaves', leavectrl.index);
//default fall through
// app.get('*', (req: Request, res: Response)=>{
// res.sendFile(approot,'dist/index.html');
// });
app.listen(appport, ()=> console.log(`api is alive on port
${appport}`));
}).catch(error => console.log("Data Access Error : ", error));
Your configuration is seems to be good but you didn't called or used your ormconfig.json file to createConnection.
for Eg:
createConnection(./ormconfig.json).then(async connection => {
}).catch(error => console.log("Data Access Error : ", error));
Try with or i will give you a way to configure with class object to establish a DB connection
In config file:
import "reflect-metadata";
import { ConnectionOptions } from "typeorm";
import { abc } from "../DatabaseEntities/abc";
import { def } from '../DatabaseEntities/def';
export let dbOptions: ConnectionOptions = {
type: "sqlite",
name: app,
database: "./leaveappdb.sqlite3",
entities: [abc, def],
synchronize: true,
}
In server.ts
import { createConnection, createConnections } from 'typeorm';
import * as appConfig from './Config/config';
createConnection(appConfig.dbOptions).then(async connection => {
console.log("Connected to DB");
}).catch(error => console.log("TypeORM connection error: ", error));
I think this may help you..
Also, i have found that for connecting sqlite DB you are trying to connect a sql file. Kindly confirm that once too.
Thank you