repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
0xBeaver/snarkswap-client
|
src/lib/note.ts
|
import assert from 'assert';
import circomlib from 'circomlib';
import { BigNumber, BigNumberish } from 'ethers';
export type Note = {
readonly address: BigNumberish;
readonly amount: BigNumberish;
readonly pubKey: readonly BigNumberish[];
readonly salt: BigNumberish;
};
const One = BigNumber.from(1);
export const getNoteHash = (note: Note): BigNumber => {
assert(One.shl(160).gt(note.address), 'invalid address');
assert(One.shl(239).gt(note.amount), 'invalid amount');
assert(One.shl(254).gt(note.pubKey[0]), 'invalid pubkey');
assert(One.shl(254).gt(note.pubKey[1]), 'invalid pubkey');
assert(One.shl(128).gt(note.salt), 'no need for too large salt ');
const noteHash = circomlib.poseidon([
BigInt(BigNumber.from(note.address)),
BigInt(BigNumber.from(note.amount)),
BigInt(BigNumber.from(note.pubKey[0])),
BigInt(BigNumber.from(note.pubKey[1])),
BigInt(BigNumber.from(note.salt)),
]);
return BigNumber.from(noteHash);
};
|
0xBeaver/snarkswap-client
|
src/types/chacha.d.ts
|
<gh_stars>1-10
declare module 'chacha20' {
const encrypt: (privKey: Buffer, nonce: Buffer, data: Buffer) => Buffer;
const decrypt: (privKey: Buffer, nonce: Buffer, data: Buffer) => Buffer;
export { encrypt, decrypt };
}
|
0xBeaver/snarkswap-client
|
src/lib/utils.spec.ts
|
<gh_stars>1-10
import test from 'ava';
import { Wallet } from 'ethers';
import { genEdDSAPrivKey } from './utils';
test('genEdDSAPrivKey', async (t) => {
const ecdsaPrivKey = '0xabcd';
const wallet = new Wallet(ecdsaPrivKey);
const eddsaPriv = genEdDSAPrivKey(Buffer.from('abcd', 'hex'), wallet);
t.not(eddsaPriv, undefined);
});
|
0xBeaver/snarkswap-client
|
src/types/circomlib.d.ts
|
<filename>src/types/circomlib.d.ts
/**
* If you import a dependency which does not include its own type definitions,
* TypeScript will try to find a definition for it by following the `typeRoots`
* compiler option in tsconfig.json. For this project, we've configured it to
* fall back to this folder if nothing is found in node_modules/@types.
*
* Often, you can install the DefinitelyTyped
* (https://github.com/DefinitelyTyped/DefinitelyTyped) type definition for the
* dependency in question. However, if no one has yet contributed definitions
* for the package, you may want to declare your own. (If you're using the
* `noImplicitAny` compiler options, you'll be required to declare it.)
*
* This is an example type definition which allows import from `module-name`,
* e.g.:
* ```ts
* import something from 'module-name';
* something();
* ```
*/
declare module 'circomlib' {
type EdDSASignature = {
readonly R8: readonly bigint[];
readonly S: bigint;
};
const poseidon: (values: readonly bigint[]) => bigint;
const eddsa: {
readonly sign: (
privKey: string | Buffer,
message: bigint
) => EdDSASignature;
readonly signMiMC: (
privKey: string | Buffer,
message: bigint
) => EdDSASignature;
readonly signMiMCSponge: (
privKey: string | Buffer,
message: bigint
) => EdDSASignature;
readonly signPoseidon: (
privKey: string | Buffer,
message: bigint
) => EdDSASignature;
readonly verify: (
message: bigint,
signature: EdDSASignature,
publicKey: readonly bigint[]
) => boolean;
readonly verifyPoseidon: (
message: bigint,
signature: EdDSASignature,
publicKey: readonly bigint[]
) => boolean;
readonly verifyMiMC: (
message: bigint,
signature: EdDSASignature,
publicKey: readonly bigint[]
) => boolean;
readonly verifyMiMCSponge: (
message: bigint,
signature: EdDSASignature,
publicKey: readonly bigint[]
) => boolean;
readonly packSignature: (signature: EdDSASignature) => Buffer;
readonly unpackSignature: (signature: Buffer) => EdDSASignature;
readonly prv2pub: (privKey: string | Buffer) => readonly bigint[];
readonly pruneBuffer: (buff: Buffer) => Buffer;
};
export { EdDSASignature, poseidon, eddsa };
}
|
0xBeaver/snarkswap-client
|
src/lib/utils.ts
|
<reponame>0xBeaver/snarkswap-client<filename>src/lib/utils.ts
import assert from 'assert';
import { decrypt } from 'chacha20';
import { eddsa } from 'circomlib';
import { BigNumber, BigNumberish, Bytes, Signer } from 'ethers';
import { arrayify, BytesLike, keccak256 } from 'ethers/lib/utils';
import { SnarkjsProof } from 'snarkjs';
import { getNoteHash, Note } from './note';
export const PRIME_Q = 21888242871839275222246405745257275088696311157297823662689037894645226208583n;
export type Proof = {
readonly a: readonly BigNumber[];
readonly b: readonly (readonly BigNumber[])[];
readonly c: readonly BigNumber[];
};
export const privToBuffer = (privKey: BigNumberish): Buffer => {
const buff = Buffer.from(arrayify(BigNumber.from(privKey).toHexString()));
return buff;
};
export const privToPubKey = (privKey: BigNumberish): readonly BigNumber[] => {
const privKeyBuff = privToBuffer(privKey);
const pubKey = eddsa.prv2pub(privKeyBuff);
return pubKey.map((n) => BigNumber.from(n));
};
export const snarkjsProofToContractArg = (proof: SnarkjsProof): Proof => {
return {
a: proof.pi_a.map((n) => BigNumber.from(n)),
b: [
[...proof.pi_b[0]].reverse().map((n) => BigNumber.from(n)),
[...proof.pi_b[1]].reverse().map((n) => BigNumber.from(n)),
],
c: proof.pi_c.map((n) => BigNumber.from(n)),
};
};
export const proofToSnarkjsProof = (proof: Proof): SnarkjsProof => {
return {
pi_a: proof.a.map((bn) => BigInt(bn)),
pi_b: [
[...proof.b[0]].reverse().map((bn) => BigInt(bn)),
[...proof.b[1]].reverse().map((bn) => BigInt(bn)),
],
pi_c: proof.c.map((bn) => BigInt(bn)),
protocol: 'groth16',
};
};
export const genEdDSAPrivKey = async (
message: string | Bytes,
signer: Signer
): Promise<BigNumber> => {
const ecdsa = await signer.signMessage(message);
const privKey = BigNumber.from(keccak256(ecdsa)).mod(BigNumber.from(PRIME_Q));
return privKey;
};
export type FeeRatio = {
readonly numerator: number;
readonly denominator: number;
};
export const getAmountOut = (
amountIn: BigNumberish,
reserveIn: BigNumberish,
reserveOut: BigNumberish,
feeRatio?: FeeRatio
): BigNumber => {
const _feeNumerator = feeRatio?.numerator || 3;
const _feeDeonminator = feeRatio?.denominator || 1000;
const _amountIn = BigNumber.from(amountIn);
const _reserveIn = BigNumber.from(reserveIn);
const amountInWithFee = _amountIn.mul(_feeDeonminator - _feeNumerator);
const numerator = amountInWithFee.mul(reserveOut);
const denominator = _reserveIn.mul(_feeDeonminator).add(amountInWithFee);
return numerator.div(denominator);
};
export const getAmountIn = (
amountOut: BigNumberish,
reserveIn: BigNumberish,
reserveOut: BigNumberish,
feeRatio?: FeeRatio
): BigNumber => {
const _feeNumerator = feeRatio?.numerator || 3;
const _feeDeonminator = feeRatio?.denominator || 1000;
const _amountOut = BigNumber.from(amountOut);
const _reserveOut = BigNumber.from(reserveOut);
const numerator = _amountOut.mul(reserveIn).mul(_feeDeonminator);
const denominator = _reserveOut
.sub(amountOut)
.mul(_feeDeonminator - _feeNumerator);
return numerator.div(denominator.add(1));
};
export const decryptTransaction = (
privKey: BigNumberish,
outputA: BigNumberish,
outputB: BigNumberish,
address0: string,
address1: string,
secret: BytesLike
) => {
const privBuff = privToBuffer(privKey);
const pubKey = privToPubKey(privKey);
const decrypted = decrypt(
privBuff,
Buffer.from([]),
Buffer.from(arrayify(secret))
);
const amountA = BigNumber.from(decrypted.slice(0, 32));
const saltA = BigNumber.from(decrypted.slice(32, 48));
const amountB = BigNumber.from(decrypted.slice(48, 80));
const saltB = BigNumber.from(decrypted.slice(80, 96));
const output0a: Note = {
address: BigNumber.from(address0),
amount: amountA,
salt: saltA,
pubKey,
};
const output0b: Note = {
address: BigNumber.from(address0),
amount: amountB,
salt: saltB,
pubKey,
};
const output1a: Note = {
address: BigNumber.from(address1),
amount: amountA,
salt: saltA,
pubKey,
};
const output1b: Note = {
address: BigNumber.from(address1),
amount: amountB,
salt: saltB,
pubKey,
};
if (getNoteHash(output0a).eq(outputA)) {
assert(getNoteHash(output1b).eq(outputB));
return [output0a, output1b];
} else {
assert(getNoteHash(output0b).eq(outputB));
assert(getNoteHash(output1a).eq(outputA));
return [output0b, output1a];
}
};
|
0xBeaver/snarkswap-client
|
src/index.ts
|
import * as eddsa from './lib/eddsa';
import * as pow from './lib/pow';
import * as swap from './lib/swap';
import * as utils from './lib/utils';
export * from './lib/note';
export { eddsa, pow, swap, utils };
|
0xBeaver/snarkswap-client
|
src/lib/swap.ts
|
/* eslint-disable functional/no-let */
import assert from 'assert';
import path from 'path';
import { encrypt } from 'chacha20';
import circomlib from 'circomlib';
import { BigNumber, BigNumberish } from 'ethers';
import {
arrayify,
hexConcat,
hexZeroPad,
keccak256,
solidityPack,
} from 'ethers/lib/utils';
import { groth16 } from 'snarkjs';
import { hexToNumberString, randomHex } from 'web3-utils';
import swapVK from '../snarkfiles/swap.vk.json';
import { getNoteHash, Note } from './note';
import { hideReserve } from './pow';
import {
FeeRatio,
getAmountIn,
getAmountOut,
privToBuffer,
privToPubKey,
Proof,
snarkjsProofToContractArg,
} from './utils';
export enum SwapType {
Token0In = '0In',
Token0Out = '0Out',
Token1In = '1In',
Token1Out = '1Out',
}
const Zero = BigNumber.from(0);
export const hideSwap = async (
privKey: BigNumberish,
reserve0: BigNumberish,
reserve1: BigNumberish,
sourceA: Note,
sourceB: Note,
address0: BigNumberish,
address1: BigNumberish,
amount: BigNumberish,
swapType: SwapType,
fee: FeeRatio,
difficulty: number
): Promise<{
readonly commitment: string;
readonly hReserve0: BigNumber;
readonly hReserve1: BigNumber;
readonly hRatio: BigNumber;
readonly mask: BigNumber;
readonly salt: BigNumber;
readonly outputA: Note;
readonly outputB: Note;
readonly darkness: string;
readonly encryptedOutputs: Buffer;
readonly proof: Proof;
}> => {
const pubKey = privToPubKey(privKey);
assert(difficulty <= 30, 'MAX difficulty is 30');
assert(BigNumber.from(sourceA.pubKey[0]).eq(pubKey[0]), 'no ownership');
assert(BigNumber.from(sourceA.pubKey[1]).eq(pubKey[1]), 'no ownership');
assert(BigNumber.from(sourceB.pubKey[0]).eq(pubKey[0]), 'no ownership');
assert(BigNumber.from(sourceB.pubKey[1]).eq(pubKey[1]), 'no ownership');
assert(
BigNumber.from(sourceA.address).eq(address0) ||
BigNumber.from(sourceA.address).eq(address1),
'Invalid asset in Source A'
);
assert(
BigNumber.from(sourceB.address).eq(address0) ||
BigNumber.from(sourceB.address).eq(address1),
'Invalid asset in Source B'
);
let amount0In: BigNumber;
let amount0Out: BigNumber;
let amount1In: BigNumber;
let amount1Out: BigNumber;
const _amount = BigNumber.from(amount);
const _reserve0 = BigNumber.from(reserve0);
const _reserve1 = BigNumber.from(reserve1);
switch (swapType) {
case SwapType.Token0In:
amount0In = _amount;
amount0Out = Zero;
amount1In = Zero;
amount1Out = getAmountOut(amount, reserve0, reserve1);
break;
case SwapType.Token0Out:
amount0In = Zero;
amount0Out = _amount;
amount1In = getAmountIn(amount, reserve1, reserve0);
amount1Out = Zero;
break;
case SwapType.Token1In:
amount0In = Zero;
amount0Out = getAmountOut(amount, reserve1, reserve0);
amount1In = _amount;
amount1Out = Zero;
break;
case SwapType.Token1Out:
amount0In = getAmountIn(amount, reserve0, reserve1);
amount0Out = Zero;
amount1In = Zero;
amount1Out = _amount;
break;
}
const input0 = [sourceA, sourceB]
.filter((note) => note.address === address0)
.reduce((acc, note) => acc.add(note.amount), Zero);
const input1 = [sourceA, sourceB]
.filter((note) => note.address === address1)
.reduce((acc, note) => acc.add(note.amount), Zero);
const newBal0 = input0.add(amount0Out).sub(amount0In);
const newBal1 = input1.add(amount1Out).sub(amount1In);
const output0: Note = {
address: address0,
amount: newBal0,
pubKey,
salt: BigNumber.from(hexToNumberString(randomHex(16))),
};
const output1: Note = {
address: address1,
amount: newBal1,
pubKey,
salt: BigNumber.from(hexToNumberString(randomHex(16))),
};
const rand = Math.random();
const outputA = rand < 0.5 ? output0 : output1;
const outputB = rand < 0.5 ? output1 : output0;
const sourceAHash = getNoteHash(sourceA);
const sourceBHash = getNoteHash(sourceB);
const outputAHash = getNoteHash(outputA);
const outputBHash = getNoteHash(outputB);
const secret = Buffer.from(
arrayify(
hexConcat([
hexZeroPad(BigNumber.from(outputA.amount).toHexString(), 32),
hexZeroPad(BigNumber.from(outputA.salt).toHexString(), 16),
hexZeroPad(BigNumber.from(outputB.amount).toHexString(), 32),
hexZeroPad(BigNumber.from(outputB.salt).toHexString(), 16),
])
)
);
const encryptedOutputs = encrypt(
privToBuffer(privKey),
Buffer.from([]),
secret
);
const newReserve0 = _reserve0.add(amount0In).sub(amount0Out);
const newReserve1 = _reserve1.add(amount1In).sub(amount1Out);
const {
darkness: commitment,
hReserve0,
hReserve1,
mask,
salt,
hRatio,
} = hideReserve(newReserve0, newReserve1, difficulty);
const txHash = circomlib.poseidon([
BigInt(sourceAHash),
BigInt(sourceBHash),
BigInt(outputAHash),
BigInt(outputBHash),
BigInt(salt),
]);
const signature = circomlib.eddsa.signPoseidon(privToBuffer(privKey), txHash);
const noteAmountIn0 = [sourceA, sourceB].reduce(
(acc, note) => acc.add(note.address === address0 ? note.amount : Zero),
Zero
);
const noteAmountIn1 = [sourceA, sourceB].reduce(
(acc, note) => acc.add(note.address === address1 ? note.amount : Zero),
Zero
);
const noteAmountOut0 = [outputA, outputB].reduce(
(acc, note) => acc.add(note.address === address0 ? note.amount : Zero),
Zero
);
const noteAmountOut1 = [outputA, outputB].reduce(
(acc, note) => acc.add(note.address === address1 ? note.amount : Zero),
Zero
);
assert(
newReserve0.add(noteAmountOut0).eq(_reserve0.add(noteAmountIn0)),
'money printed'
);
assert(
newReserve1.add(noteAmountOut1).eq(_reserve1.add(noteAmountIn1)),
'money printed'
);
const result = await groth16.fullProve(
{
sourceA: BigInt(sourceAHash),
sourceB: BigInt(sourceBHash),
reserve0: BigInt(reserve0),
reserve1: BigInt(reserve1),
mask: BigInt(mask),
hRatio: BigInt(hRatio),
hReserve0: BigInt(hReserve0),
hReserve1: BigInt(hReserve1),
ratioSalt: BigInt(salt),
outputA: BigInt(outputAHash),
outputB: BigInt(outputBHash),
address0: BigInt(address0),
address1: BigInt(address1),
feeNumerator: BigInt(fee.numerator),
feeDenominator: BigInt(fee.denominator),
sourceADetails: [
sourceA.address,
sourceA.amount,
sourceA.pubKey[0],
sourceA.pubKey[1],
sourceA.salt,
].map((bn) => BigInt(bn)),
sourceBDetails: [
sourceB.address,
sourceB.amount,
sourceB.pubKey[0],
sourceB.pubKey[1],
sourceB.salt,
].map((bn) => BigInt(bn)),
outputADetails: [
outputA.address,
outputA.amount,
outputA.pubKey[0],
outputA.pubKey[1],
outputA.salt,
].map((bn) => BigInt(bn)),
outputBDetails: [
outputB.address,
outputB.amount,
outputB.pubKey[0],
outputB.pubKey[1],
outputB.salt,
].map((bn) => BigInt(bn)),
newReserve0: BigInt(newReserve0),
newReserve1: BigInt(newReserve1),
pubkey: pubKey.map((bn) => BigInt(bn)),
sigR8: signature.R8,
sigS: signature.S,
},
`${path.join(__dirname, '../snarkfiles/swap.wasm')}`,
`${path.join(__dirname, '../snarkfiles/swap.zkey')}`
);
const verifyResult = await groth16.verify(
swapVK,
result.publicSignals,
result.proof
);
assert(verifyResult, 'generated false proof');
const darkness = keccak256(
solidityPack(
['uint256', 'uint112', 'uint112', 'uint224'],
[hRatio, hReserve0, hReserve1, mask]
)
);
return {
commitment,
hReserve0,
hReserve1,
hRatio,
mask,
salt,
encryptedOutputs,
outputA,
outputB,
darkness,
proof: snarkjsProofToContractArg(result.proof),
};
};
|
0xBeaver/snarkswap-client
|
src/lib/pow.ts
|
<filename>src/lib/pow.ts
/* eslint-disable functional/no-throw-statement */
/* eslint-disable functional/no-loop-statement */
/* eslint-disable functional/no-let */
import circomlib from 'circomlib';
import { BigNumber, BigNumberish } from 'ethers';
import {
hexZeroPad,
keccak256,
randomBytes,
solidityPack,
} from 'ethers/lib/utils';
const RIGHT_112_BITS = (1n << 112n) - 1n;
export const solve = async (
darkness: string,
hReserve0: BigNumberish,
hReserve1: BigNumberish,
mask: BigNumberish,
salt: BigNumberish
): Promise<{
readonly reserve0: BigNumber;
readonly reserve1: BigNumber;
readonly n: number;
}> => {
const _hReserve0 = BigInt(BigNumber.from(hReserve0));
const _hReserve1 = BigInt(BigNumber.from(hReserve1));
const _mask = BigInt(BigNumber.from(mask));
const _salt = BigInt(BigNumber.from(salt));
const maskHex = hexZeroPad(BigNumber.from(mask).toHexString(), 28);
return new Promise((resolve) => {
// concatenated
const concatHReserve = (_hReserve0 << 112n) | _hReserve1;
const unknownBits = [...Array(224).keys()]
.filter((i) => (_mask & (1n << BigInt(i))) !== 0n)
.map((i) => BigInt(i))
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.sort((_a, _b) => {
return 0.5 - Math.random();
});
const numOfCases = 1 << unknownBits.length;
let hRatio: BigNumber;
for (let i = 0; i < numOfCases; i += 1) {
let flipper = 0n;
for (let j = 0; j < unknownBits.length; j += 1) {
flipper |= (i & (1 << j)) === 0 ? 0n : 1n << unknownBits[j];
}
const guessedReserve = concatHReserve ^ flipper;
const reserve0 = guessedReserve >> 112n;
const reserve1 = guessedReserve & RIGHT_112_BITS;
hRatio = BigNumber.from(circomlib.poseidon([reserve0, reserve1, _salt]));
const computedDarkness = keccak256(
solidityPack(
['uint256', 'uint112', 'uint112', 'uint224'],
[hRatio, hReserve0, hReserve1, maskHex]
)
);
if (BigNumber.from(darkness).eq(computedDarkness)) {
resolve({
reserve0: BigNumber.from(reserve0),
reserve1: BigNumber.from(reserve1),
n: i,
});
}
}
throw Error('Failed to solve the PoW puzzle. Verify SNARK');
});
};
export const hideReserve = (
reserve0: BigNumberish,
reserve1: BigNumberish,
difficulty: number
): {
readonly darkness: string;
readonly hReserve0: BigNumber;
readonly hReserve1: BigNumber;
readonly mask: BigNumber;
readonly salt: BigNumber;
readonly hRatio: BigNumber;
} => {
if (difficulty > 30) throw Error('Difficulty is too large');
const _reserve0 = BigInt(BigNumber.from(reserve0));
const _reserve1 = BigInt(BigNumber.from(reserve1));
const mask = getBestMask(difficulty, reserve0, reserve1);
// reserve0FirstBit
// reserve1FirstBit
let concatReserve = (_reserve0 << 112n) | _reserve1;
for (let i = 0n; i < 224n; i += 1n) {
if (((1n << i) & BigInt(mask)) !== 0n) {
concatReserve |= Math.random() < 0.5 ? 1n << i : 0n;
}
}
const hReserve0 = BigNumber.from(concatReserve >> 112n);
const hReserve1 = BigNumber.from(concatReserve & RIGHT_112_BITS);
const salt = BigNumber.from(randomBytes(16));
const hRatio = BigNumber.from(
circomlib.poseidon([_reserve0, _reserve1, BigInt(salt)])
);
const darkness = keccak256(
solidityPack(
['uint256', 'uint112', 'uint112', 'uint224'],
[hRatio, hReserve0, hReserve1, mask]
)
);
return {
darkness,
hReserve0,
hReserve1,
mask,
salt,
hRatio,
};
};
export const getDifficulty = (mask: BigNumberish): number => {
return BigInt(BigNumber.from(mask)).toString(2).replace(/0/g, '').length;
};
export const getBestMask = (
difficulty: number,
reserve0: BigNumberish,
reserve1: BigNumberish
): BigNumber => {
if (difficulty === 0) return BigNumber.from(0);
const reserve0FirstBit = BigInt(BigNumber.from(reserve0)).toString(2).length;
const reserve1FirstBit = BigInt(BigNumber.from(reserve1)).toString(2).length;
const difficulty0 = Math.floor(difficulty / 2);
const difficulty1 = difficulty - difficulty0;
let mask0Shift = reserve0FirstBit - difficulty0 + 1;
mask0Shift = mask0Shift > 0 ? mask0Shift : 0;
const mask0 =
((1n << 112n) - 1n) &
(BigInt(parseInt(new Array(difficulty0).fill('1').join(''), 2)) <<
BigInt(mask0Shift));
let mask1Shift = reserve1FirstBit - difficulty1 + 1;
mask1Shift = mask1Shift > 0 ? mask1Shift : 0;
const mask1 =
((1n << 112n) - 1n) &
(BigInt(parseInt(new Array(difficulty1).fill('1').join(''), 2)) <<
BigInt(mask1Shift));
const mask = BigNumber.from((mask0 << 112n) | mask1);
if (getDifficulty(mask) > difficulty) throw Error('difficulty error');
return mask;
};
|
0xBeaver/snarkswap-client
|
src/types/circomlib.spec.ts
|
<gh_stars>1-10
import test from 'ava';
import circomlib from 'circomlib';
test('poseidon', (t) => {
t.is(
circomlib.poseidon([1234n, 4321n]),
12384503409460211275296730302116273884825946305305235951279779955197099791503n
);
t.not(
circomlib.poseidon([1234n, 4321n]),
12384503409460211275296730302116273884825946305305235951279779955197099791500n
);
});
test('eddsa', (t) => {
const password = 'password';
const pubKey = circomlib.eddsa.prv2pub(password);
const message = 1234n;
const signature = circomlib.eddsa.signPoseidon(password, message);
t.is(circomlib.eddsa.verifyPoseidon(message, signature, pubKey), true);
t.is(circomlib.eddsa.verifyPoseidon(message + 1n, signature, pubKey), false);
});
|
0xBeaver/snarkswap-client
|
src/types/snarkjs.d.ts
|
/**
* If you import a dependency which does not include its own type definitions,
* TypeScript will try to find a definition for it by following the `typeRoots`
* compiler option in tsconfig.json. For this project, we've configured it to
* fall back to this folder if nothing is found in node_modules/@types.
*
* Often, you can install the DefinitelyTyped
* (https://github.com/DefinitelyTyped/DefinitelyTyped) type definition for the
* dependency in question. However, if no one has yet contributed definitions
* for the package, you may want to declare your own. (If you're using the
* `noImplicitAny` compiler options, you'll be required to declare it.)
*
* This is an example type definition which allows import from `module-name`,
* e.g.:
* ```ts
* import something from 'module-name';
* something();
* ```
*/
declare module 'snarkjs' {
type SnarkjsProof = {
readonly pi_a: readonly (string | bigint)[];
readonly pi_b: readonly (readonly (string | bigint)[])[];
readonly pi_c: readonly (string | bigint)[];
readonly protocol: string;
};
type PublicSignals = readonly (string | bigint)[];
type SNARK = {
readonly proof: SnarkjsProof;
readonly publicSignals: PublicSignals;
};
type VK = {
readonly nPublic: number;
readonly curve: unknown;
readonly vk_alpha_1: unknown;
readonly vk_beta_2: unknown;
readonly vk_gamma_2: unknown;
readonly vk_delta_2: unknown;
readonly IC: unknown;
};
const groth16: {
readonly fullProve: (
input: {
readonly [key: string]:
| bigint
| readonly bigint[]
| readonly (readonly bigint[])[];
},
wasmFile: string,
zkeyFileName: string,
logger?: unknown
) => Promise<SNARK>;
readonly prove: (
zkeyFileName: string,
witnessFilename: string,
logger?: unknown
) => Promise<SNARK>;
readonly verify: (
vkVerifier: VK,
publicSignals: PublicSignals,
proof: SnarkjsProof,
logger?: unknown
) => Promise<boolean>;
};
export { SnarkjsProof, VK, groth16 };
}
|
0xBeaver/snarkswap-client
|
src/lib/pow.spec.ts
|
<reponame>0xBeaver/snarkswap-client<filename>src/lib/pow.spec.ts
import test from 'ava';
import { BigNumber } from 'ethers';
import { getBestMask, getDifficulty, hideReserve, solve } from './pow';
test('getDifficulty', (t) => {
t.is(getDifficulty(parseInt('10000000', 2)), 1);
t.is(getDifficulty(parseInt('10000101', 2)), 3);
t.is(getDifficulty(parseInt('11111111', 2)), 8);
});
test('getBestMask', (t) => {
const difficulty = 11;
const reserve0 = BigNumber.from(parseInt('00000001111110000000000', 2));
const besMask0 = BigNumber.from(parseInt('00000011111000000000000', 2));
const reserve1 = BigNumber.from(parseInt('00000000011110000000000', 2));
const besMask1 = BigNumber.from(parseInt('00000000111111000000000', 2));
const bestMask = besMask0.shl(112).add(besMask1);
t.true(getBestMask(difficulty, reserve0, reserve1).eq(bestMask));
});
const reserve0 = '8971234671621374';
const reserve1 = '91234700182377911837';
test('hide difficulty test', async (t) => {
const { hReserve0, hReserve1 } = hideReserve(reserve0, reserve1, 0);
t.true(hReserve0.eq(reserve0));
t.true(hReserve1.eq(reserve1));
});
test('hide & solve - low difficulty', async (t) => {
const { darkness: commitment, hReserve0, hReserve1, mask, salt } = hideReserve(
reserve0,
reserve1,
8
);
console.time('solve');
const result = await solve(commitment, hReserve0, hReserve1, mask, salt);
console.timeEnd('solve');
t.true(result.reserve0.eq(reserve0));
t.true(result.reserve1.eq(reserve1));
t.log(`Computed hash ${result.n} times`);
});
test.skip('hide & solve - high difficulty', async (t) => {
const { darkness: commitment, hReserve0, hReserve1, mask, salt } = hideReserve(
reserve0,
reserve1,
16
);
t.false(hReserve0.eq(reserve0));
t.false(hReserve1.eq(reserve1));
console.time('solve');
const result = await solve(commitment, hReserve0, hReserve1, mask, salt);
console.timeEnd('solve');
t.true(result.reserve0.eq(reserve0));
t.true(result.reserve1.eq(reserve1));
t.log(`Computed hash ${result.n} times`);
});
|
0xBeaver/snarkswap-client
|
src/lib/eddsa.spec.ts
|
import test from 'ava';
import { signEdDSA, verifyEdDSA } from './eddsa';
import { privToPubKey } from './utils';
test('signEdDSA & verifyEdDSA', async (t) => {
const msg = '1234';
const privKey =
'1020304050607080900010203040506070809000102030405060708090001';
const pubKey = privToPubKey(privKey);
const proof = await signEdDSA(msg, privKey);
const verified = await verifyEdDSA(msg, pubKey, proof);
t.is(verified, true);
});
|
0xBeaver/snarkswap-client
|
src/lib/eddsa.ts
|
import assert from 'assert';
import path from 'path';
import { eddsa } from 'circomlib';
import { BigNumber, BigNumberish } from 'ethers';
import { keccak256, solidityPack } from 'ethers/lib/utils';
import { groth16 } from 'snarkjs';
import eddsaVK from '../snarkfiles/eddsa.vk.json';
import {
PRIME_Q,
privToBuffer,
privToPubKey,
Proof,
proofToSnarkjsProof,
snarkjsProofToContractArg,
} from './utils';
export const signWithdrawal = async (
noteHash: BigNumberish,
to: BigNumberish,
privKey: BigNumberish
): Promise<Proof> => {
const msg = BigNumber.from(
keccak256(solidityPack(['uint256', 'address'], [noteHash, to]))
).mod(BigNumber.from(PRIME_Q));
const proof = await signEdDSA(msg, privKey);
return proof;
};
export const signEdDSA = async (
message: BigNumberish,
privKey: BigNumberish
): Promise<Proof> => {
const privKeyBuff = privToBuffer(privKey);
const pubKey = privToPubKey(privKey);
const signature = eddsa.signPoseidon(
privKeyBuff,
BigInt(BigNumber.from(message))
);
const result = await groth16.fullProve(
{
note: BigInt(BigNumber.from(message)),
pubKey: pubKey.map((bn) => BigInt(BigNumber.from(bn))),
R8x: signature.R8[0],
R8y: signature.R8[1],
s: signature.S,
},
`${path.join(__dirname, '../snarkfiles/eddsa.wasm')}`,
`${path.join(__dirname, '../snarkfiles/eddsa.zkey')}`
);
const verifyResult = await groth16.verify(
eddsaVK,
result.publicSignals,
result.proof
);
assert(verifyResult, 'generated false proof');
const proof = snarkjsProofToContractArg(result.proof);
return proof;
};
export const verifyEdDSA = async (
message: BigNumberish,
pubKey: readonly BigNumberish[],
proof: Proof
): Promise<boolean> => {
const publicSignals = [message, pubKey[0], pubKey[1]].map((bn) =>
BigInt(BigNumber.from(bn))
);
const result = await groth16.verify(
eddsaVK,
publicSignals,
proofToSnarkjsProof(proof)
);
return result;
};
|
Maxar96/Progetto
|
src/index.ts
|
import * as firebase from 'firebase/app';
import 'firebase/database';
import { MDCRipple } from '@material/ripple/index';
import { MDCTextField } from '@material/textfield';
import { MDCSelect } from '@material/select';
import { Chart } from 'chart.js';
import { MDCTopAppBar } from '@material/top-app-bar';
import {MDCList} from "@material/list";
const testo = document.getElementById('page-0') as HTMLElement;
const grafico = document.getElementById('page-1') as HTMLElement;
grafico.hidden = true;
const list = MDCList.attachTo(document.querySelector('.mdc-list')!);
list.wrapFocus = true;
let menuItemSelected = 0;
list.listen('click', () => {
const selectedNow = list.selectedIndex as number;
if (menuItemSelected == selectedNow) {
return;
}
if (selectedNow == 0) {
testo.hidden = false;
grafico.hidden = true;
} else {
testo.hidden = true;
grafico.hidden = false;
}
menuItemSelected = selectedNow;
})
const topAppBarElement = document.querySelector('.mdc-top-app-bar');
const topAppBar = new MDCTopAppBar(topAppBarElement!);
const getColor = () => Math.round(Math.random() * 255);
const createMenuEntry = (giorno: string) => `<li class="mdc-list-item" data-value="${giorno}"> ${giorno} </li>`.trimLeft();
let curriedPopulate: Function;
const populateChartCurried = (values: firebase.database.DataSnapshot) => (giorno: string) => populateChart(values.child(giorno));
const ctx = (document.getElementById('myChart') as HTMLCanvasElement).getContext('2d') as CanvasRenderingContext2D;
let chart: Chart;
// const multiply = (x: number) => (y: number) => x * y;
// console.log(multiply(2)(3));
// const multiplyBy2 = multiply(2);
// console.log(multiplyBy2(10), multiplyBy2(20))
const buttonRipple = new MDCRipple(document.querySelector('.mdc-button') as HTMLElement);
const username = new MDCTextField(document.querySelector('.username') as HTMLElement);
const select = new MDCSelect(document.querySelector('.mdc-select') as HTMLElement);
const dropDownDiv = document.getElementById('dropdown-menu') as HTMLElement;
let oldSelectValue: string;
select.listen('MDCSelect:change', () => {
console.log(`Selected option at index ${select.selectedIndex} with value "${select.value}"`);
if (!select.value) return;
if (select.value === oldSelectValue) return;
if (chart) chart.destroy();
oldSelectValue = select.value;
curriedPopulate(select.value);
});
function populateDropdown(values: firebase.database.DataSnapshot) {
let giorni: string[] = [];
values.forEach(elem => {
giorni.push(elem.key as string);
});
select.disabled = false;
dropDownDiv.innerHTML = `
<li class="mdc-list-item mdc-list-item--selected" data-value="" aria-selected="true"></li>
${giorni.map(createMenuEntry).join('')}
`;
curriedPopulate = populateChartCurried(values);
}
function populateChart(giorno: firebase.database.DataSnapshot) {
let serieKeys: string[] = [];
let data: number[][] = [];
giorno.forEach(serie => {
let serieData: number[] = [];
serieKeys.push(serie.key as string);
serie.forEach(elem => {
serieData.push(elem.val().valore);
});
data.push(serieData);
});
const maxArrLength = Math.max(...data.map(elem => elem.length));
const longestSerie = data.filter(elem => elem.length === maxArrLength)[0];
const labels = longestSerie.map((_, i) => i);
const datasets = data.map((data, i) => {
const color = `rgb(${getColor()}, ${getColor()}, ${getColor()})`; //"rgb(255, 99, 132)"
return {
label: `Serie ${i + 1}`,
backgroundColor: color,
borderColor: color,
data,
fill: false
};
});
chart = new Chart(ctx, {
type: 'line',
data: {
labels,
datasets
},
options: {}
});
}
(() => {
const firebaseConfig = {
apiKey: 'apikey',
authDomain: 'domain',
databaseURL: 'url'
projectId: 'projectid',
storageBucket: '',
messagingSenderId: '',
appId: '',
measurementId: ''
};
// Initialize Firebase
!firebase.apps.length ? firebase.initializeApp(firebaseConfig) : firebase.app();
const database = firebase.database();
username.value = 'Barberto';
buttonRipple.listen('click', async () => {
if (username.value.length <= 0) return;
if (chart) chart.destroy();
select.selectedIndex = 0;
oldSelectValue = '';
const values = await database.ref(`/${username.value}`).once('value');
if (values.hasChildren()) populateDropdown(values);
else alert('no');
});
})();
|
ii02735/nestjs-training
|
src/tasks/dto/create-task.dto.ts
|
/**
* DTO is a pattern to represent object structure
* or the shape of an object that will carry data
* when it will be retrieved / sent from controller
*
* TLDR : it replaces the hard-written parameters
* of the object that has to be created
* by a concrete object -> that give a better maintenance
*
* Indeed, if the Task structure has to be changed,
* instead of modify all of controller's functions,
* it will be enough to modify the dto --> speed up the maintenance
*/
export class CreateTaskDto {
title: string;
description: string;
}
//We using a class and no an interface
/**
* Because interfaces are pure TS and not JS
* Ergo, when the application will be compilated,
* interfaces won't be understood when they will
* be attached to controllers paramaters
*/
|
ii02735/nestjs-training
|
src/tasks/tasks.service.ts
|
<reponame>ii02735/nestjs-training
import { Injectable } from '@nestjs/common';
import { Task, TaskStatus } from './task.model';
import { v1 as uuid } from "uuid";
import { CreateTaskDto } from './dto/create-task.dto';
/**
* A service is a class that must have
* the BUSINESS LOGIC
* Because in Controller, we must not
* write a lot of code
* Controllers are firstly destined to retrive and
* send http requests.
*/
@Injectable()
export class TasksService {
private tasks: Task[] = [];
getAllTasks()
{
//Make array immutable (very important) by returning a copy
return this.tasks.slice();
}
createTask(createTaskDto:CreateTaskDto): Task {
const {title,description} = createTaskDto;
const task: Task = {
id: uuid(),
title,
description,
status: TaskStatus.OPEN
}
this.tasks.push(task)
return task;
}
getTaskById(id: string): Task
{
return this.tasks.find(task => task.id === id);
}
deleteTask(id: string): void
{
this.tasks = this.tasks.filter(task => task.id !== id);
}
}
|
ii02735/nestjs-training
|
src/tasks/tasks.controller.ts
|
import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common';
import { create } from 'domain';
import { CreateTaskDto } from './dto/create-task.dto';
import { Task } from './task.model';
import { TasksService } from './tasks.service';
@Controller('tasks')
export class TasksController {
/**
* Because we precised the TaskService type,
* an instance of TaskService will be injected
* for two reasons :
* 1) TaskService class has the Injectable decorator
* 2) TaskService belongs to the TaskController's module
*/
constructor(private tasksService: TasksService){}
@Get() /** By default "/" route */
getAllTasks()
{
return this.tasksService.getAllTasks();
}
@Post("/test") /**Decorate body object in order to tell that it is the request's body, it's also possible to designate the key to retrieve directly the value*/
testPost(@Body("description") description: string)
{
console.log('body',description)
}
@Post() //Replacing paramaters by their Dto (describer object that will receive the parameters)
createTask(@Body() createTaskDto:CreateTaskDto): Task
{
return this.tasksService.createTask(createTaskDto)
}
@Get('/:id')
getTaskById(@Param("id") id: string): Task
{
return this.tasksService.getTaskById(id)
}
@Delete("/:id")
deleteTask(@Param("id") id: string)
{
this.tasksService.deleteTask(id);
return { "message": `Task ${id} deleted successfully !` }
}
}
|
GrafGenerator/translation-selector
|
src/GrafGenerator.TranslationSelector.UI/app/components/Greeter.ts
|
<reponame>GrafGenerator/translation-selector
"use strict";
export class Greeter {
constructor(public name: string) {
}
}
|
GrafGenerator/translation-selector
|
src/GrafGenerator.TranslationSelector.UI/app/app.ts
|
<reponame>GrafGenerator/translation-selector
import { Greeter } from './components/Greeter';
export function run() {
window.onload = () => {
var greeter = new Greeter("Nikita");
document.body.innerHTML = greeter.name;
alert(greeter.name);
};
};
|
GrafGenerator/translation-selector
|
src/GrafGenerator.TranslationSelector.UI/app/custom_typings/main.d.ts
|
/// <reference path="main/definitions/jquery/index.d.ts" />
|
GrafGenerator/translation-selector
|
src/GrafGenerator.TranslationSelector.UI/app/index.ts
|
/// <reference path="typings/main.d.ts" />
/// <reference path="custom_typings/main.d.ts" />
import jQuery = require("jquery");
window["jQuery"] = window["$"] = jQuery;
import Bootstrap = require("bootstrap");
[Bootstrap];
import app = require("./app");
app.run();
|
GrafGenerator/translation-selector
|
src/GrafGenerator.TranslationSelector.UI/app/custom_typings/browser.d.ts
|
/// <reference path="browser/definitions/jquery/index.d.ts" />
|
piotrrussw/snake-multiplayer
|
client/sketch/P5Object.ts
|
interface P5Object {
x: number,
y: number,
readonly scale: number,
draw(p5: p5): any,
setup(p5: p5): any
}
|
piotrrussw/snake-multiplayer
|
client/sketch/Opponent.ts
|
///<reference path="Snake.ts"/>
class Opponent extends Snake {
}
|
piotrrussw/snake-multiplayer
|
client/sketch/Sketch.ts
|
<reponame>piotrrussw/snake-multiplayer<gh_stars>0
const sketch = (p: p5) => {
let socket: any;
const gameScale = 20;
let player: Player;
let opponents: any = {};
let food: Food;
p.preload = () => {
};
p.setup = () => {
const canvas = p.createCanvas(800, 500);
// canvas.parent('sketch');
p.frameRate(10);
// @ts-ignore
socket = io();
// socket = io(`http://localhost:${process.env.PORT || 3000}`);
player = new Player(gameScale);
food = new Food(gameScale);
socket.on('message', (data: any, foodData: any, highScore: number) => {
console.log(data, foodData);
Object.keys(data).forEach((id: string) => {
if (Object.keys(data[id]).length) {
opponents[id] = new Snake(gameScale);
opponents[id].update(data[id]);
} else {
opponents[id] = new Snake(gameScale);
}
});
if (!Object.keys(opponents).length) {
food.setup(p);
socket.emit('food', food.getData());
} else {
food.update(p, foodData);
}
player.setScore(highScore);
player.mountHighScore();
});
socket.on('disconnect', (id: string) => {
opponents.hasOwnProperty(id)
? delete opponents[id]
: null;
});
socket.on('newConnection', (id: string) => {
opponents[id] = new Snake(gameScale);
});
socket.on('move', (data: any, id: string) => {
console.log('on move', data);
opponents[id].update(data);
});
socket.on('food', (data: any) => {
return food.update(p, data);
});
socket.on('highScore', (score: number) => {
player.setScore(score);
});
};
p.windowResized = () => {
p.resizeCanvas(800, 500);
};
p.draw = () => {
p.background('#fff');
player.setup(p);
player.draw(p);
Object.keys(opponents).forEach((id: string) => {
// noinspection TypeScriptValidateJSTypes
opponents[id].setup(p);
// noinspection TypeScriptValidateJSTypes
opponents[id].draw(p);
});
food.draw(p);
if (player.eat(food, p)) {
food.setup(p);
food.draw(p);
socket.emit('highScore', player.getScore());
socket.emit('food', food.getData());
}
socket.emit('move', player.getData());
};
p.keyPressed = () => {
player.move(p.keyCode);
};
};
// noinspection JSPotentiallyInvalidConstructorUsage
new p5(sketch);
|
piotrrussw/snake-multiplayer
|
client/sketch/Snake.ts
|
class Snake implements P5Object {
x: number;
y: number;
highScore: number = 0;
readonly scale: number;
protected xSpeed: number;
protected ySpeed: number;
protected total: number = 0;
protected tail: Array<any> = [];
constructor(args: any) {
if (typeof args === 'number') {
this.scale = args;
this.x = 0;
this.y = 0;
this.xSpeed = 1;
this.ySpeed = 0;
} else {
this.x = args.x;
this.y = args.y;
this.xSpeed = args.xSpeed;
this.ySpeed = args.ySpeed;
this.total = args.total;
this.tail = args.tail;
this.scale = args.scale;
this.highScore = args.highScore;
}
}
setup(p5: p5) {
this.death(p5);
if (this.total === this.tail.length) {
this.tail.shift();
}
this.tail[this.total - 1] = {x: this.x, y: this.y};
this.x += this.xSpeed * this.scale;
this.y += this.ySpeed * this.scale;
this.x = p5.constrain(this.x, 0, p5.width - this.scale);
this.y = p5.constrain(this.y, 0, p5.height - this.scale);
}
draw(p5: p5) {
p5.fill('#969696');
this.tail.forEach(({x, y}) => p5.rect(x, y, this.scale, this.scale));
p5.rect(this.x, this.y, this.scale, this.scale);
}
update(args: any) {
this.x = args.x;
this.y = args.y;
this.xSpeed = args.xSpeed;
this.ySpeed = args.ySpeed;
this.tail = args.tail;
this.total = args.total;
this.highScore = args.highScore;
}
private death(p5: p5) {
if (this.tail.some(({x, y}) => p5.dist(this.x, this.y, x, y) < 1)) {
this.total = 0;
this.tail = [];
}
}
}
|
piotrrussw/snake-multiplayer
|
client/sketch/Player.ts
|
///<reference path="Snake.ts"/>
class Player extends Snake {
/**
* @param curr - current (x, y) direction
* @param next - next (x, y) direction
*/
private _moved: boolean = false;
private isMovingBackward = (curr: Array<number>, next: Array<number>): boolean => curr[0] === (next[0] * -1) || curr[1] === (next[1] * -1);
eat(food: Food, p5: p5) {
if (p5.dist(this.x, this.y, food.x, food.y) < 1) {
this.total++;
this.mountTotal();
if (this.highScore < this.total) {
this.highScore = this.total;
this.mountHighScore();
}
return true;
}
return false;
}
draw(p5: p5) {
super.draw(p5);
p5.fill('#fff');
this.tail.forEach(({x, y}) => p5.rect(x, y, this.scale, this.scale));
p5.rect(this.x, this.y, this.scale, this.scale);
}
move(key: number) {
switch (key) {
case Direction.LEFT:
!this.isMovingBackward([this.xSpeed, this.ySpeed], [-1, 0])
? this.direction(-1, 0)
: null;
break;
case Direction.UP:
!this.isMovingBackward([this.xSpeed, this.ySpeed], [0, -1])
? this.direction(0, -1)
: null;
break;
case Direction.RIGHT:
!this.isMovingBackward([this.xSpeed, this.ySpeed], [1, 0])
? this.direction(1, 0)
: null;
break;
case Direction.DOWN:
!this.isMovingBackward([this.xSpeed, this.ySpeed], [0, 1])
? this.direction(0, 1)
: null;
break;
}
}
getData(): any {
return {
x: this.x,
y: this.y,
xSpeed: this.xSpeed,
ySpeed: this.ySpeed,
tail: this.tail,
total: this.total,
highScore: this.highScore
}
}
getScore() {
return this.total;
}
setScore(score: number) {
this.highScore = score;
this.mountHighScore();
}
private direction(x: number, y: number) {
this._moved = true;
this.xSpeed = x;
this.ySpeed = y;
}
mountTotal() {
document.getElementById('player-score').innerText = this.total.toString();
}
mountHighScore() {
document.getElementById('high-score').innerText = this.highScore.toString();
}
get moved(): boolean {
return this._moved;
}
set moved(value: boolean) {
this._moved = value;
}
}
|
piotrrussw/snake-multiplayer
|
client/sketch/Direction.ts
|
enum Direction {
LEFT = 37,
UP = 38,
RIGHT = 39,
DOWN = 40,
}
|
piotrrussw/snake-multiplayer
|
src/server.ts
|
import * as express from "express";
import * as socket from "socket.io";
import * as path from "path";
const app = express();
app.set("port", process.env.PORT || 3000);
app.use("/public", express.static(path.join(__dirname + "/public")));
app.get("/", (req: any, res: any) => {
res.sendFile(path.resolve("public/index.html"));
});
const server = app.listen(process.env.PORT || 3000, function() {
console.log(`listening on *:${process.env.PORT || 3000}`);
});
const io = socket(server);
let clients: any = {};
let food: any = null;
let highScore: number = 0;
io.sockets.on("connection", (client: any) => {
console.log("user connected - ", client.id, clients);
client.send(clients, food, highScore);
clients[client.id] = {};
client.on('disconnect', () => {
delete clients[client.id];
io.sockets.emit('disconnect', client.id);
});
client.broadcast.emit('newConnection', client.id);
client.on('move', (data: any) => {
clients[client.id] = data;
client.broadcast.emit('move', data, client.id);
});
client.on('food', (data: any) => {
food = data;
client.broadcast.emit('food', data);
});
client.on('highScore', (score: number) => {
if (score > highScore) {
highScore = score;
client.broadcast.emit('highScore', highScore);
}
});
});
|
piotrrussw/snake-multiplayer
|
client/sketch/Food.ts
|
<reponame>piotrrussw/snake-multiplayer
class Food implements P5Object {
x: number;
y: number;
readonly scale: number;
constructor(scale: number) {
this.scale = scale;
}
setup(p5: p5) {
const cols = p5.floor(p5.width / this.scale);
const rows = p5.floor(p5.height / this.scale);
let vector = p5.createVector(p5.floor(p5.random(cols)), p5.floor(p5.random(rows)));
vector.mult(this.scale);
this.x = vector.x;
this.y = vector.y;
}
draw(p5: p5) {
p5.fill('#F43706');
p5.rect(this.x, this.y, this.scale, this.scale);
}
update(p5: p5, data: any) {
this.x = data.x;
this.y = data.y;
}
getData() {
return {
x: this.x,
y: this.y,
scale: this.scale
}
}
}
|
iamkarimi/blog-nestjs
|
src/app.controller.ts
|
<filename>src/app.controller.ts<gh_stars>0
import {
Body,
Controller,
DefaultValuePipe,
Get,
Param,
ParseIntPipe,
ParseUUIDPipe,
Post,
Query,
UseGuards,
ValidationPipe,
} from '@nestjs/common';
import { GetAuthUser } from './auth/decorators/get-auth-user.decorator';
import { User } from './users/entities/user.entity';
import { CreateCommentDto } from './comments/dto/create-comment.dto';
import { AuthGuard } from '@nestjs/passport';
import { AppService } from './app.service';
@Controller('app')
export class AppController {
constructor(private readonly appService: AppService) {}
@Post('articles/:id')
getOneArticle(@Param('id', ParseUUIDPipe) id: string) {
return this.appService.getOneArticle(id);
}
@Get('articles')
getAllArticles(
@Query('page', new DefaultValuePipe(1), ParseIntPipe) page = 1,
@Query('limit', new DefaultValuePipe(10), ParseIntPipe) limit = 10,
) {
limit = limit > 100 ? 100 : limit;
return this.appService.getAllArticles({ page, limit });
}
@Get('simple-search/articles')
simpleSearchArticle(@Query('search') search: string) {
return this.appService.simpleSearchArticle(search);
}
@Get('categories')
getAllGategories() {
return this.appService.getAllCategories();
}
@Post('articles/:id/newcomment')
@UseGuards(AuthGuard('jwt'))
submitComment(
@Query('parentId') parentId: string,
@Param('id', ParseUUIDPipe) id: string,
@GetAuthUser() user: User,
@Body(ValidationPipe) createCommentDto: CreateCommentDto,
) {
console.log(parentId);
return this.appService.submitComment(id, parentId, user, createCommentDto);
}
}
|
iamkarimi/blog-nestjs
|
src/app.service.ts
|
<reponame>iamkarimi/blog-nestjs
import {
Injectable,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { isUUID } from 'class-validator';
import {
IPaginationOptions,
paginate,
Pagination,
} from 'nestjs-typeorm-paginate';
import { Repository } from 'typeorm';
import { Article } from './articles/entities/article.entity';
import { CreateCommentDto } from './comments/dto/create-comment.dto';
import { Comment } from './comments/entities/comment.entity';
import { User } from './users/entities/user.entity';
import { Category } from './categories/entities/category.entity';
@Injectable()
export class AppService {
constructor(
@InjectRepository(Article)
private readonly articleRepository: Repository<Article>,
@InjectRepository(Comment)
private readonly commentRepository: Repository<Comment>,
@InjectRepository(Category)
private readonly categoryRepository: Repository<Category>,
) {}
async getOneArticle(id: string) {
const article = this.articleRepository.findOne(id, {
relations: ['author', 'comments'],
});
if (!article) throw new NotFoundException();
return article;
}
async getAllArticles(
options: IPaginationOptions,
): Promise<Pagination<Article>> {
return await paginate<Article>(this.articleRepository, options, {
relations: ['author'],
});
}
async getAllCategories() {
return await this.categoryRepository.find();
}
async simpleSearchArticle(search: string) {
return await this.articleRepository
.createQueryBuilder('article')
.where('article.title like :title', { title: `%${search}%` })
.orWhere('article.slug like :slug', { slug: `%${search}%` })
.orWhere('article.abstract like :abstract', { abstract: `%${search}%` })
.orWhere('article.content like :content', { content: `%${search}%` })
.orderBy('article.createdAt', 'DESC')
.getMany();
}
async submitComment(
id: string,
parentId: string,
user: User,
createCommentDto: CreateCommentDto,
): Promise<Comment> {
let parent = null;
if (parentId && isUUID(parentId)) {
parent = await this.commentRepository.findOne({
id: parentId,
isApproved: true,
});
}
const article = await this.articleRepository.findOne(id);
if (!article) throw new NotFoundException();
const comment = new Comment();
comment.author = user;
comment.article = article;
comment.parent = parent;
const object = Object.assign(comment, createCommentDto);
try {
return await this.commentRepository.save(object);
} catch (error) {
throw new InternalServerErrorException();
}
}
}
|
iamkarimi/blog-nestjs
|
src/config/jwt.config.ts
|
<reponame>iamkarimi/blog-nestjs<filename>src/config/jwt.config.ts
import { registerAs } from '@nestjs/config';
import { JwtModuleOptions } from '@nestjs/jwt';
export default registerAs(
'jwt.config',
(): JwtModuleOptions => ({
secret: process.env.JWT_SECRET,
signOptions: {
expiresIn: Number(process.env.JWT_EXPIRESIN),
},
}),
);
|
iamkarimi/blog-nestjs
|
src/categories/entities/category.entity.ts
|
<gh_stars>0
import {
BaseEntity,
Column,
CreateDateColumn,
Entity,
OneToMany,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { Article } from '../../articles/entities/article.entity';
@Entity()
export class Category extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ nullable: false })
name: string;
@Column({ unique: true })
slug: string;
@OneToMany(() => Article, (article: Article) => article.category, {
onDelete: 'CASCADE',
})
articles: Article[];
@CreateDateColumn({
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP(6)',
})
createdAt: Date;
@UpdateDateColumn({
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP(6)',
onUpdate: 'CURRENT_TIMESTAMP(6)',
})
updatedAt: Date;
}
|
iamkarimi/blog-nestjs
|
src/roles/entities/role.entity.ts
|
import { User } from '../../users/entities/user.entity';
import {
BaseEntity,
Column,
CreateDateColumn,
Entity,
OneToMany,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
@Entity()
export class Role extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ unique: true })
name: string;
@OneToMany(() => User, (user: User) => user.role, {
onDelete: 'CASCADE',
})
users: User[];
@CreateDateColumn({
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP(6)',
})
createdAt: Date;
@UpdateDateColumn({
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP(6)',
onUpdate: 'CURRENT_TIMESTAMP(6)',
})
updatedAt: Date;
}
|
iamkarimi/blog-nestjs
|
src/users/users.controller.ts
|
<filename>src/users/users.controller.ts
import {
ParseUUIDPipe,
Post,
Body,
UseGuards,
ValidationPipe,
Controller,
Get,
Patch,
Delete,
Param,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { UsersService } from './users.service';
import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from 'src/auth/decorators/roles.decorator';
@Controller('admin/users')
@UseGuards(AuthGuard('jwt'), RolesGuard)
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Get()
@Roles('admin')
findAll() {
return this.usersService.findAll();
}
@Get(':id')
@Roles('admin')
findOne(@Param('id', ParseUUIDPipe) id: string) {
return this.usersService.findOne(id);
}
@Patch(':id')
@Roles('admin')
update(
@Param('id', ParseUUIDPipe) id: string,
@Body(ValidationPipe) updateUserDto: UpdateUserDto,
) {
return this.usersService.update(id, updateUserDto);
}
@Delete(':id')
@Roles('admin')
remove(@Param('id', ParseUUIDPipe) id: string) {
return this.usersService.remove(id);
}
}
|
iamkarimi/blog-nestjs
|
src/comments/dto/create-comment.dto.ts
|
import { IsDefined, IsString, Matches } from 'class-validator';
export class CreateCommentDto {
@IsString()
@IsDefined()
@Matches(/^(?!\s*$).+/, {
message: 'content should not be empty',
})
content: string;
}
|
iamkarimi/blog-nestjs
|
src/comments/entities/comment.entity.ts
|
import { User } from '../../users/entities/user.entity';
import { Article } from '../../articles/entities/article.entity';
import {
Entity,
BaseEntity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
TreeChildren,
TreeParent,
} from 'typeorm';
@Entity()
export class Comment extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
content: string;
@Column({ default: false })
isApproved: boolean;
@ManyToOne(() => User, (author: User) => author.articles)
author: User;
@ManyToOne(() => Article, (article: Article) => article.comments)
article: Article;
@TreeChildren()
children: Comment[];
@TreeParent()
parent: Comment;
@CreateDateColumn({
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP(6)',
})
createdAt: Date;
@UpdateDateColumn({
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP(6)',
onUpdate: 'CURRENT_TIMESTAMP(6)',
})
updatedAt: Date;
}
|
iamkarimi/blog-nestjs
|
src/roles/dto/create-role.dto.ts
|
import { IsDefined, IsString, Matches } from 'class-validator';
export class CreateRoleDto {
@IsString()
@IsDefined()
@Matches(/^(?!\s*$).+/, {
message: 'name should not be empty',
})
name: string;
}
|
iamkarimi/blog-nestjs
|
src/articles/dto/create-article.dto.ts
|
import {
IsDefined,
IsOptional,
IsString,
IsUUID,
Matches,
} from 'class-validator';
export class CreateArticleDto {
@IsString()
@IsDefined({ message: 'title is required' })
@Matches(/^(?!\s*$).+/, {
message: 'title should not be empty',
})
title: string;
@IsString()
@IsDefined({ message: 'slug is required' })
@Matches(/^(?!\s*$).+/, {
message: 'slug should not be empty',
})
@Matches(/^[a-zA-Z0-9- ]+$/, {
message: 'slug is not valid',
})
slug: string;
@IsString()
@IsDefined({ message: 'abstract is required' })
@Matches(/^(?!\s*$).+/, {
message: 'asbtract should not be empty',
})
abstract: string;
@IsString()
@IsDefined({ message: 'abstract is required' })
@Matches(/^(?!\s*$).+/, {
message: 'content should not be empty',
})
content: string;
@IsString()
@IsOptional()
thumbnail: string;
@IsUUID()
@IsString()
@IsDefined({ message: 'categoryId is required' })
@Matches(/^(?!\s*$).+/, {
message: 'categoryId should not be empty',
})
categoryId: string;
}
|
iamkarimi/blog-nestjs
|
src/articles/dto/update-article.dto.ts
|
import { PartialType } from '@nestjs/mapped-types';
import { CreateArticleDto } from './create-article.dto';
export class UpdateArticleDto extends PartialType(CreateArticleDto) {
title?: string;
slug?: string;
abstract?: string;
content?: string;
categoryId: string;
}
|
iamkarimi/blog-nestjs
|
src/comments/dto/update-comment.dto.ts
|
import { PartialType } from '@nestjs/mapped-types';
import { IsBoolean } from 'class-validator';
import { CreateCommentDto } from './create-comment.dto';
export class UpdateCommentDto extends PartialType(CreateCommentDto) {
content?: string;
@IsBoolean()
isApproved?: boolean;
}
|
iamkarimi/blog-nestjs
|
src/users/subscribers/user.subscriber.ts
|
<filename>src/users/subscribers/user.subscriber.ts
import {
EventSubscriber,
EntitySubscriberInterface,
Connection,
InsertEvent,
UpdateEvent,
} from 'typeorm';
import { User } from '../entities/user.entity';
import * as bcrypt from 'bcrypt';
@EventSubscriber()
export class UserSubscriber implements EntitySubscriberInterface<User> {
constructor(connection: Connection) {
connection.subscribers.push(this);
}
listenTo() {
return User;
}
async hashPassword(entity: User): Promise<void> {
entity.password = await bcrypt.hash(entity.password, entity.salt);
}
emailToLowerCase(entity: User) {
entity.email = entity.email.toLowerCase();
}
trimName(entity: User) {
entity.name = entity.name.trim();
}
async beforeInsert(event: InsertEvent<User>): Promise<void> {
await this.hashPassword(event.entity);
this.emailToLowerCase(event.entity);
this.trimName(event.entity);
}
async beforeUpdate({
entity,
databaseEntity,
}: UpdateEvent<User>): Promise<void> {
if (entity.password !== databaseEntity?.password)
await this.hashPassword(entity);
if (entity.name !== databaseEntity?.name) this.trimName(entity);
if (entity.email !== databaseEntity?.email) this.trimName(entity);
}
}
|
iamkarimi/blog-nestjs
|
src/auth/auth.controller.ts
|
import {
Body,
Controller,
Delete,
HttpCode,
Post,
ValidationPipe,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { CreateUserDto } from '../users/dto/create-user.dto';
import { AuthUserDto } from './dto/auth-user.dto';
import { LogoutUserDto } from './dto/logout-user.dto';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Post('register')
register(@Body(ValidationPipe) createUserDto: CreateUserDto) {
return this.authService.register(createUserDto);
}
@Post('login')
login(@Body(ValidationPipe) authUserdto: AuthUserDto) {
return this.authService.login(authUserdto);
}
@Delete('logout')
@HttpCode(204)
logout(@Body(ValidationPipe) logoutUserDto: LogoutUserDto) {
return this.authService.logout(logoutUserDto);
}
}
|
iamkarimi/blog-nestjs
|
src/auth/dto/logout-user.dto.ts
|
<gh_stars>0
import { IsDefined, IsJWT, IsString, Matches } from 'class-validator';
export class LogoutUserDto {
@IsJWT()
@IsString()
@IsDefined({ message: 'refreshToken is required' })
@Matches(/^(?!\s*$).+/, {
message: 'refreshToken should not be empty',
})
refreshToken: string;
}
|
iamkarimi/blog-nestjs
|
src/users/entities/user.entity.ts
|
import {
BaseEntity,
Column,
CreateDateColumn,
Entity,
JoinColumn,
ManyToOne,
OneToMany,
OneToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import * as bcrypt from 'bcrypt';
import { Profile } from './profile.entity';
import { Article } from '../../articles/entities/article.entity';
import { Role } from '../../roles/entities/role.entity';
@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
name: string;
@Column({ unique: true })
username: string;
@Column({ unique: true })
email: string;
@ManyToOne(() => Role, (role: Role) => role.users, { eager: true })
role: Role;
@Column({ select: false })
salt: string;
@Column({ select: false })
password: string;
@CreateDateColumn({
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP(6)',
})
createdAt: Date;
@UpdateDateColumn({
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP(6)',
onUpdate: 'CURRENT_TIMESTAMP(6)',
})
updatedAt: Date;
@OneToOne(() => Profile, (profile) => profile.user, {
onDelete: 'CASCADE',
})
@JoinColumn()
profile: Profile;
@OneToMany(() => Article, (article: Article) => article.author, {
onDelete: 'CASCADE',
})
articles: Article[];
async validatePassword(password: string): Promise<boolean> {
const hash = await bcrypt.hash(password, this.salt);
return hash === this.password;
}
}
|
iamkarimi/blog-nestjs
|
src/comments/comments.service.ts
|
<filename>src/comments/comments.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UpdateCommentDto } from './dto/update-comment.dto';
import { Comment } from './entities/comment.entity';
@Injectable()
export class CommentsService {
constructor(
@InjectRepository(Comment)
private readonly commentRepository: Repository<Comment>,
) {}
async findAll(): Promise<Comment[]> {
return await this.commentRepository.find({ order: { createdAt: 'DESC' } });
}
async findOne(id: string): Promise<Comment> {
const comment = await this.commentRepository.findOne(id);
if (!comment) throw new NotFoundException();
return comment;
}
async update(
id: string,
updateCommentDto: UpdateCommentDto,
): Promise<Comment> {
const comment = await this.commentRepository.findOne(id);
if (!comment) {
throw new NotFoundException();
}
const object = Object.assign(comment, updateCommentDto);
const newComment = await this.commentRepository.save(object);
return newComment;
}
async remove(id: string): Promise<Comment> {
const comment = await this.commentRepository.findOne(id);
if (!comment) throw new NotFoundException();
await this.commentRepository.delete(id);
return comment;
}
}
|
iamkarimi/blog-nestjs
|
src/categories/categories.service.ts
|
import {
ConflictException,
Injectable,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateCategoryDto } from './dto/create-category.dto';
import { UpdateCategoryDto } from './dto/update-category.dto';
import { Category } from './entities/category.entity';
@Injectable()
export class CategoriesService {
constructor(
@InjectRepository(Category)
private readonly categoryRepository: Repository<Category>,
) {}
async create(createCategoryDto: CreateCategoryDto): Promise<Category> {
try {
return await this.categoryRepository.save(createCategoryDto);
} catch (error) {
if (error.code === '23505') {
if (error.detail.includes('slug'))
throw new ConflictException('slug already exists');
} else {
throw new InternalServerErrorException();
}
}
}
async findAll(): Promise<Category[]> {
return await this.categoryRepository.find({ order: { createdAt: 'DESC' } });
}
async findOne(id: string): Promise<Category> {
const category = await this.categoryRepository.findOne(id);
if (!category) throw new NotFoundException();
return category;
}
async update(
id: string,
updateCategoryDto: UpdateCategoryDto,
): Promise<Category> {
const category = await this.categoryRepository.findOne(id);
if (!category) {
throw new NotFoundException();
}
const object = Object.assign(category, updateCategoryDto);
try {
const newCategory = await this.categoryRepository.save(object);
return newCategory;
} catch (error) {
if (error.code === '23505') {
if (error.detail.includes('slug'))
throw new ConflictException('slug already exists');
} else {
throw new InternalServerErrorException();
}
}
}
async remove(id: string): Promise<Category> {
const category = await this.categoryRepository.findOne(id);
if (!category) throw new NotFoundException();
await this.categoryRepository.delete(id);
return category;
}
}
|
iamkarimi/blog-nestjs
|
src/users/subscribers/profile.subscriber.ts
|
import {
EventSubscriber,
EntitySubscriberInterface,
Connection,
InsertEvent,
UpdateEvent,
} from 'typeorm';
import { Profile } from '../entities/profile.entity';
@EventSubscriber()
export class ProfileSubscriber implements EntitySubscriberInterface<Profile> {
constructor(connection: Connection) {
connection.subscribers.push(this);
}
listenTo() {
return Profile;
}
tirmAvatar(entity: Profile) {
entity.avatar = entity.avatar.trim();
}
tirmBio(entity: Profile) {
entity.bio = entity.bio.trim();
}
async beforeInsert(event: InsertEvent<Profile>): Promise<void> {
this.tirmBio(event.entity);
this.tirmAvatar(event.entity);
}
async beforeUpdate({
entity,
databaseEntity,
}: UpdateEvent<Profile>): Promise<void> {
if (entity.avatar !== databaseEntity?.avatar) this.tirmAvatar(entity);
if (entity.bio !== databaseEntity?.bio) this.tirmBio(entity);
}
}
|
iamkarimi/blog-nestjs
|
src/config/redis.config.ts
|
<gh_stars>0
import { registerAs } from '@nestjs/config';
import { RedisModuleOptions } from 'nestjs-redis';
export default registerAs(
'redis.config',
(): RedisModuleOptions => ({
name: 'redis',
port: Number(process.env.REDIS_PORT),
host: process.env.REDIS_HOST,
}),
);
|
iamkarimi/blog-nestjs
|
src/roles/roles.controller.ts
|
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
ParseUUIDPipe,
UseGuards,
ValidationPipe,
} from '@nestjs/common';
import { RolesService } from './roles.service';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { AuthGuard } from '@nestjs/passport';
import { Roles } from '../auth/decorators/roles.decorator';
import { RolesGuard } from '../auth/guards/roles.guard';
@Controller('admin/roles')
@UseGuards(AuthGuard('jwt'), RolesGuard)
export class RolesController {
constructor(private readonly rolesService: RolesService) {}
@Post()
@Roles('admin')
create(@Body(ValidationPipe) createRoleDto: CreateRoleDto) {
return this.rolesService.create(createRoleDto);
}
@Get()
@Roles('admin')
findAll() {
return this.rolesService.findAll();
}
@Get(':id')
@Roles('admin')
findOne(@Param('id', ParseUUIDPipe) id: string) {
return this.rolesService.findOne(id);
}
@Patch(':id')
@Roles('admin')
update(
@Param('id', ParseUUIDPipe) id: string,
@Body(ValidationPipe) updateRoleDto: UpdateRoleDto,
) {
return this.rolesService.update(id, updateRoleDto);
}
@Delete(':id')
@Roles('admin')
remove(@Param('id', ParseUUIDPipe) id: string) {
return this.rolesService.remove(id);
}
}
|
iamkarimi/blog-nestjs
|
src/app.module.ts
|
<filename>src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { UsersModule } from './users/users.module';
import postgresConfig from './config/postgres.config';
import { RedisModule } from 'nestjs-redis';
import { AuthModule } from './auth/auth.module';
import { ArticlesModule } from './articles/articles.module';
import { CategoriesModule } from './categories/categories.module';
import { CommentsModule } from './comments/comments.module';
import { RolesModule } from './roles/roles.module';
import redisConfig from './config/redis.config';
import { AppService } from './app.service';
import { Comment } from './comments/entities/comment.entity';
import { Article } from './articles/entities/article.entity';
import { Category } from './categories/entities/category.entity';
@Module({
imports: [
TypeOrmModule.forFeature([Article, Comment, Category]),
ConfigModule.forRoot({
isGlobal: true,
load: [postgresConfig],
expandVariables: true,
envFilePath: '.env',
}),
TypeOrmModule.forRootAsync({
useFactory: postgresConfig,
}),
RedisModule.forRootAsync({
useFactory: redisConfig,
}),
UsersModule,
AuthModule,
ArticlesModule,
CategoriesModule,
CommentsModule,
RolesModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
|
iamkarimi/blog-nestjs
|
src/users/entities/profile.entity.ts
|
import {
BaseEntity,
Column,
Entity,
OneToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
import { User } from './user.entity';
@Entity()
export class Profile extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ nullable: true })
avatar: string;
@Column({ unsigned: true, nullable: true })
age: number;
@Column('text', { nullable: true })
bio: string;
@OneToOne(() => User, (user) => user.profile)
user: User;
}
|
iamkarimi/blog-nestjs
|
src/articles/articles.controller.ts
|
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
UseGuards,
ValidationPipe,
ParseUUIDPipe,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ArticlesService } from './articles.service';
import { CreateArticleDto } from './dto/create-article.dto';
import { UpdateArticleDto } from './dto/update-article.dto';
import { GetAuthUser } from '../auth/decorators/get-auth-user.decorator';
import { User } from '../users/entities/user.entity';
import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/decorators/roles.decorator';
@Controller('admin/articles')
@UseGuards(AuthGuard('jwt'), RolesGuard)
export class ArticlesController {
constructor(private readonly articlesService: ArticlesService) {}
@Post()
@Roles('admin')
create(
@GetAuthUser() user: User,
@Body(ValidationPipe) createArticleDto: CreateArticleDto,
) {
return this.articlesService.create(user, createArticleDto);
}
@Get()
@Roles('admin')
findAll() {
return this.articlesService.findAll();
}
@Get(':id')
@Roles('admin')
findOne(@Param('id', ParseUUIDPipe) id: string) {
return this.articlesService.findOne(id);
}
@Patch(':id')
@Roles('admin')
update(
@Param('id', ParseUUIDPipe) id: string,
@Body(ValidationPipe) updateArticleDto: UpdateArticleDto,
) {
return this.articlesService.update(id, updateArticleDto);
}
@Delete(':id')
@Roles('admin')
remove(@Param('id', ParseUUIDPipe) id: string) {
return this.articlesService.remove(id);
}
}
|
iamkarimi/blog-nestjs
|
src/users/users.service.ts
|
import {
ConflictException,
Injectable,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { RedisService } from 'nestjs-redis';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { Role } from '../roles/entities/role.entity';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User) private readonly userRepository: Repository<User>,
@InjectRepository(Role) private readonly roleRepository: Repository<Role>,
) {}
async findAll(): Promise<User[]> {
return await this.userRepository.find({ order: { createdAt: 'DESC' } });
}
async findOne(id: string): Promise<User> {
const user = this.userRepository.findOne(id);
if (!user) throw new NotFoundException();
return user;
}
async update(id: string, updateUserDto: UpdateUserDto): Promise<User> {
const user = await this.userRepository.findOne(id);
if (!user) throw new NotFoundException();
let role = null;
if (updateUserDto.roleId)
role = await this.roleRepository.findOne({ id: updateUserDto.roleId });
if (role) {
user.role = role;
}
user.name = updateUserDto.name;
user.username = updateUserDto.username;
user.email = updateUserDto.email;
user.password = <PASSWORD>;
try {
return await this.userRepository.save(user);
} catch (error) {
if (error.code === '23505') {
if (error.detail.includes('username'))
throw new ConflictException('username already exists');
if (error.detail.includes('email'))
throw new ConflictException('email already exists');
}
throw new InternalServerErrorException();
}
}
async remove(id: string): Promise<User> {
const user = this.userRepository.findOne(id);
if (!user) throw new NotFoundException();
await this.userRepository.delete(id);
return user;
}
}
|
iamkarimi/blog-nestjs
|
src/categories/subscribers/category.subscriber.ts
|
<gh_stars>0
import {
EventSubscriber,
EntitySubscriberInterface,
Connection,
InsertEvent,
UpdateEvent,
} from 'typeorm';
import { Category } from '../entities/category.entity';
import slugify from 'slugify';
@EventSubscriber()
export class CategorySubscriber implements EntitySubscriberInterface<Category> {
constructor(connection: Connection) {
connection.subscribers.push(this);
}
listenTo() {
return Category;
}
slugifySlug(entity: Category) {
entity.slug = slugify(entity.slug).trim().toLowerCase();
}
trimName(entity: Category) {
entity.name = entity.name.trim();
}
beforeInsert(event: InsertEvent<Category>) {
this.slugifySlug(event.entity);
this.trimName(event.entity);
}
beforeUpdate({ entity, databaseEntity }: UpdateEvent<Category>) {
if (entity.slug !== databaseEntity?.slug) this.slugifySlug(entity);
if (entity.name !== databaseEntity?.name) this.trimName(entity);
}
}
|
iamkarimi/blog-nestjs
|
src/articles/articles.service.ts
|
<reponame>iamkarimi/blog-nestjs<gh_stars>0
import {
ConflictException,
Injectable,
NotFoundException,
InternalServerErrorException,
UnauthorizedException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateArticleDto } from './dto/create-article.dto';
import { UpdateArticleDto } from './dto/update-article.dto';
import { Article } from './entities/article.entity';
import { Repository } from 'typeorm';
import { User } from '../users/entities/user.entity';
import { Category } from '../categories/entities/category.entity';
@Injectable()
export class ArticlesService {
constructor(
@InjectRepository(Article)
private readonly articleRepository: Repository<Article>,
@InjectRepository(Category)
private readonly categoryRepository: Repository<Category>,
) {}
async create(
user: User,
createArticleDto: CreateArticleDto,
): Promise<Article> {
const category = await this.categoryRepository.findOne(
createArticleDto.categoryId,
);
if (!category) {
throw new NotFoundException('category not found');
}
const article = new Article();
article.category = category;
article.author = user;
const object = Object.assign(article, createArticleDto);
try {
const art = await this.articleRepository.save(object);
delete art.categoryId;
return art;
} catch (error) {
if (error.code === '23505') {
throw new ConflictException('slug already exists');
} else {
throw new InternalServerErrorException();
}
}
}
async findAll(): Promise<Article[]> {
return await this.articleRepository.find({ order: { createdAt: 'DESC' } });
}
async findOne(id: string): Promise<Article> {
const article = await this.articleRepository.findOne(id);
if (!article) {
throw new NotFoundException();
}
return article;
}
async update(
id: string,
updateArticleDto: UpdateArticleDto,
): Promise<Article> {
const category = await this.categoryRepository.findOne(
updateArticleDto.categoryId,
);
if (!category) {
throw new NotFoundException('category not found');
}
const article = await this.articleRepository.findOne(id);
if (!article) throw new NotFoundException();
article.category = category;
const object = Object.assign(article, updateArticleDto);
try {
const art = await this.articleRepository.save(object);
delete art.categoryId;
return art;
} catch (error) {
if (error.code === '23505') {
throw new ConflictException('slug already exists');
} else {
throw new InternalServerErrorException();
}
}
}
async remove(id: string): Promise<Article> {
const article = await this.articleRepository.findOne(id);
if (!article) {
throw new NotFoundException();
}
await this.articleRepository.delete(id);
return article;
}
}
|
iamkarimi/blog-nestjs
|
src/roles/roles.service.ts
|
<gh_stars>0
import { InjectRepository } from '@nestjs/typeorm';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { Repository } from 'typeorm';
import { Role } from './entities/role.entity';
import {
ConflictException,
Injectable,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
@Injectable()
export class RolesService {
constructor(
@InjectRepository(Role) private readonly roleRepository: Repository<Role>,
) {}
async create(createRoleDto: CreateRoleDto): Promise<Role> {
try {
return await this.roleRepository.save(createRoleDto);
} catch (error) {
if (error.code === '23505') {
throw new ConflictException('name already exisits');
}
throw new InternalServerErrorException();
}
}
async findAll(): Promise<Role[]> {
return await this.roleRepository.find({ order: { createdAt: 'DESC' } });
}
async findOne(id: string): Promise<Role> {
const role = await this.roleRepository.findOne(id);
if (!role) throw new NotFoundException();
return role;
}
async update(id: string, updateRoleDto: UpdateRoleDto) {
const role = await this.roleRepository.findOne(id);
if (!role) throw new NotFoundException();
const object = Object.assign(role, updateRoleDto);
try {
return await this.roleRepository.save(object);
} catch (error) {
if (error.code === '23505')
throw new ConflictException('name already exists');
throw new InternalServerErrorException();
}
}
async remove(id: string): Promise<Role> {
const role = await this.roleRepository.findOne(id);
if (!role) throw new NotFoundException();
await this.roleRepository.delete(id);
return role;
}
}
|
iamkarimi/blog-nestjs
|
src/users/dto/create-user.dto.ts
|
import { Match } from '../decorators/match.decorator';
import {
IsDefined,
IsEmail,
IsString,
Matches,
MinLength,
} from 'class-validator';
export class CreateUserDto {
@IsString()
@IsDefined({ message: 'name is required' })
@Matches(/^(?!\s*$).+/, {
message: 'name should not be empty',
})
name: string;
@IsString()
@IsDefined({ message: 'username is required' })
@Matches(/^(?!\s*$).+/, {
message: 'username should not be empty',
})
@Matches(/^(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/, {
message: 'username is not valid',
})
username: string;
@IsString()
@IsEmail()
@IsDefined({ message: 'email is required' })
@Matches(/^(?!\s*$).+/, {
message: 'email should not be empty',
})
email: string;
@IsString()
@MinLength(8)
@Matches(/((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/, {
message: 'password too weak',
})
password: string;
@IsString()
@Match('password', {
message: 'password is not match',
})
passwordConfirm: string;
// @IsDefined()
}
|
iamkarimi/blog-nestjs
|
src/articles/entities/article.entity.ts
|
import {
BaseEntity,
Column,
CreateDateColumn,
Entity,
ManyToOne,
OneToMany,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { User } from '../../users/entities/user.entity';
import { Category } from '../../categories/entities/category.entity';
import { Comment } from '../../comments/entities/comment.entity';
@Entity()
export class Article extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
title: string;
@Column({ unique: true })
slug: string;
@Column()
abstract: string;
@Column({ type: 'text' })
content: string;
@Column({ nullable: true })
thumbnail: string;
@CreateDateColumn({
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP(6)',
})
createdAt: Date;
@UpdateDateColumn({
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP(6)',
onUpdate: 'CURRENT_TIMESTAMP(6)',
})
updatedAt: Date;
@ManyToOne(() => User, (author: User) => author.articles)
author: User;
@ManyToOne(() => Category, (category: Category) => category.articles)
category: Category;
@OneToMany(() => Comment, (comment: Comment) => comment.article, {
onDelete: 'CASCADE',
})
comments: Comment[];
}
|
iamkarimi/blog-nestjs
|
src/comments/comments.controller.ts
|
import {
Controller,
Get,
Body,
Patch,
Param,
Delete,
ParseUUIDPipe,
ValidationPipe,
UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { CommentsService } from './comments.service';
import { UpdateCommentDto } from './dto/update-comment.dto';
import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/decorators/roles.decorator';
@Controller('admin/comments')
@UseGuards(AuthGuard('jwt'), RolesGuard)
export class CommentsController {
constructor(private readonly commentsService: CommentsService) {}
@Get()
@Roles('admin')
findAll() {
return this.commentsService.findAll();
}
@Get(':id')
@Roles('admin')
findOne(@Param('id', ParseUUIDPipe) id: string) {
return this.commentsService.findOne(id);
}
@Patch(':id')
@Roles('admin')
update(
@Param('id', ParseUUIDPipe) id: string,
@Body(ValidationPipe) updateCommentDto: UpdateCommentDto,
) {
return this.commentsService.update(id, updateCommentDto);
}
@Delete(':id')
@Roles('admin')
remove(@Param('id', ParseUUIDPipe) id: string) {
return this.commentsService.remove(id);
}
}
|
iamkarimi/blog-nestjs
|
src/categories/dto/create-category.dto.ts
|
<filename>src/categories/dto/create-category.dto.ts
import { IsDefined, IsString, Matches } from 'class-validator';
export class CreateCategoryDto {
@IsString()
@IsDefined({ message: 'name is required' })
@Matches(/^(?!\s*$).+/, {
message: 'name should not be empty',
})
name: string;
@IsString()
@IsDefined({ message: 'slug is required' })
@Matches(/^(?!\s*$).+/, {
message: 'slug should not be empty',
})
@Matches(/^[a-zA-Z0-9- ]+$/, {
message: 'slug is not valid',
})
slug: string;
}
|
iamkarimi/blog-nestjs
|
src/articles/subscribers/article.subscriber.ts
|
<reponame>iamkarimi/blog-nestjs
import {
EventSubscriber,
Connection,
InsertEvent,
UpdateEvent,
EntitySubscriberInterface,
} from 'typeorm';
import { Article } from '../entities/article.entity';
import slugify from 'slugify';
@EventSubscriber()
export class ArticleSubscriber implements EntitySubscriberInterface<Article> {
constructor(connection: Connection) {
connection.subscribers.push(this);
}
listenTo() {
return Article;
}
slugifySlug(entity: Article) {
entity.slug = slugify(entity.slug).trim().toLowerCase();
}
beforeInsert(event: InsertEvent<Article>) {
this.slugifySlug(event.entity);
event.entity.title = event.entity.title.trim();
event.entity.abstract = event.entity.abstract.trim();
event.entity.content = event.entity.content.trim();
if (event.entity.thumbnail) {
event.entity.thumbnail = event.entity.thumbnail.trim();
}
}
beforeUpdate({ entity, databaseEntity }: UpdateEvent<Article>) {
if (entity.slug !== databaseEntity?.slug) this.slugifySlug(entity);
if (entity.title !== databaseEntity?.title)
entity.title = entity.title.trim();
if (entity.abstract !== databaseEntity?.abstract)
entity.abstract = entity.abstract.trim();
if (entity.content !== databaseEntity?.content)
entity.content = entity.content.trim();
if (entity.thumbnail) {
if (entity.thumbnail !== databaseEntity?.thumbnail)
entity.thumbnail = entity.thumbnail.trim();
}
}
}
|
iamkarimi/blog-nestjs
|
src/auth/dto/auth-user.dto.ts
|
<filename>src/auth/dto/auth-user.dto.ts
import { IsDefined, IsNotEmpty, IsString, Matches } from 'class-validator';
export class AuthUserDto {
@IsString()
@IsDefined({ message: 'username is required' })
@Matches(/^(?!\s*$).+/, {
message: 'username should not be empty',
})
username: string;
@IsString()
@IsNotEmpty()
@IsDefined({ message: 'password is required' })
password: string;
}
|
iamkarimi/blog-nestjs
|
src/auth/auth.module.ts
|
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from '../users/entities/user.entity';
import { Profile } from '../users/entities/profile.entity';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import jwtConfig from 'src/config/jwt.config';
import { JwtStrategy } from './jwt/jwt.strategy';
import { Role } from '../roles/entities/role.entity';
@Module({
imports: [
TypeOrmModule.forFeature([User, Profile, Role]),
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
useFactory: jwtConfig,
}),
],
providers: [AuthService, JwtStrategy],
controllers: [AuthController],
exports: [PassportModule, JwtStrategy, AuthService],
})
export class AuthModule {}
|
iamkarimi/blog-nestjs
|
src/auth/auth.service.ts
|
import {
BadRequestException,
ConflictException,
Injectable,
InternalServerErrorException,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { RedisService } from 'nestjs-redis';
import { Repository } from 'typeorm';
import { User } from '../users/entities/user.entity';
import { CreateUserDto } from '../users/dto/create-user.dto';
import * as bcrypt from 'bcrypt';
import { JwtPayload } from './jwt/jwt-payload.interface';
import { AuthUserDto } from './dto/auth-user.dto';
import { LogoutUserDto } from './dto/logout-user.dto';
import { Role } from '../roles/entities/role.entity';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(User) private readonly userRepository: Repository<User>,
@InjectRepository(Role) private readonly roleRepository: Repository<Role>,
private readonly jwtService: JwtService,
private readonly redisService: RedisService,
) {}
async register(
createUserDto: CreateUserDto,
): Promise<{ user: User; accessToken: string; refreshToken: string }> {
const role = await this.roleRepository.findOne({ name: 'user' });
if (!role) throw new NotFoundException('user role not found');
const user = new User();
user.name = createUserDto.name;
user.username = createUserDto.username;
user.email = createUserDto.email;
user.salt = await bcrypt.genSalt();
user.password = <PASSWORD>;
user.profile = null;
user.role = role;
try {
const newUser = await this.userRepository.save(user);
const { id } = newUser;
const payload: JwtPayload = { id };
const accessToken = await this.signAccessToken(payload);
const refreshToken = await this.signRefreshToken(payload);
await this.setRefreshTokenToRedis(id, refreshToken);
delete newUser.role;
delete newUser.profile;
delete newUser.password;
delete newUser.salt;
return { user: newUser, accessToken, refreshToken };
} catch (error) {
if (error.code === '23505') {
if (error.detail.includes('username'))
throw new ConflictException('username already exists');
if (error.detail.includes('email'))
throw new ConflictException('email already exists');
} else {
throw new InternalServerErrorException();
}
}
}
async login(
authUserDto: AuthUserDto,
): Promise<{ user: User; accessToken: string; refreshToken: string }> {
const user = await this.validateUserPassword(authUserDto);
if (!user) throw new UnauthorizedException('invalid crendentials');
const { id } = user;
const payload: JwtPayload = { id };
const accessToken = await this.signAccessToken(payload);
const refreshToken = await this.signRefreshToken(payload);
await this.setRefreshTokenToRedis(id, refreshToken);
delete user.password;
delete user.salt;
return { user, accessToken, refreshToken };
}
async logout(logoutUserDto: LogoutUserDto): Promise<void> {
try {
const { refreshToken } = logoutUserDto;
const payload = await this.jwtService.verify(refreshToken, {
secret: process.env.JWT_REFRESH_SECRET,
});
const client = await this.redisService.getClient('redis');
const result = await client.get(payload.id);
if (result && result === refreshToken) {
await client.del(payload.id);
return;
} else {
throw new UnauthorizedException();
}
} catch (error) {
if (error instanceof SyntaxError) {
throw new BadRequestException('invalid refresh token');
}
if (error instanceof UnauthorizedException) {
throw new UnauthorizedException();
}
throw new InternalServerErrorException();
}
}
private async setRefreshTokenToRedis(id: string, refreshToken: string) {
const client = await this.redisService.getClient('redis');
await client.set(
id,
refreshToken,
'EX',
Number(process.env.REFRESH_TOKEN_EXPIRESIN),
);
}
private async signAccessToken(payload: JwtPayload): Promise<string> {
return await this.jwtService.sign(payload);
}
private async signRefreshToken(payload: JwtPayload): Promise<string> {
return await this.jwtService.sign(payload, {
secret: process.env.JWT_REFRESH_SECRET,
expiresIn: Number(process.env.REFRESH_TOKEN_EXPIRESIN),
});
}
private async validateUserPassword(authUserDto: AuthUserDto): Promise<User> {
const { username, password } = authUserDto;
const user = await this.userRepository
.createQueryBuilder('user')
.select()
.where({ username })
.addSelect('user.password')
.addSelect('user.salt')
.getOne();
if (user && (await user.validatePassword(password))) return user;
else return null;
}
}
|
iamkarimi/blog-nestjs
|
src/comments/subscribers/comment.subscriber.ts
|
import { Comment } from '../entities/comment.entity';
import {
Connection,
EntitySubscriberInterface,
EventSubscriber,
InsertEvent,
UpdateEvent,
} from 'typeorm';
@EventSubscriber()
export class CommentSubscriber implements EntitySubscriberInterface<Comment> {
constructor(connection: Connection) {
connection.subscribers.push(this);
}
listenTo() {
return Comment;
}
tirmContent(entity: Comment) {
entity.content = entity.content.trim();
}
beforeInsert(event: InsertEvent<Comment>) {
return this.tirmContent(event.entity);
}
beforeUpdate({ entity, databaseEntity }: UpdateEvent<Comment>) {
if (entity.content !== databaseEntity?.content) this.tirmContent(entity);
}
}
|
thinhtran3588/react-native-starter-kit
|
src/core/components/index.ts
|
import {Text, SafeAreaView} from 'react-native';
export {Text, SafeAreaView};
export * from './icon/icon';
export * from './navigation/navigation';
|
thinhtran3588/react-native-starter-kit
|
src/modules/weather/screens/index.ts
|
export * from './weather_screen/weather_screen';
|
thinhtran3588/react-native-starter-kit
|
src/modules/settings/screens/settings_screen/settings_screen.tsx
|
<reponame>thinhtran3588/react-native-starter-kit
import React from 'react';
import {Text, SafeAreaView} from '@core/components';
export const SettingsScreen = (): JSX.Element => {
return (
<SafeAreaView>
<Text>Settings!</Text>
</SafeAreaView>
);
};
|
thinhtran3588/react-native-starter-kit
|
src/core/components/navigation/navigation.tsx
|
import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import {NavItem} from '@core/interfaces';
import {Icon} from '../icon/icon';
interface Props {
navItems: NavItem[];
}
const Tab = createBottomTabNavigator();
export const Navigation = (props: Props): JSX.Element => {
const {navItems} = props;
return (
<NavigationContainer>
<Tab.Navigator
tabBarOptions={{
activeTintColor: 'tomato',
inactiveTintColor: 'gray',
}}
initialRouteName={navItems[0].name}>
{navItems.map((navItem) => (
<Tab.Screen
key={navItem.name}
name={navItem.name}
component={navItem.component}
options={{
title: navItem.title,
tabBarIcon: (iconProps) => {
const {focused, color, size} = iconProps;
return <Icon name={focused ? navItem.iconFocused : navItem.icon} size={size} color={color} />;
},
}}
/>
))}
</Tab.Navigator>
</NavigationContainer>
);
};
|
thinhtran3588/react-native-starter-kit
|
src/modules/weather/screens/weather_screen/weather_screen.tsx
|
<filename>src/modules/weather/screens/weather_screen/weather_screen.tsx<gh_stars>1-10
import React from 'react';
import {Text, SafeAreaView} from '@core/components';
export const WeatherScreen = (): JSX.Element => {
return (
<SafeAreaView>
<Text>Weather Forecast!</Text>
</SafeAreaView>
);
};
|
thinhtran3588/react-native-starter-kit
|
src/modules/settings/screens/index.ts
|
<reponame>thinhtran3588/react-native-starter-kit<filename>src/modules/settings/screens/index.ts
export * from './settings_screen/settings_screen';
|
thinhtran3588/react-native-starter-kit
|
src/app.tsx
|
import React from 'react';
import {Navigation} from '@core/components';
import {NavItem} from '@core/interfaces';
import {WeatherScreen} from '@weather/screens';
import {SettingsScreen} from '@settings/screens';
const navItems: NavItem[] = [
{
name: 'weather',
title: 'Weather',
component: WeatherScreen,
icon: 'thought-bubble-outline',
iconFocused: 'thought-bubble',
},
{
name: 'settings',
title: 'Settings',
component: SettingsScreen,
icon: 'settings-outline',
iconFocused: 'settings',
},
];
export const App = (): JSX.Element => {
return <Navigation navItems={navItems} />;
};
|
hcl2020/mobile-view
|
src/index.ts
|
// @ts-ignore
import QRCode from './libs/qrcode'; // from 'qrcode_js';
const strStyle = '__CSS_CONTENT__';
let qrcode: any;
function changeQrCode(text: string) {
console.log('MobileView: QrCode', text);
text = addParam(text, 'from=MobileView');
if (qrcode) {
qrcode.clear(); // clear the code.
qrcode.makeCode(text); // make another code.
} else {
qrcode = new QRCode(document.getElementById('mobile-view-qrcode-img'), {
text: text,
width: 156,
height: 156,
colorDark: '#000000',
colorLight: '#ffffff'
// correctLevel: QRCode.CorrectLevel.H
});
}
}
function addParam(text: string, param: string) {
if (param && text.match(/^http(s)?:\/\//)) {
text += text.includes('?') ? '&' : '?';
text += param;
}
return text;
}
function syncTitle(contentDocument: Document, document: Document) {
let $title = contentDocument.getElementsByTagName('title')[0];
if ($title) {
new MutationObserver(records => {
records.forEach(record => {
document.title = contentDocument.title;
});
}).observe($title, { subtree: true, childList: true, characterData: true });
}
}
function stopLoadNextEl() {
try {
window.stop();
} catch (error) {
// For IE
document.execCommand('stop');
}
}
interface MobileViewOption {
tips?: string;
message?: string;
threshold?: number;
noThrowError?: boolean;
logo?: string;
}
const MobileView = function MobileView(option: MobileViewOption = {}): boolean {
let {
tips = '扫描二维码用手机查看~',
message = '建议使用手机访问此页面',
threshold = 981,
noThrowError = false,
logo = ''
} = option;
if (window.innerWidth <= threshold || window.screen.width <= threshold) {
return false;
}
let bodyTpl = `
<div id="mobile-view">
<div id="mobile-view-message">${message}</div>
<div id="mobile-view-qrcode">
<div id="mobile-view-qrcode-img"></div>
${logo ? `<img id="mobile-view-qrcode-logo" src="${logo}" alt="logo" />` : ''}
<p>${tips}</p>
</div>
<div id="mobile-view-mobile">
<mark></mark>
<iframe src="${location.href}"></iframe>
</div>
</div>
<style>${strStyle}</style>`;
// 停止网页解析和资源加载,构造body对象 (only Chrome)
stopLoadNextEl();
document.open();
document.close();
// 移除 head 中的各种 (For Chrome 36...)
document.head.innerHTML = '';
let $body = document.body;
if (!$body) {
$body = document.createElement('body');
document.getElementsByTagName('html')[0].append($body);
}
$body.innerHTML = bodyTpl;
changeQrCode(location.href);
function insertStyle(doc: Document) {
let strCss =
'* {-ms-overflow-style: -ms-autohiding-scrollbar;scrollbar-width: thin;}' +
'::-webkit-scrollbar{width:6px;height:6px;background:transparent}' +
'::-webkit-scrollbar-thumb{background:rgba(128,128,128,0.5)}' +
'::-webkit-scrollbar-thumb:hover{background:rgba(0,0,0,0.5)}' +
'::-webkit-scrollbar-corner{display: none}';
let $style = doc.createElement('style');
$style.innerHTML = strCss;
doc.head.appendChild($style);
}
let $iframe = document.getElementsByTagName('iframe')[0];
if ($iframe) {
$iframe.onload = function initIframe() {
let { contentDocument, contentWindow } = $iframe;
if (contentDocument && contentWindow) {
insertStyle(contentDocument);
/* 处理地址栏 */
let _location = contentWindow.location;
history.replaceState(null, '', _location.href);
changeQrCode(_location.href);
let { replaceState, pushState } = contentWindow.history;
contentWindow.history.replaceState = function (
data: any,
unused: string,
url?: string | URL | null | undefined
) {
replaceState.apply(this, [data, unused, url]);
history.replaceState.apply(history, [data, unused, url]);
changeQrCode(_location.href);
};
contentWindow.history.pushState = function (data: any, unused: string, url?: string | URL | null | undefined) {
pushState.apply(this, [data, unused, url]);
history.replaceState.apply(history, [data, unused, url]);
changeQrCode(_location.href);
};
contentWindow.addEventListener('hashchange', function (event) {
window.location.hash = _location.hash;
});
contentWindow.addEventListener('popstate', function (event) {
changeQrCode(_location.href);
});
document.title = contentDocument.title;
syncTitle(contentDocument, document);
} else {
// 跨域外部链接
// TODO: 获取外部链接,生成二维码,地址栏给出提示
}
};
}
if (noThrowError) {
return true;
} else {
let { onerror } = window;
window.onerror = function mv_onerror(message) {
console.log('MobileView: __VERSION__');
window.onerror = onerror;
return true;
};
throw new Error('MobileView:阻止后续代码执行');
}
};
export default MobileView;
|
hcl2020/mobile-view
|
types/index.d.ts
|
declare function MobileView(option?: {
tips?: string;
message?: string;
threshold?: number;
noThrowError?: boolean;
logo?: string;
}): boolean;
export default MobileView;
export as namespace MobileView;
|
sgsonu/covid-vaccine-distribution
|
services/server/src/models/root/experimental/signUpRandomAdminsUsers/index.ts
|
import { point, nearestPoint, featureCollection } from "@turf/turf";
import { hash } from "bcryptjs";
import { internet, name } from "faker";
import { getConnection } from "typeorm";
import { User } from "../../../../entity/User";
import { timeSlots } from "../../../admin/scheduleVaccination/timeSlots";
import cities from "./cities.json";
const getRandomInt = (min: number, max: number): number => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
};
const getRandomElementsFromArray = <T>(arr: T[], n: number) => {
const shuffled = arr.sort(() => 0.5 - Math.random());
return shuffled.slice(0, n);
};
export const signUpRandomAdminsUsers = async (
numAdmins: number,
numUsers: number
): Promise<boolean> => {
const dbConnection = getConnection();
const admins: User[] = await Promise.all(
getRandomElementsFromArray(cities, Math.min(numAdmins, cities.length)).map(
async (city) => {
const admin = new User();
admin.email = internet.email();
admin.firstName = city.city;
admin.lastName = "Admin";
admin.password = await hash("<PASSWORD>", 10);
admin.isVerified = true;
admin.isAdmin = true;
admin.location = { type: "Point", coordinates: [+city.lat, +city.lng] };
return admin;
}
)
);
const users: User[] = new Array(numUsers).fill(0).map(() => {
const user = new User();
user.email = internet.email();
user.firstName = name.firstName();
user.lastName = name.lastName();
user.password = <PASSWORD>();
user.isVerified = true;
user.isVaccinated = 0.5 - Math.random() > 0;
const date = new Date();
if (user.isVaccinated) {
date.setDate(date.getDate() - getRandomInt(1, 60));
user.vaccinationDate = date.toDateString();
user.vaccinationTimeSlot =
timeSlots[getRandomInt(0, timeSlots.length - 1)];
}
user.covidVulnerabilityScore = Math.random();
const { lat, lng } = cities[getRandomInt(0, cities.length - 1)]!;
user.location = { type: "Point", coordinates: [+lat, +lng] };
if (user.isVaccinated) {
const userPoint = point(user.location.coordinates);
const adminPoints = admins.map(({ location }) =>
point(location.coordinates)
);
const nearestAdmin = nearestPoint(
userPoint,
featureCollection(adminPoints)
);
user.adminEmail = admins[nearestAdmin.properties.featureIndex]!.email;
}
return user;
});
try {
await dbConnection.getRepository(User).insert([...admins, ...users]);
return true;
} catch (error) {
throw new Error(error);
}
};
|
sgsonu/covid-vaccine-distribution
|
services/server/src/routers/getAdmins/index.ts
|
import { Router, Response } from "express";
import { getAdmins } from "../../models/getAdmins";
export const getAdminsRouter = Router();
getAdminsRouter.get(
"/",
async (_, res: Response): Promise<Response> => {
try {
const admins = await getAdmins();
return res.status(200).send({ admins });
} catch (error) {
return res.status(500).send({ error: error.message });
}
}
);
|
sgsonu/covid-vaccine-distribution
|
services/server/src/models/admin/getRegisteredPatients/index.ts
|
import { Brackets, getConnection } from "typeorm";
import { User } from "../../../entity/User";
export interface PatientDetail {
email: string;
firstName: string;
lastName?: string;
vaccinationDate?: string;
covidVulnerabilityScore?: number;
isVaccinated: boolean;
}
interface ReturnType {
scheduled: PatientDetail[];
notScheduled: PatientDetail[];
vaccinated: PatientDetail[];
}
export const getRegisteredPatients = async (
adminEmail: string,
lastNumDays?: number,
nextNumDays?: number
): Promise<ReturnType> => {
const dbConnection = getConnection();
const patients: ReturnType = {
scheduled: [],
notScheduled: [],
vaccinated: [],
};
try {
let query = dbConnection
.getRepository(User)
.createQueryBuilder("user")
.where(`user.adminEmail = :adminEmail`, { adminEmail })
.andWhere(`user.vaccinationDate IS NOT NULL`);
if (lastNumDays && nextNumDays) {
query = query.andWhere(
new Brackets((qb) =>
qb
.where(
`TO_DATE(:currentDate, 'Dy Mon DD YYYY') - TO_DATE("vaccinationDate", 'Dy Mon DD YYYY') BETWEEN 0 AND :lastNumDays`,
{ currentDate: new Date().toDateString(), lastNumDays }
)
.orWhere(
`TO_DATE("vaccinationDate", 'Dy Mon DD YYYY') - TO_DATE(:currentDate, 'Dy Mon DD YYYY') BETWEEN 0 AND :nextNumDays`,
{ currentDate: new Date().toDateString(), nextNumDays }
)
)
);
} else if (lastNumDays) {
query = query.andWhere(
`TO_DATE(:currentDate, 'Dy Mon DD YYYY') - TO_DATE("vaccinationDate", 'Dy Mon DD YYYY') <= :lastNumDays`,
{ currentDate: new Date().toDateString(), lastNumDays }
);
} else if (nextNumDays) {
query = query.andWhere(
`TO_DATE("vaccinationDate", 'Dy Mon DD YYYY') - TO_DATE(:currentDate, 'Dy Mon DD YYYY') <= :nextNumDays`,
{ currentDate: new Date().toDateString(), nextNumDays }
);
}
query = query
.orderBy(`TO_DATE(user.vaccinationDate, 'Dy Mon DD YYYY')`)
.addOrderBy(`user.covidVulnerabilityScore`, "DESC");
const patientsData = await query.getMany();
patientsData.forEach(
({
email,
firstName,
lastName,
vaccinationDate,
covidVulnerabilityScore,
isVaccinated,
vaccinationTimeSlot,
location,
}) => {
const data = {
email,
firstName,
lastName,
vaccinationDate,
covidVulnerabilityScore,
vaccinationTimeSlot,
location,
isVaccinated: !!isVaccinated,
};
if (isVaccinated) {
patients.vaccinated.push(data);
} else if (vaccinationTimeSlot) {
patients.scheduled.push(data);
} else patients.notScheduled.push(data);
}
);
return patients;
} catch (error) {
return patients;
}
};
|
sgsonu/covid-vaccine-distribution
|
services/server/src/entity/PatientProfile.ts
|
<reponame>sgsonu/covid-vaccine-distribution<filename>services/server/src/entity/PatientProfile.ts
import { Column, Entity, OneToOne, PrimaryGeneratedColumn } from "typeorm";
import { User } from "./User";
// const formatDate = (): string => {
// const d = new Date();
// let month = "" + (d.getMonth() + 1),
// day = "" + d.getDate(),
// year = d.getFullYear();
// if (month.length < 2) month = "0" + month;
// if (day.length < 2) day = "0" + day;
// return [day, month, year].join("-");
// };
@Entity()
export class PatientProfile {
@PrimaryGeneratedColumn()
id?: number;
@Column()
sex: 1 | 0;
@Column()
patientType: 1 | 2;
@Column()
dateEntry: string;
@Column()
dateSymptoms: string;
@Column()
intubed: 1 | 0;
@Column()
pneumonia: 1 | 0;
@Column()
ageBand: number;
@Column()
pregnancy: 1 | 0;
@Column()
diabetes: 1 | 0;
@Column()
copd: 1 | 0;
@Column()
asthma: 1 | 0;
@Column()
inmsupr: 1 | 0;
@Column()
hypertension: 1 | 0;
@Column()
otherDisease: 1 | 0;
@Column()
cardiovascular: 1 | 0;
@Column()
obesity: 1 | 0;
@Column()
renalChronic: 1 | 0;
@Column()
tobacco: 1 | 0;
@Column()
contactOtherCovid: 1 | 0;
@Column({ nullable: true })
covidTestResult: 0 | 1 | 2;
@Column()
icu: 1 | 0;
@OneToOne(() => User, (user) => user.patientProfile, {
onDelete: "CASCADE",
onUpdate: "CASCADE",
})
user: User;
}
|
sgsonu/covid-vaccine-distribution
|
services/server/src/routers/auth/signUp/signUp.ts
|
<gh_stars>0
import { Request, Response, Router } from "express";
import { signUp } from "../../../models/auth/signUp";
import { validate } from "./validate";
export const signUpRouter = Router();
signUpRouter.post(
"/",
async (req: Request, res: Response): Promise<Response> => {
const errors: string[] = validate(req.body);
if (errors.length) return res.status(400).send({ errors });
try {
await signUp(req.body);
return res.status(200).send({ success: true });
} catch (error) {
error = error.message;
if (error.includes("duplicate key")) error = "User already exists";
return res.status(400).send({ errors: [error] });
}
}
);
|
sgsonu/covid-vaccine-distribution
|
services/server/src/index.ts
|
if (process.env.NODE_ENV === "development") {
const { config } = require("dotenv");
const devEnvironment = config();
if (devEnvironment.error) {
console.error(devEnvironment.error);
}
}
import "reflect-metadata";
import { createConnection } from "typeorm";
import { createRootUser } from "./models/utils/createRootUser";
import { server } from "./routers/server";
(async () => {
try {
await createConnection();
await createRootUser();
const PORT: number = +(process.env.PORT || 5000);
server.listen(PORT, () => console.log(`Server started on port ${PORT}...`));
} catch (error) {
console.error(error);
}
})();
|
sgsonu/covid-vaccine-distribution
|
services/server/src/models/su/registerAndDispatchVaccines/index.ts
|
import { Point } from "geojson";
import { getConnection } from "typeorm";
import { User } from "../../../entity/User";
import { sendMail } from "../../utils/sendMail";
const getVaccinationDate = (adminSUDist: number): string => {
let numDays = Math.ceil(adminSUDist / (1000 * 250));
if (!numDays) numDays = 1;
const vaccinationDate = new Date();
vaccinationDate.setDate(vaccinationDate.getDate() + numDays);
return vaccinationDate.toDateString();
};
export const registerAndDispatchVaccines = async (
numVaccines: number,
suLocation: Point
): Promise<boolean> => {
const dbConnection = getConnection();
try {
// Get patients with highest scores and also their respective nearest vaccination centers
const patients: {
adminSUDist: number;
adminEmail: string;
patientEmail: string;
}[] = await dbConnection.getRepository(User).query(
`SELECT
"nearestAdmin"."dist" AS "adminSUDist",
"nearestAdmin"."adminEmail" AS "adminEmail",
"patient"."email" AS "patientEmail"
FROM
"user" "patient"
INNER JOIN LATERAL
(SELECT
"admin"."email" AS "adminEmail",
ST_DISTANCE(
"admin"."location",
ST_GeomFromGeoJSON($1)::geography
) AS dist
FROM "user" "admin"
WHERE "admin"."isAdmin" = $2 AND "admin"."isSuperUser" = $3 AND "admin"."isRoot" = $4
ORDER BY "admin"."location" <-> patient.location ASC LIMIT 1
) "nearestAdmin"
ON TRUE
WHERE
"patient"."isVaccinated" = $5 AND
"patient"."vaccinationDate" IS NULL AND
"patient"."isRoot" = $6 AND
"patient"."isSuperUser" = $7 AND
"patient"."isAdmin" = $8 AND
"patient"."covidVulnerabilityScore" IS NOT NULL
ORDER BY "patient"."covidVulnerabilityScore" DESC
LIMIT $9`,
[
JSON.stringify(suLocation),
true,
false,
false,
false,
false,
false,
false,
numVaccines,
]
);
if (!patients.length) {
return true;
}
// Update patients' entries to include their vaccination center email and date of vaccination
await dbConnection
.getRepository(User)
.createQueryBuilder()
.update()
.set({
vaccinationDate: () => `"patientList"."vaccinationDate"`,
adminEmail: () =>
`"patientList"."adminEmail" FROM (VALUES ${patients
.map(
({ adminEmail, patientEmail, adminSUDist }) =>
`('${patientEmail}', '${adminEmail}', '${getVaccinationDate(
adminSUDist
)}')`
)
.join(
`,`
)} ) AS "patientList"("patientEmail", "adminEmail", "vaccinationDate")`,
})
.where(`"user"."email" = "patientList"."patientEmail"`)
.execute();
// Notify vaccination centers about the patients who have been registered vaccines
// asking the admin to schedule vaccination
// for those patients
const admins: {
[key: string]: { deliveryDate: string; patients: string[] };
} = {};
patients.forEach(({ adminEmail, patientEmail, adminSUDist }) => {
if (admins[adminEmail]) {
admins[adminEmail]!.patients.push(patientEmail);
}
if (!admins[adminEmail])
admins[adminEmail] = {
deliveryDate: getVaccinationDate(adminSUDist),
patients: [patientEmail],
};
});
Object.entries(admins).forEach(
([adminEmail, { deliveryDate, patients }]) => {
sendMail({
to: adminEmail,
subject: `Covid vaccine delivery`,
html: `<p>
<div>Hello!, We have dispatched Covid vaccines to your center for the following patients.</div>
<ol>
${patients.map((patient) => `<li>${patient}</li>`)}
</ol>
<div>The vaccines are going to arrive on ${deliveryDate}</div>
<div><a href="${
process.env.WEB
}/schedule_vaccination">Click here</a> to schedule vaccination for the above patients</div>
</p>`,
});
}
);
return true;
} catch (error) {
console.log(error);
throw new Error("Internal server error");
}
};
|
sgsonu/covid-vaccine-distribution
|
services/server/src/entity/User.ts
|
<filename>services/server/src/entity/User.ts
import { Point } from "geojson";
import {
Column,
Entity,
JoinColumn,
OneToOne,
PrimaryColumn,
PrimaryGeneratedColumn,
} from "typeorm";
import { PatientProfile } from "./PatientProfile";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({ unique: true })
@PrimaryColumn()
email: string;
@Column({ nullable: true })
verifyEmailHash?: string;
@Column()
firstName: string;
@Column({ nullable: true })
lastName?: string;
@Column()
password: string;
@Column({ default: false })
isVerified?: boolean;
@Column({ default: false })
isAdmin?: boolean;
@Column({ default: false })
isSuperUser?: boolean;
@Column({ default: false })
isRoot?: boolean;
@Column({ default: false })
isVaccinated?: boolean;
@Column({ nullable: true })
vaccinationDate?: string;
@Column({ nullable: true })
vaccinationTimeSlot?: string;
@Column({ nullable: true })
adminEmail?: string;
@Column("geography")
location: Point;
@Column({ nullable: true, type: "float8" })
covidVulnerabilityScore?: number;
@OneToOne(() => PatientProfile, (patientProfile) => patientProfile.user)
@JoinColumn()
patientProfile?: PatientProfile;
}
|
sgsonu/covid-vaccine-distribution
|
services/server/src/models/auth/verifyEmail/index.ts
|
<gh_stars>0
import { getConnection } from "typeorm";
import { User } from "../../../entity/User";
export const verifyEmail = async (
verifyEmailHash: string
): Promise<boolean> => {
const dbConnection = getConnection();
try {
await dbConnection
.getRepository(User)
.update(
{ verifyEmailHash, isVerified: false },
{ verifyEmailHash: undefined, isVerified: true }
);
} catch (error) {
throw new Error(error);
}
return true;
};
|
sgsonu/covid-vaccine-distribution
|
services/server/src/models/utils/createAccessToken.ts
|
import { sign } from "jsonwebtoken";
import { Payload } from "../../types/Payload";
export const createAccessToken = (payload: Payload): string =>
sign(payload, process.env.ACCESS_TOKEN_SECRET!, { expiresIn: 30 * 60 });
|
sgsonu/covid-vaccine-distribution
|
services/server/src/routers/root/experimental/signUpRandomAdminsUsers/index.ts
|
<gh_stars>0
import { Request, Response, Router } from "express";
import { signUpRandomAdminsUsers } from "../../../../models/root/experimental/signUpRandomAdminsUsers";
export const signUpRandomAdminsUsersRouter = Router();
signUpRandomAdminsUsersRouter.post(
"/",
async (req: Request, res: Response): Promise<Response> => {
const numAdmins = parseInt(req.body.numAdmins) || 20;
const numUsers = parseInt(req.body.numUsers) || 100;
try {
await signUpRandomAdminsUsers(numAdmins, numUsers);
return res.status(200).send({ success: true });
} catch (error) {
return res.status(500).send({ error: error.message });
}
}
);
|
sgsonu/covid-vaccine-distribution
|
services/server/src/models/su/signUpAdmin/index.ts
|
<gh_stars>0
import { signUp, SignUpProps } from "../../auth/signUp";
export const signUpAdmin = async (user: SignUpProps): Promise<boolean> => {
try {
return await signUp({ ...user, isAdmin: true });
} catch (error) {
throw new Error(error.message);
}
};
|
sgsonu/covid-vaccine-distribution
|
services/server/src/models/auth/refreshToken/index.ts
|
<filename>services/server/src/models/auth/refreshToken/index.ts<gh_stars>0
import { verify } from "jsonwebtoken";
import { getConnection } from "typeorm";
import { User } from "../../../entity/User";
import { Payload } from "../../../types/Payload";
import { createAccessToken } from "../../utils/createAccessToken";
export const refreshToken = async (token: string): Promise<string> => {
const dbConnection = getConnection();
try {
const payload = verify(token, process.env.REFRESH_TOKEN_SECRET!) as Payload;
const user = await dbConnection
.getRepository(User)
.findOne({ email: payload.email, isVerified: true });
if (!user) {
throw new Error("INVALID_USER");
}
return createAccessToken({
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
isAdmin: !!user.isAdmin,
isSuperUser: !!user.isSuperUser,
isProfileAdded:
user.covidVulnerabilityScore !== null &&
user.covidVulnerabilityScore !== undefined,
vaccinationDate: user.vaccinationDate,
location: user.location,
} as Payload);
} catch (error) {
throw new Error("INVALID_TOKEN");
}
};
|
sgsonu/covid-vaccine-distribution
|
services/server/src/models/admin/scheduleVaccination/index.ts
|
import { getConnection } from "typeorm";
import { User } from "../../../entity/User";
import { timeSlots } from "./timeSlots";
import { sendMail } from "../../utils/sendMail";
const getTimeSlot = (patientsPerSlot: number, idx: number): string =>
timeSlots[Math.floor(idx / patientsPerSlot) % timeSlots.length]!;
const getVaccinationDate = (
patientsPerSlot: number,
idx: number,
prevDate: Date
): string => {
const numDays = Math.floor(
Math.floor(idx / patientsPerSlot) / timeSlots.length
);
prevDate.setDate(prevDate.getDate() + numDays);
return prevDate.toDateString();
};
type ReturnType = {
email: string;
vaccinationDate: string;
vaccinationTimeSlot: string;
}[];
export const scheduleVaccination = async (
adminEmail: string,
patientsPerSlot: number
): Promise<ReturnType> => {
const dbConnection = getConnection();
try {
// Get patients who are registered under this vaccination center
// in descending order of covidVulnerabilityScore
const registeredPatients: {
email: string;
vaccinationDate: string;
}[] = await dbConnection
.getRepository(User)
.createQueryBuilder()
.select([`email`, `"vaccinationDate"`])
.where(`"adminEmail" = :adminEmail`, { adminEmail })
.andWhere(`"isVaccinated" = false`)
.andWhere(`"vaccinationTimeSlot" IS NULL`)
.orderBy(`"covidVulnerabilityScore"`, "DESC")
.getRawMany();
if (!registeredPatients.length) return [];
// Compute the time slot of the patients according to patientsPerSlot
// Also, new vaccinationDate if it has changed
const registeredPatientsDetails: ReturnType = registeredPatients.map(
({ email, vaccinationDate }, idx) => ({
email,
vaccinationDate: getVaccinationDate(
patientsPerSlot,
idx,
new Date(vaccinationDate)
),
vaccinationTimeSlot: getTimeSlot(patientsPerSlot, idx),
})
);
// Update the patients' entries with the new values computed
await dbConnection
.getRepository(User)
.createQueryBuilder()
.update()
.set({
vaccinationDate: () => `"patientList"."vaccinationDate"`,
vaccinationTimeSlot: () =>
`"patientList"."vaccinationTimeSlot" FROM (VALUES ${registeredPatientsDetails
.map(
({ email, vaccinationDate, vaccinationTimeSlot }) =>
`('${vaccinationTimeSlot}', '${email}', '${vaccinationDate}')`
)
.join(
`,`
)}) AS "patientList"("vaccinationTimeSlot", "email", "vaccinationDate")`,
})
.where(`"user"."email" = "patientList"."email"`)
.execute();
// Send mail to each patient about their
// date and time slot of vaccination
registeredPatientsDetails.forEach(
({ email, vaccinationDate, vaccinationTimeSlot }) => {
sendMail({
to: email,
subject: "Covid Vaccination schedule",
html: `<div>Hi ! Your covid vaccination has been scheduled on
<b>${new Date(
vaccinationDate
).toDateString()}</b> in the time slot <b>${vaccinationTimeSlot}</b>
</div>`,
});
}
);
return registeredPatientsDetails;
} catch (error) {
throw new Error("Internal server error");
}
};
|
sgsonu/covid-vaccine-distribution
|
services/server/src/routers/user/addProfile/validate.ts
|
<reponame>sgsonu/covid-vaccine-distribution<gh_stars>0
import { PatientProfile } from "../../../entity/PatientProfile";
import { isDate } from "../../utils/isDate";
export const validate = ({
ageBand,
asthma,
cardiovascular,
contactOtherCovid,
copd,
dateSymptoms,
covidTestResult,
diabetes,
hypertension,
icu,
inmsupr,
intubed,
obesity,
otherDisease,
patientType,
pneumonia,
pregnancy,
renalChronic,
sex,
tobacco,
}: PatientProfile): string[] => {
const errors: string[] = [];
if (ageBand === undefined || ageBand === null)
errors.push("ageBand required");
else if (isNaN(ageBand)) errors.push("Invalid ageBand");
Object.entries({
sex,
intubed,
pneumonia,
pregnancy,
diabetes,
copd,
asthma,
inmsupr,
hypertension,
otherDisease,
cardiovascular,
obesity,
renalChronic,
tobacco,
contactOtherCovid,
icu,
}).forEach(([field, value]) => {
if (value === undefined || value === null) errors.push(`${field} required`);
else if (isNaN(value) || (value != 1 && value != 0))
errors.push(`Invalid ${field}`);
});
if (covidTestResult === undefined || covidTestResult === null)
errors.push("covidTestResult required");
else if (
isNaN(covidTestResult) ||
(covidTestResult != 0 && covidTestResult != 1 && covidTestResult != 2)
)
errors.push("Invalid covidTestResult");
if (patientType === undefined || patientType === null)
errors.push(`patientType required`);
else if (isNaN(patientType) || (patientType != 1 && patientType != 2))
errors.push(`Invalid patientType`);
if (!dateSymptoms) errors.push("dateSymptoms required");
else if (!isDate(new Date(dateSymptoms))) errors.push("Invalid dateSymptoms");
return errors;
};
|
sgsonu/covid-vaccine-distribution
|
services/server/src/models/admin/getNonScheduledPatients/index.ts
|
<reponame>sgsonu/covid-vaccine-distribution<gh_stars>0
import { getConnection } from "typeorm";
import { User } from "../../../entity/User";
import { PatientDetail } from "../getRegisteredPatients";
interface NonScheduledPatientDetail extends Partial<PatientDetail> {}
export const getNonScheduledPatients = async (
adminEmail: string
): Promise<NonScheduledPatientDetail[]> => {
const dbConnection = getConnection();
try {
const patients = await dbConnection
.getRepository(User)
.createQueryBuilder("user")
.where(`user.adminEmail = :adminEmail`, { adminEmail })
.andWhere(`user.vaccinationDate IS NOT NULL`)
.andWhere(`user.vaccinationTimeSlot IS NULL`)
.orderBy(`user.vaccinationDate`, "ASC")
.orderBy(`user.covidVulnerabilityScore`, "DESC")
.getMany();
return patients.map(
({
email,
firstName,
lastName,
vaccinationDate,
covidVulnerabilityScore,
vaccinationTimeSlot,
location,
}) => ({
email,
firstName,
lastName,
vaccinationDate,
covidVulnerabilityScore,
vaccinationTimeSlot,
location,
})
);
} catch (error) {
return [];
}
};
|
sgsonu/covid-vaccine-distribution
|
services/server/src/routers/su/registerAndDispatchVaccines/index.ts
|
<reponame>sgsonu/covid-vaccine-distribution
import { Request, Response, Router } from "express";
import { registerAndDispatchVaccines } from "../../../models/su/registerAndDispatchVaccines";
export const registerAndDispatchVaccinesRouter = Router();
registerAndDispatchVaccinesRouter.post(
"/",
async (req: Request, res: Response): Promise<Response> => {
if (!req.body.numVaccines) {
return res.status(400).json({ error: "numVaccines required" });
} else if (isNaN(req.body.numVaccines))
return res.status(400).json({ error: "Invalid numVaccines" });
try {
await registerAndDispatchVaccines(
req.body.numVaccines,
req.user.location
);
return res.status(200).send({ success: true });
} catch (error) {
return res.status(500).send({ errors: [error.message] });
}
}
);
|
sgsonu/covid-vaccine-distribution
|
services/server/src/routers/auth/verifyEmail.ts
|
import { Request, Response, Router } from "express";
import { verifyEmail } from "../../models/auth/verifyEmail";
export const verifyEmailRouter = Router();
verifyEmailRouter.post(
"/",
async (req: Request, res: Response): Promise<Response> => {
const verifyEmailHash = req.body.verify_email_hash;
if (!verifyEmailRouter)
return res.status(404).send({ error: "Invalid url" });
try {
await verifyEmail(verifyEmailHash);
} catch (error) {
return res.send(400).send({ error: "Invalid url" });
}
return res.status(200).send({ success: true });
}
);
|
sgsonu/covid-vaccine-distribution
|
services/server/src/routers/server.ts
|
import express from "express";
import cookieParser from "cookie-parser";
import bodyParser from "body-parser";
import cors from "cors";
import { adminRouter } from "./admin";
import { verifyUser } from "../models/middlewares/verifyUser";
import { verifyAdmin } from "../models/middlewares/verifyAdmin";
import { verifySuperUser } from "../models/middlewares/verifySuperUser";
import { superUserRouter } from "./su";
import { userRouter } from "./user";
import { authRouter } from "./auth";
import { getAdminsRouter } from "./getAdmins";
import { getPatientTrendRouter } from "./getPatientTrend";
import { verifyRoot } from "../models/middlewares/verifyRoot";
import { rootRouter } from "./root";
export const server = express();
server.use(
cors({
credentials: true,
origin: `${process.env.WEB}`,
})
);
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json());
server.use(cookieParser());
server.use("/root", verifyUser, verifyRoot, rootRouter);
server.use("/admin", verifyUser, verifyAdmin, adminRouter);
server.use("/su", verifyUser, verifySuperUser, superUserRouter);
server.use("/user", verifyUser, userRouter);
server.use("/auth", authRouter);
server.use("/admins", getAdminsRouter);
server.use("/patient_trend", getPatientTrendRouter);
|
sgsonu/covid-vaccine-distribution
|
services/server/src/routers/admin/getNonScheduledPatients/index.ts
|
import { Request, Response, Router } from "express";
import { getNonScheduledPatients } from "../../../models/admin/getNonScheduledPatients";
export const getNonScheduledPatientsRouter = Router();
getNonScheduledPatientsRouter.get(
"/",
async (req: Request, res: Response): Promise<Response> => {
try {
const patients = await getNonScheduledPatients(req.user.email);
return res.status(200).send({ patients });
} catch (error) {
return res.status(500).send({ error: error.message });
}
}
);
|
sgsonu/covid-vaccine-distribution
|
services/server/src/routers/root/index.ts
|
<filename>services/server/src/routers/root/index.ts<gh_stars>0
import { Router } from "express";
import { experimentalRootRouter } from "./experimental";
import { signUpAdminRouter } from "./signUpAdmin";
import { signUpSuperUserRouter } from "./signUpSuperUser";
export const rootRouter = Router();
rootRouter.use("/experimental", experimentalRootRouter);
rootRouter.use("/admin", signUpAdminRouter);
rootRouter.use("/su", signUpSuperUserRouter);
|
sgsonu/covid-vaccine-distribution
|
services/server/src/models/auth/login/index.ts
|
import { compare } from "bcryptjs";
import { Response } from "express";
import { getConnection } from "typeorm";
import { User } from "../../../entity/User";
import { Payload } from "../../../types/Payload";
import { createAccessToken } from "../../utils/createAccessToken";
import { createRefreshToken } from "../../utils/createRefreshToken";
export interface LoginProps {
email: string;
password: string;
res: Response;
}
export const login = async ({
email,
password,
res,
}: LoginProps): Promise<{ accessToken: string }> => {
const dbConnection = getConnection();
const user = await dbConnection
.getRepository(User)
.findOne({ email, isVerified: true });
if (!user) {
throw new Error("Invalid user");
}
const isPasswordValid = await compare(password, user.password);
if (!isPasswordValid) {
throw new Error("Invalid password");
}
const payload: Payload = {
email,
firstName: user.firstName,
lastName: `${user.lastName}`,
isAdmin: !!user.isAdmin,
isSuperUser: !!user.isSuperUser,
isProfileAdded:
user.covidVulnerabilityScore !== null &&
user.covidVulnerabilityScore !== undefined,
vaccinationDate: user.vaccinationDate,
location: user.location,
};
const accessToken = createAccessToken(payload);
const refreshToken = createRefreshToken(payload);
res.cookie("jid", refreshToken, {
httpOnly: true,
path: "/auth/refresh_token",
});
return { accessToken };
};
|
sgsonu/covid-vaccine-distribution
|
services/server/src/routers/su/index.ts
|
import { Router } from "express";
import { getAdminsRouter } from "../getAdmins";
import { getRegisteredPatientsRouter } from "./getRegisteredPatients";
import { registerAndDispatchVaccinesRouter } from "./registerAndDispatchVaccines";
export const superUserRouter = Router();
superUserRouter.use(
"/register_and_dispatch_vaccines",
registerAndDispatchVaccinesRouter
);
superUserRouter.use("/admins", getAdminsRouter);
superUserRouter.use(
"/admins/:adminEmail/registered_patients",
getRegisteredPatientsRouter
);
|
sgsonu/covid-vaccine-distribution
|
services/server/src/models/utils/createRootUser/index.ts
|
import { getConnection } from "typeorm";
import { User } from "../../../entity/User";
import { signUp } from "../../auth/signUp";
export const createRootUser = async (): Promise<boolean> => {
const dbConnection = getConnection();
const rootEmail = process.env.ROOT_EMAIL;
if (!rootEmail) return false;
try {
let rootUser = await dbConnection
.getRepository(User)
.findOne({ email: rootEmail, isRoot: true });
if (rootUser) return false;
const rootPassword = process.env.ROOT_PASSWORD;
if (!rootPassword) return false;
await signUp({
firstName: "Root",
lastName: "User",
email: rootEmail,
password: <PASSWORD>,
lat: 12.9716,
lng: 77.5946,
isRoot: true,
});
return true;
} catch (error) {
console.error(error);
return false;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.