Skip to content

Instantly share code, notes, and snippets.

View t1mofe1's full-sized avatar

Timothy Myagi t1mofe1

View GitHub Profile
@t1mofe1
t1mofe1 / pkce.ts
Last active March 7, 2024 08:49
PKCE Generator in nodejs which generates `code_challenge` and `code_verifier` using sha256. Implemented custom length feature.
import * as crypto from 'crypto';
export type PkcePayload = {
code_verifier: string;
code_challenge: string;
code_challenge_method: 'S256';
};
export default function generatePKCE(length = 128): PkcePayload {
if (length < 43) length = 43;
@t1mofe1
t1mofe1 / time-helper.ts
Last active October 25, 2022 21:44
IMPORTANT!! `formatStrToTime` will show different result if you did `formatTimeToStr` with different depth
export const timeUnits = [
// { name: "y", milliseconds: 31_536_000_000 },
// { name: "mo", milliseconds: 2_592_000_000 },
{ name: "d", milliseconds: 86_400_000 },
{ name: "h", milliseconds: 3_600_000 },
{ name: "m", milliseconds: 60_000 },
{ name: "s", milliseconds: 1_000 },
{ name: "ms", milliseconds: 1 },
];
@t1mofe1
t1mofe1 / Number.toFixedNoRounding.js
Last active August 6, 2021 22:32
Number.toFixed is rounding numbers, but this don't do that. It's just converting float to int.
Number.prototype.toFixedNoRounding = function toFixedNoRounding(n = 0) {
if (n < 0) n = 0;
const str = this.toString();
const dot = str.indexOf('.');
if (dot === -1) return this;
return Number(str.slice(0, dot) + n !== 0 ? str.substr(dot, dot + n) : '');
};
@t1mofe1
t1mofe1 / time-helper.js
Created June 25, 2021 10:14
Time string formatter
/**
* @function formatTime
* @param {string} str - string with all times joined with space. Ex: "10s 4m"
* @returns {string} total time in milliseconds
*/
module.exports = function formatTime(str) {
let totalTime = 0;
str.split(' ').forEach((field) => {
field = field.trim();
const regex = /(?<time>[0-9]{1,})(?<type>ms|s|m|h|d|w)/gi;
@t1mofe1
t1mofe1 / email-verification.js
Last active June 25, 2021 10:08
Email verification system
const crypto = require('crypto');
const createError = (field, last = 'provided') => { throw Error(`${field} needs to be ${last}!`); };
const genHash = (secret, email, expiry, separator) => crypto.createHmac('sha256', secret).update(`${email}${separator}${expiry}`).digest('hex');
/**
* @function createHash
* @param {string} email - email
* @param {string|number} secret - your secret (DO NOT PUBLISH IT)
* @param {number|string} expiry - time in ms, when verification hash will be expired