Skip to content

Instantly share code, notes, and snippets.

View afraz-khan's full-sized avatar
☁️
data is reality

Afraz Khan afraz-khan

☁️
data is reality
View GitHub Profile
@afraz-khan
afraz-khan / WHITELIST_REQUEST_PATHS.ts
Last active April 28, 2024 12:17
Whitelist request paths
import { Middleware, ExpressMiddlewareInterface } from 'routing-controllers';
import express from 'express';
/**
* Regular expression pattern for whitelisting request paths.
* Each pattern represents an allowed HTTP method and path.
*/
const whiteListedPathsPattern = new RegExp(
[
`^GET /api/user$`,
@afraz-khan
afraz-khan / jwt-sig-hmac.ts
Last active April 28, 2024 12:19
Calculate HMAC for JWT Signature (TypeScript/NodeJS)
import crypto from 'crypto';
export class JwtTokenVerifier {
verifyToken(token: string) {
const [headerEncoded, payloadEncoded, signature] = token.split('.');
const header = this.decodeBase64ToAscii(headerEncoded);
const payload = this.decodeBase64ToAscii(payloadEncoded);
// Other validation checks here
@afraz-khan
afraz-khan / Moment.ts
Last active February 14, 2023 13:52
Moment utilities
const ONE_DAY_INTERVAL = 24 * 60 * 60;
/**
* This method restricts any given moment in time(seconds) to pre midnight like "23:59" or "11:59pm".
*/
export trimTo24HourLimit(
timestamp: number // in seconds
) {
if (timestamp >= ONE_DAY_INTERVAL || timestamp <= -ONE_DAY_INTERVAL) {
timestamp %= ONE_DAY_INTERVAL;
@afraz-khan
afraz-khan / POSTGRES_BACKUP.md
Last active September 9, 2022 14:01
Export a postgres backup and import into some other server.
  1. On the source server(remote/local), export the backup first:
pg_dump -U {username} -h {host} -p {port} -f {output-file-path}.sql {dbname to backup}

copy the backup file to the target server.

  1. On the target server(remote/local), log into the postgres using below command.
@afraz-khan
afraz-khan / POSTGRESQL_TO_CSV.md
Last active April 29, 2022 10:41
Export Postgresql Data to CSV File
  1. Open a terminal and login to your database using below command (LINUX)
$ psql -h [HOST-STRING] -d [DATABASE-NAME] -U [USERNAME]
  1. Now use below command to export data from your database to CSV file
$ \copy (Table/Query) to [path-to-csvfile] csv header

Examples:

@afraz-khan
afraz-khan / VALIDATE_PHONE_REGEX.js
Created April 20, 2022 14:21
Phone Number Validation Regex Nodejs
// E.164 Notation for Phone Numbers
const phonePattern = /^\+[0-9]{7,14}$/;
const phoneNumber = '+2312323231321';
if (!phonePattern.test(phoneNumber)) {
const message =
"Phone number must start with '+' symbol, must have numerical digits only, " +
'min 7 digits and max 15 digits allowed';
@afraz-khan
afraz-khan / AWS_COGNITO_JWT_VERIFIER.ts
Last active April 27, 2023 14:29
AWS Cognito JWT Verification Algorithm | TypeScript
import jwkToPem from 'jwk-to-pem';
import jwt, {JwtPayload, VerifyCallback, VerifyOptions} from 'jsonwebtoken';
import {AppConfig} from '../AppConfig';
import JsonWebTokenException from '../../exception/JsonWebTokenException';
export class CognitoJWTVerifier {
/*
This is application config object having all cognito params.
*/
@afraz-khan
afraz-khan / GENERATE_EXPIRED_JWT.ts
Created February 10, 2022 19:27
Generate an expired JWT in Nodejs.
import * as jwt from 'jsonwebtoken';
export class PastJWTGenerator {
protected jwtSecret: string = 'jwt-secret';
protected expiresIn: number = 60 * 60 * 3; // three hours
// secondsInPast: number of seconds to move back in the past from where token must be issued.
generate(claims: any, secondsInPast: number, secondsToExpireIn?: number) {
const data = {
...claims,
@afraz-khan
afraz-khan / AES_ENCRYPOR_DECRYPTOR.ts
Last active February 10, 2022 19:22
Nodejs AES Text Encrypter/Decrypter.
import {scryptSync, randomBytes, createCipheriv, createDecipheriv} from 'crypto';
export class Encrypter {
private algorithm: string = 'aes-192-cbc';
// encryption key for the cipher
private key: string;
constructor(key: string) {
this.key = key;
@afraz-khan
afraz-khan / CREATE_POSTGRESAL_DATABASE_RDS.md
Created February 10, 2022 11:29
Create new database in existing AWS RDS Postgresql Instance.

Log into your RDS Instance

  • Open a terminal into your local machine.
  • Get hold of credentials of any existing database in your RDS instance.
  • Log into the instance with those DB credentials using below command:
      psql \
       --host=<DB instance endpoint> \
       --port=<port> \
       --username=<master username> \
    

--password \