class-transformer#serialize TypeScript Examples

The following examples show how to use class-transformer#serialize. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: result.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
// this is a helper method that allows use to utilize the class-transformer
    // when working with express.js returns
    public asResponse(resp: express.Response, code?: number) {
        if (this.isError) {
            resp.status(this.error?.errorCode ? this.error.errorCode : 500);
        } else if (code) {
            resp.status(code);
        } else {
            resp.status(200);
        }

        resp.setHeader('Content-Type', 'application/json');
        resp.send(serialize(this));
    }
Example #2
Source File: type_mapping_repository.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
private async setCache(t: TypeMapping): Promise<boolean> {
        let set = await Cache.set(`${TypeMappingMapper.tableName}:${t.id}`, serialize(t), Config.cache_default_ttl);
        if (!set) Logger.error(`unable to set cache for type mapping${t.id}`);

        set = await Cache.set(
            `${TypeMappingMapper.tableName}:dataSourceID:${t.data_source_id}:shapeHash:${t.shape_hash}`,
            serialize(t),
            Config.cache_default_ttl,
        );
        if (!set) Logger.error(`unable to set cache for type mapping${t.id}`);

        return Promise.resolve(set);
    }
Example #3
Source File: oauth_routes.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
private static registerPage(req: Request, res: Response, next: NextFunction) {
        return res.render('register', {
            // @ts-ignore
            _csrfToken: req.csrfToken(),
            oauthRequest: serialize(oauthRepo.authorizationFromRequest(req)),
            _success: req.query.success ? DOMPurify.sanitize(req.query.success as string) : undefined,
            _error: req.query.error ? DOMPurify.sanitize(req.query.error as string) : undefined,
        });
    }
Example #4
Source File: repository.ts    From leapp with Mozilla Public License 2.0 5 votes vote down vote up
persistWorkspace(workspace: Workspace): void {
    const path = this.nativeService.os.homedir() + "/" + constants.lockFileDestination;
    this.fileService.writeFileSync(path, this.fileService.encryptText(serialize(workspace)));
  }
Example #5
Source File: retro-compatibility-service.ts    From leapp with Mozilla Public License 2.0 5 votes vote down vote up
private persists(workspace: Workspace): void {
    this.fileService.writeFileSync(
      this.fileService.homeDir() + "/" + constants.lockFileDestination,
      this.fileService.encryptText(serialize(workspace))
    );
  }
Example #6
Source File: base-injectables.ts    From leapp with Mozilla Public License 2.0 5 votes vote down vote up
spyFileService.readFileSync.and.callFake((_: string) => serialize(new Workspace()));
Example #7
Source File: type_transformation_repository.ts    From Deep-Lynx with MIT License 5 votes vote down vote up
private async setCache(t: TypeTransformation): Promise<boolean> {
        const set = await Cache.set(`${TypeTransformationMapper.tableName}:${t.id}`, serialize(t), Config.cache_default_ttl);
        if (!set) Logger.error(`unable to set cache for type transformation ${t.id}`);

        return Promise.resolve(set);
    }
Example #8
Source File: container_respository.ts    From Deep-Lynx with MIT License 5 votes vote down vote up
private async setCache(c: Container): Promise<boolean> {
        const set = await Cache.set(`${ContainerMapper.tableName}:${c.id}`, serialize(c), Config.cache_default_ttl);
        if (!set) Logger.error(`unable to set cache for container ${c.id}`);

        return Promise.resolve(set);
    }
Example #9
Source File: metatype_key_repository.ts    From Deep-Lynx with MIT License 5 votes vote down vote up
async setCachedForMetatype(metatypeID: string, keys: MetatypeKey[]): Promise<boolean> {
        const set = await Cache.set(`${MetatypeMapper.tableName}:${metatypeID}:keys`, serialize(keys), Config.cache_default_ttl);
        if (!set) Logger.error(`unable to set cache for metatype ${metatypeID}'s keys`);

        return Promise.resolve(set);
    }
Example #10
Source File: metatype_relationship_pair_repository.ts    From Deep-Lynx with MIT License 5 votes vote down vote up
private async setCache(p: MetatypeRelationshipPair): Promise<boolean> {
        const set = await Cache.set(`${MetatypeRelationshipPairMapper.tableName}:${p.id}`, serialize(p), Config.cache_default_ttl);
        if (!set) Logger.error(`unable to set cache for metatype relationship pair ${p.id}`);

        return Promise.resolve(set);
    }
Example #11
Source File: metatype_relationship_repository.ts    From Deep-Lynx with MIT License 5 votes vote down vote up
private async setCache(m: MetatypeRelationship): Promise<boolean> {
        const set = await Cache.set(`${MetatypeRelationshipMapper.tableName}:${m.id}`, serialize(m), Config.cache_default_ttl);
        if (!set) Logger.error(`unable to set cache for metatype relationship ${m.id}`);

        return Promise.resolve(set);
    }
Example #12
Source File: metatype_repository.ts    From Deep-Lynx with MIT License 5 votes vote down vote up
private async setCache(m: Metatype): Promise<boolean> {
        const set = await Cache.set(`${MetatypeMapper.tableName}:${m.id}`, serialize(m), Config.cache_default_ttl);
        if (!set) Logger.error(`unable to set cache for metatype ${m.id}`);

        return Promise.resolve(set);
    }
Example #13
Source File: type_mapping_routes.ts    From Deep-Lynx with MIT License 5 votes vote down vote up
private static exportTypeMappings(req: Request, res: Response, next: NextFunction) {
        const user = req.currentUser!;
        const mappingRepo = new TypeMappingRepository();

        if (req.dataSource) {
            let payload: TypeMappingExportPayload | undefined;
            if (req.body) payload = plainToClass(TypeMappingExportPayload, req.body as object);

            // list all the mappings from the supplied data source, or only those mappings specified by the payload
            let query = mappingRepo.where().containerID('eq', req.container?.id).and().dataSourceID('eq', req.dataSource.DataSourceRecord?.id);

            if (payload && payload.mapping_ids && payload.mapping_ids.length > 0) {
                query = query.and().id('in', payload.mapping_ids);
            }

            query
                .list()
                .then((results) => {
                    if (results.isError) {
                        results.asResponse(res);
                        next();
                        return;
                    }
                    // if there is no data source specified prep the mappings and return as a .json file
                    if (!payload || !payload?.target_data_source) {
                        const prepared = [];

                        for (const mapping of results.value) {
                            prepared.push(mappingRepo.prepareForImport(mapping, true));
                        }

                        Promise.all(prepared)
                            .then((preparedMappings) => {
                                res.setHeader('Content-disposition', 'attachment; filename= exportedMappings.json');
                                res.setHeader('Content-type', 'application/json');
                                res.write(serialize(preparedMappings), (err) => {
                                    res.end();
                                });
                            })
                            .catch((e) => {
                                Result.Failure(e).asResponse(res);
                                next();
                            });
                    } else {
                        mappingRepo
                            .importToDataSource(payload.target_data_source, user, ...results.value)
                            .then((result) => {
                                res.status(200).json(result);
                                next();
                            })
                            .catch((e) => {
                                Result.Failure(e).asResponse(res);
                                next();
                            });
                    }
                })
                .catch((e) => {
                    Result.Failure(e).asResponse(res);
                    next();
                });
        } else {
            Result.Failure(`data source not found`).asResponse(res);
            next();
        }
    }
Example #14
Source File: router.ts    From Deep-Lynx with MIT License 5 votes vote down vote up
private mountAuthMiddleware(): void {
        // BasicStrategy should be used only on the endpoints that we want secured, but don't care if they're "secure"
        // basic auth is considered insufficient for production applications.
        passport.use(
            new BasicStrategy((userID, password, done) => {
                if (userID === Config.basic_user && password === Config.basic_password) {
                    return done(null, serialize(SuperUser));
                }

                return done(null, false);
            }),
        );

        // SetSaml will initialize and assign the saml auth strategy
        if (Config.saml_enabled) SetSamlAdfs(this.app);
        SetLocalAuthMethod(this.app);

        // Once a user has authed against one of the accepted auth methods - the application using the API must
        // use a JWT for each subsequent request
        SetJWTAuthMethod(this.app);

        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore - as of 1/6/2021 passport.js types haven't been updated
        passport.serializeUser((user: User, done: any) => {
            if (typeof user === 'string') {
                user = JSON.parse(user);
            }
            user.password = '';
            done(null, user.id);
        });

        passport.deserializeUser((user: string, done: any) => {
            void UserMapper.Instance.Retrieve(user).then((result) => {
                if (result.isError) done('unable to retrieve user', null);

                done(null, result.value);
            });
        });

        // finalize passport.js usage
        this.app.use(passport.initialize());
        this.app.use(passport.session());
        this.app.use(currentUser()); // current user can be pulled after passport runs
    }
Example #15
Source File: sse.service.ts    From office-hours with GNU General Public License v3.0 5 votes vote down vote up
/** Send some data to everyone in a room */
  async sendEvent<D>(
    room: string,
    payload: (metadata: T) => Promise<D>,
  ): Promise<void> {
    const redisPub = this.redisService.getClient('pub');
    const redis = this.redisService.getClient('db');

    if (!redisPub) {
      Sentry.captureException(ERROR_MESSAGES.sseService.getPubClient);
      throw new Error(ERROR_MESSAGES.sseService.getPubClient);
    }

    if (!redis) {
      Sentry.captureException(ERROR_MESSAGES.sseService.getDBClient);
      throw new Error(ERROR_MESSAGES.sseService.getDBClient);
    }

    const roomInfo = await redis.smembers(room).catch((err) => {
      console.error(ERROR_MESSAGES.sseService.roomMembers);
      console.error(err);
      Sentry.captureException(err);
    });
    if (room && roomInfo) {
      const clients: RedisClientInfo<T>[] = roomInfo.map((s) => JSON.parse(s));
      console.log(`sending sse to ${clients.length} clients in ${room}`);
      console.time(`sending sse time: `);
      await each(clients, async ({ clientId, metadata }) => {
        const toSend = serialize(
          await payload(metadata).catch((err) => {
            console.error(ERROR_MESSAGES.sseService.serialize);
            console.error(err);
            Sentry.captureException(err);
          }),
        );
        await redisPub
          .publish(this.idToChannel(clientId), toSend)
          .catch((err) => {
            console.error(ERROR_MESSAGES.sseService.publish);
            console.error(err);
            Sentry.captureException(err);
          });
      });
      console.timeEnd(`sending sse time: `);
    }
  }
Example #16
Source File: saml-adfs.ts    From Deep-Lynx with MIT License 4 votes vote down vote up
export function SetSamlAdfs(app: express.Application) {
    // do not set the auth strategy if we don't have a public/private key pair.
    // If a user attempts to auth with this strategy attempting the login routes
    // without a public/private key present the application will return an error
    if (!Config.saml_adfs_private_cert_path || !Config.saml_adfs_public_cert_path) return;

    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore - as of 1/6/2021 passport.js types haven't been updated
    passport.serializeUser((user: User, done: any) => {
        if (typeof user === 'string') {
            user = JSON.parse(user);
        }
        user.password = '';
        done(null, user.id);
    });

    passport.deserializeUser((user: string, done: any) => {
        void UserMapper.Instance.Retrieve(user).then((result) => {
            if (result.isError) done('unable to retrieve user', null);

            done(null, result.value);
        });
    });

    passport.use(
        new SamlStrategy(
            {
                entryPoint: Config.saml_adfs_entry_point,
                issuer: Config.saml_adfs_issuer,
                callbackUrl: Config.saml_adfs_callback,
                privateCert: fs.readFileSync(Config.saml_adfs_private_cert_path, 'utf-8'),
                cert: fs.readFileSync(Config.saml_adfs_public_cert_path, 'utf-8'),
                signatureAlgorithm: 'sha256',
                RACComparison: 'exact',
                disableRequestedAuthnContext: true,
                identifierFormat: null,
            },
            (profile: any, done: any) => {
                const storage = UserMapper.Instance;

                return new Promise((resolve) => {
                    storage
                        .RetrieveByEmail(profile[Config.saml_claims_email])
                        .then((result) => {
                            if (result.isError && result.error?.errorCode !== 404) {
                                resolve(done(result.error, false));
                            }

                            if (result.isError && result.error?.errorCode === 404) {
                                void storage.List().then((users) => {
                                    // if there are no other users of this Deep Lynx instance
                                    // we go ahead and assign admin status to this newly created
                                    // user
                                    void storage
                                        .Create(
                                            'saml-adfs login',
                                            new User({
                                                identity_provider_id: profile[Config.saml_claims_email],
                                                identity_provider: 'saml_adfs',
                                                display_name: profile[Config.saml_claims_name],
                                                email: profile[Config.saml_claims_email],
                                                admin: users.value.length === 0,
                                            }),
                                        )
                                        .then((user: Result<User>) => {
                                            if (user.isError) {
                                                resolve(done(user.error, false));
                                            }

                                            resolve(done(null, serialize(user.value)));
                                        });
                                });
                            } else {
                                resolve(done(null, serialize(result.value)));
                            }
                        })
                        .catch((error) => resolve(done(error, false)));
                });
            },
        ),
    );
}