Skip to content

Instantly share code, notes, and snippets.

View jeremybradbury's full-sized avatar
🎹
Making music

Jeremy Bradbury jeremybradbury

🎹
Making music
  • Portland, OR
  • 19:34 (UTC -07:00)
View GitHub Profile
@jeremybradbury
jeremybradbury / request-wrapper.js
Last active March 24, 2022 06:54
a JS wrapper for NodeJS http/s Request, supports json & forms via post body
// written for NodeJS v12
const https = require("https"); // core node
const http = require("http"); // core node
const qs = require("querystring"); // core node
const isProd = process.env.NODE_ENV === "production";
const debug = process.env.DEBUG;
const request = async (
url = "", // string
options = {}, // any, or see: https://nodejs.org/api/http.html#new-agentoptions
@jeremybradbury
jeremybradbury / six_digit_code.sql
Last active January 9, 2022 09:23
Six Digit Code generated by PostgreSQL on one line. Simple function too.
-- source oneliner - all caps letters + 10 digits - base 36 ~2.17B enums
SELECT array_to_string(array(select substr('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',((random()*(36-1)+1)::integer),1) from generate_series(1,6)),'') AS "Code";
/*
Code
--------
EY25QI
(1 row)
*/
@jeremybradbury
jeremybradbury / stimpyren.js
Last active November 24, 2021 18:33
Log, Log, it's big it's heavy it's wood. Better than bad, it's good
// a very basic Winston replacement, which combines well with a systemd service, to replace most features
const isProd = process.env.NODE_ENV === "production";
const logLog = (level, ...e) => {
switch (true) {
case e && !!e.find((o) => o.redact): // params contain an object with a key called redact: {redact: true}
case isProd && level === "dir":
case isProd && level === "log":
case isProd && level === "info":
@jeremybradbury
jeremybradbury / user-agent-middleware.js
Last active October 9, 2021 00:33
This header can be spoofed, but it can at least block browser calls to your endpoints that are used for for apps only. Don't use this alone, ensure you also have authorization.
// blacklist Mozilla/Opera (all browsers) prefix, with optional overrides
export const noBrowsersMiddleware = async (req, res, next) => {
const client = req.headers["user-agent"];
switch (true) { // yeah it's still faster than if/else
// optional overrrides by platform
// mobile / tablet
//case client.includes('Android') && !client.includes('Windows'):
//case client.includes('iPhone'):
//case client.includes('Windows Phone'):
@jeremybradbury
jeremybradbury / browser-encoder.js
Last active September 27, 2021 01:15
IKR: "Don't do encryption in the browser"... Well what if you plan to compile or "write-once" using Electron/Ionic/NWJS/Cordova solutions?
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
'use strict';
const asn1 = exports;
asn1.bignum = require('bn.js');
asn1.define = require('./asn1/api').define;
asn1.base = require('./asn1/base');
asn1.constants = require('./asn1/constants');
@jeremybradbury
jeremybradbury / upsert-row.js
Created April 17, 2021 01:59
nodejs pg helper - upsertRow
// you'll likely want the pool creation in another file & imported here instead of a new pool
const pool = new require("pg").Pool(); // left here for completeness
// import { pool } from "../db"
// usage example: `upsertRow("profile", {id:"999", bio: "I like to..." image: "https://..."})`
const upsertRow = async (table, row = {}) => {
try {
const fields = Object.keys(row);
const values = Object.values(row);
let q = `INSERT INTO ${table} (${fields.reduce((x, y) => `"${x}", "${y}"`)})
@jeremybradbury
jeremybradbury / rate-limit-middleware-express-redis.js
Last active February 19, 2021 02:42
Simple async request rate limit middleware, for ExpressJS endpoints, using Redis with 1 second TTLs
////
// MIT License
// Copyright (c) 2021 Jeremy Bradbury
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
@jeremybradbury
jeremybradbury / nodejs pg helper - getWherePhraseFromObj
Last active December 17, 2020 00:05
A simple helper function for building where phrases for npmjs.com/package/pg (aka node-postgres)
const getWherePhraseFromObj = (where={}) => {
// input {userid: 11, type: 'admin'}
// output {wherePhrase: 'WHERE userid = $1 AND type = $2', values:[11,'admin']}
const keys = Object.keys(where);
const values = Object.values(where);
console.info({keys, values});
let wherePhrase='';
for (let i=0; i < keys.length; i++) {
if (! wherePhrase) {
wherePhrase = 'WHERE '; // first time: i === 0
@jeremybradbury
jeremybradbury / rsa.js
Last active October 16, 2021 01:30
RSA Encrypt & Decrypt NodeJS Module (v12+, no deps)
const {
generateKeyPairSync,
privateDecrypt,
publicEncrypt,
constants: { RSA_PKCS1_OAEP_PADDING },
} = require("crypto"); // core node
const {
CRYPTIC_PASSPHRASE, // set to enable for your private key (changes require new keys)
CRYPTIC_GENERATE_KEYS, // set CRYPTIC_GENERATE_KEYS=1 to write key files
} = process.env;
@jeremybradbury
jeremybradbury / lanmmnp-ec2-ubuntu16.sh
Last active January 23, 2020 21:24
LANMMNP (Linux Apache Nginx MySQL MongoDB Nodejs12 PHP7 ) Stack provisioning script, designed for Amazon EC2 Ubuntu 16.04 instances
echo "https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-16-04"
echo -n "Skip nginx (y/N)? "
read inginx
if [ "$inginx" != "${inginx#[Yy]}" ] ;then
echo "nginx skipped"
else
echo "installing nginx"
sudo apt-get update
sudo apt-get install nginx
echo "press q to quit less"