19 Commits

Author SHA1 Message Date
cc3e97d2e1 Working! 2023-06-01 00:09:32 -04:00
e9681fbc9a Merge branch 'main' into develop 2023-05-30 20:23:24 -04:00
4ce4b62fe5 Reduce duplicate code, move shit out to common package 2023-05-30 20:22:55 -04:00
64e1f53f4e Updates as I integrate 2023-05-30 17:44:50 -04:00
efb237885f Merge pull request 'Release 1.0.6' (#4) from develop into main
All checks were successful
continuous-integration/drone/tag Build is passing
Reviewed-on: #4
2023-05-26 21:49:25 +00:00
ec61e29fb0 Tweaks and mergefail fixes
All checks were successful
continuous-integration/drone/pr Build is passing
2023-05-26 17:46:37 -04:00
d97a7d7f95 Merge branch 'main' into develop
Some checks failed
continuous-integration/drone/pr Build is failing
# Conflicts:
#	.npmignore
#	lib/dao/deleteById.ts
#	lib/dao/readOneByRecord.ts
#	lib/dao/readOneByUsername.ts
#	package.json
#	src/dao/auth/deleteById.ts
#	src/dao/auth/readOneByRecord.ts
#	src/dao/auth/readOneByUsername.ts
#	src/dao/create.ts
#	src/dao/deleteById.ts
#	src/dao/readOneByRecord.ts
#	src/dao/readOneByUsername.ts
2023-05-26 17:44:52 -04:00
4bbe520366 Merge pull request 'Add DAO shit for Strategy model, added types for different ops, bump package version' (#3) from feature/ISS-3_-_WebAuthn_Support into develop
Some checks failed
continuous-integration/drone/pr Build is failing
Reviewed-on: #3
2023-05-26 21:40:07 +00:00
e657d09ae5 Add DAO shit for Strategy model, added types for different ops, bump package version
All checks were successful
continuous-integration/drone/pr Build is passing
2023-05-26 17:35:58 -04:00
08293e8c16 .npmignore updates 2023-05-24 13:08:49 -04:00
88562d01cd Restructuring the folders (#1)
Co-authored-by: mifi <badmf@mifi.dev>
Reviewed-on: #1
2023-05-24 16:48:47 +00:00
fdfd8b567a Last try before I force it...
All checks were successful
continuous-integration/drone/pr Build is passing
2023-05-24 12:44:01 -04:00
55c2274a4f Grrrr...
Some checks failed
continuous-integration/drone/pr Build is failing
2023-05-24 12:41:12 -04:00
7d40fdfe74 Bam!
Some checks failed
continuous-integration/drone/pr Build is failing
2023-05-24 12:39:37 -04:00
8e5092b943 Haha!
Some checks failed
continuous-integration/drone/pr Build is failing
2023-05-24 12:35:37 -04:00
35b89062e4 Prettier?
Some checks failed
continuous-integration/drone/pr Build is failing
2023-05-24 10:46:24 -04:00
65e30ba1c7 Prettier...
Some checks failed
continuous-integration/drone/pr Build is failing
2023-05-24 10:33:41 -04:00
40645f58e3 Oops... paths.
Some checks failed
continuous-integration/drone/pr Build is failing
2023-05-24 10:31:38 -04:00
7619899edc Restructuring the folders
Some checks failed
continuous-integration/drone/pr Build is failing
2023-05-24 10:24:15 -04:00
62 changed files with 1972 additions and 706 deletions

View File

@@ -7,9 +7,15 @@ workspace:
steps: steps:
- name: yarn install - name: yarn install
image: node:latest image: node:20-bullseye-slim
environment:
YARN_VERSION: 3.5.0
commands: commands:
- yarn set version stable
- yarn install - yarn install
volumes:
- name: yarnrc
path: /drone/auth/.yarnrc.yml
- name: Code Style Checks - name: Code Style Checks
image: node:latest image: node:latest
commands: commands:
@@ -37,6 +43,30 @@ steps:
status: status:
- success - success
- failure - failure
- name: Build
image: node:latest
commands:
- yarn build:production
- name: Send Build Status Notifications
image: plugins/webhook
settings:
urls: https://lab.mifi.dev/hooks/9p65zpagctgkmndo8nwwm4199r
content_type: application/json
template: |
{
"icon_url":"https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/198/freezing-face_1f976.png",
"text": "[{{ repo.name }} - Build # {{ build.number }}] Build package {{ build.status }} {{#success build.status}}:tada:{{else}}:poop:{{/success}}",
"username":"DroneBot"
}
when:
status:
- success
- failure
volumes:
- name: yarnrc
host:
path: /volume1/docker/.yarnrc.yml
trigger: trigger:
branch: branch:
@@ -54,14 +84,26 @@ workspace:
path: /drone/auth path: /drone/auth
steps: steps:
- name: Publish NPM - name: Build
image: node:20-alpine image: node:20-bullseye-slim
failure: ignore environment:
YARN_VERSION: 3.5.0
commands: commands:
- yarn publish -t ${DRONE_TAG} - yarn set version stable
- yarn install
- yarn build:production
volumes:
- name: yarnrc
path: /drone/auth/.yarnrc.yml
- name: Publish NPM
image: node:20-bullseye-slim
commands:
- yarn npm publish
volumes: volumes:
- name: npmrc - name: npmrc
path: /drone/auth/.npmrc path: /drone/auth/.npmrc
- name: yarnrc
path: /drone/auth/.yarnrc.yml
- name: Report NPM Publish Status - name: Report NPM Publish Status
image: plugins/webhook image: plugins/webhook
settings: settings:
@@ -82,6 +124,9 @@ volumes:
- name: npmrc - name: npmrc
host: host:
path: /volume1/docker/beethoven/labs-auth/.npmrc path: /volume1/docker/beethoven/labs-auth/.npmrc
- name: yarnrc
host:
path: /volume1/docker/.yarnrc.yml
depends_on: depends_on:
- Test Pipeline - Test Pipeline

19
.eslintrc.js Normal file
View File

@@ -0,0 +1,19 @@
/* eslint-env node */
module.exports = {
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:import/errors',
'plugin:prettier/recommended',
'prettier',
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
settings: {
'import/parsers': {
'@typescript-eslint/parser': ['.ts', '.tsx'],
},
'import/resolver': 'typescript',
},
root: true,
};

3
.gitignore vendored
View File

@@ -130,3 +130,6 @@ dist
.yarn/install-state.gz .yarn/install-state.gz
.pnp.* .pnp.*
# Project
lib/

10
.npmignore Normal file
View File

@@ -0,0 +1,10 @@
.build.yarnrc.yml
.drone.yml
.eslintrc*
.npmrc
.prettierrc*
.yarnrc.yml
babel.config.*
jest.config.*
tsconfig*.json
tslint.json

7
.prettierrc.js Normal file
View File

@@ -0,0 +1,7 @@
module.exports = {
parser: 'typescript',
printWidth: 120,
trailingComma: 'all',
tabWidth: 4,
singleQuote: true,
};

873
.yarn/releases/yarn-3.5.1.cjs vendored Executable file

File diff suppressed because one or more lines are too long

View File

@@ -1 +1,3 @@
nodeLinker: node-modules nodeLinker: node-modules
yarnPath: .yarn/releases/yarn-3.5.1.cjs

View File

@@ -1,17 +0,0 @@
import { Auth, Log } from '..';
import { Action } from '../constants/action';
import { getLoginToken } from '../utils/getLoginToken';
export const authenticate = async (username: string, password: string) => {
const doc = await Auth.findByUsername(username).catch();
if (!!doc && (await doc.authenticate(password))) {
Log.add(doc.id, Action.AUTHENTICATE);
return { ...doc, token: getLoginToken(doc) };
}
if (doc) {
Log.add(doc.id, Action.AUTHENTICATE_FAILURE);
}
return false;
};

View File

@@ -1,9 +0,0 @@
export enum Action {
AUTHENTICATE = 'AUTHENTICATE',
AUTHENTICATE_FAILURE = 'AUTHENTICATE_FAILURE',
CREATE = 'CREATE',
DELETE = 'DELETE',
RESET = 'RESET',
RESET_REQUEST = 'RESET_REQUEST',
UPDATE = 'UPDATE',
}

View File

@@ -1,8 +0,0 @@
export enum Status {
ACTIVE,
BLOCK_HARD,
BLOCK_SOFT,
DELETED,
INACTIVE,
UNVERIFIED,
}

View File

@@ -1,20 +0,0 @@
export const PACKAGE_NAME = '@mifi/auth';
export const PORT = process.env.PORT || 9000;
export const SESSION_KEY = process.env.SESSION_KEY || 'secret-key';
export const JWT_AUDIENCE = process.env.JWT_AUDIENCE || 'mifi.dev';
export const JWT_ISSUER = process.env.JWT_ISSUER || PACKAGE_NAME;
export const JWT_SECRET = process.env.JWT_SECRET || 'secret';
export const LOGIN_VALID_TIMEOUT = process.env.LOGIN_VALID_TIMEOUT || '12h'; // ###d|h|m
export const RESET_VALID_TIMEOUT = process.env.RESET_VALID_TIMEOUT || '15m'; // ###d|h|m
export const VERIFY_VALID_TIMEOUT = process.env.VERIFY_VALID_TIMEOUT || '60d'; // ###d|h|m
export const DEFAULT_TOKEN_DAYS = process.env.DEFAULT_TOKEN_DAYS || 365;
export const ROUTE_PREFIX = process.env.ROUTE_PREFIX || '/auth';
export const LOGIN_ROUTE = process.env.LOGIN_ROUTE || '/login';
export const RESET_ROUTE = process.env.RESET_ROUTE || '/reset';
export const VERIFICATION_ROUTE = process.env.VERIFICATION_ROUTE || '/verification';
export const REQUIRE_VERIFICATION = process.env.REQUIRE_VERIFICATION || true;

View File

@@ -1,12 +0,0 @@
export enum ErrorCodes {
RESET_REQUEST_DATA = 'RESET_REQUEST_DATA',
}
export const ErrorMessages = {
[ErrorCodes.RESET_REQUEST_DATA]: 'A valid username and password must be provided',
};
export const getErrorBody = (code: ErrorCodes) => ({
code,
message: ErrorMessages[code],
});

View File

@@ -1,7 +0,0 @@
export enum STRATEGIES {
LOCAL,
APPLE,
FACEBOOK,
FIDO2,
GOOGLE,
}

View File

@@ -1,4 +0,0 @@
export enum TokenType {
RESET = 'RESET',
VERIFICATION = 'VERIFICATION',
}

View File

@@ -1,37 +0,0 @@
import { DatabaseError } from '@mifi/services-common/lib/domain/errors/DatabaseError';
import { Auth, Log, Strategy, Token } from '..';
import { Auth as AuthProps } from '../schema/auth';
import { STRATEGIES } from '../constants/strategies';
import { REQUIRE_VERIFICATION } from '../constants/env';
import { TokenType } from '../constants/tokens';
import { Status } from '../constants/auth';
import { Action } from '../constants/action';
export const create = async ({ record, username, password }: AuthProps & { password: string }) => {
const status = REQUIRE_VERIFICATION ? Status.UNVERIFIED : Status.ACTIVE;
const doc = await Auth.create({
record,
status,
username,
}).catch((err) => {
throw new DatabaseError('failed to create user', { err });
});
if (doc) {
const strategy = await Strategy.create({ method: STRATEGIES.LOCAL, key: password, parent: doc._id }).catch(
(err) => {
throw new DatabaseError('failed to create strategy', { err });
},
);
if (strategy) {
doc.strategies.push(strategy._id);
await doc.save();
Log.add(doc._id, Action.CREATE);
return { doc, token: REQUIRE_VERIFICATION && (await Token.getToken(TokenType.VERIFICATION, doc._id)) };
}
await doc.deleteOne((err) => {
throw new DatabaseError('failed to remove invalid auth record', { err, doc });
});
}
return null;
};

View File

@@ -1,15 +0,0 @@
import { StringSchemaDefinition } from 'mongoose';
import { Auth, Log, Strategy, Token } from '..';
import { Status } from '../constants/auth';
import { Action } from '../constants/action';
export const deleteById = async (id: StringSchemaDefinition) => {
if (await Auth.findByIdAndUpdate(id, { status: Status.DELETED, strategies: [] }).catch()) {
await Strategy.deleteMany({ parent: id });
await Token.deleteMany({ auth: id });
Log.add(id, Action.DELETE);
return true;
}
return false;
};

View File

@@ -1,15 +0,0 @@
import { LOGIN_VALID_TIMEOUT, RESET_VALID_TIMEOUT, VERIFY_VALID_TIMEOUT } from '../constants/env';
import { TokenType } from '../constants/tokens';
import { parseTimeoutToMs } from '../utils/parseTimeoutToMs';
export const getDefaultExpiresFor = (type: TokenType | void) => {
if (type === TokenType.RESET) {
return Date.now() + parseTimeoutToMs(RESET_VALID_TIMEOUT);
}
if (type === TokenType.VERIFICATION) {
return Date.now() + parseTimeoutToMs(VERIFY_VALID_TIMEOUT);
}
return Date.now() + parseTimeoutToMs(LOGIN_VALID_TIMEOUT);
};

View File

@@ -1,11 +0,0 @@
import { sign } from '../utils/jwt';
import { LOGIN_VALID_TIMEOUT } from '../constants/env';
import { parseTimeoutToMs } from '../utils/parseTimeoutToMs';
import { AuthDocument } from '../schema/auth';
export const getLoginToken = ({ record: sub, status }: AuthDocument) =>
sign({
sub: <string>sub,
status,
exp: Date.now() + parseTimeoutToMs(LOGIN_VALID_TIMEOUT),
});

View File

@@ -1,35 +0,0 @@
import jwt from 'jsonwebtoken';
import { JWT_AUDIENCE, JWT_ISSUER, JWT_SECRET } from '../constants/env';
export interface TokenProps {
aud?: string;
exp?: number | Date;
iss?: string;
sub: string | null;
[key: string]: any;
}
export type SignProps = string | TokenProps | void;
export const sign = (props: SignProps) => {
const today = new Date();
const { sub = null, ...rest }: TokenProps =
typeof props === 'string' || typeof props === 'undefined' ? { sub: props || null } : props;
let { exp } = rest;
if (!exp) {
exp = new Date(today);
exp.setDate(today.getDate() + parseInt(process.env.JWT_DAYS_VALID as string));
exp = exp.getTime() / 1000;
}
return jwt.sign(
{
exp,
sub,
aud: rest.aud || JWT_AUDIENCE,
iat: today.getTime(),
iss: rest.iss || JWT_ISSUER,
},
JWT_SECRET,
);
};
export const verify = (token: string) => jwt.verify(token, JWT_SECRET);

View File

@@ -1,5 +0,0 @@
import { RESET_ROUTE, ROUTE_PREFIX, VERIFICATION_ROUTE } from '../constants/env';
export const getPasswordResetPath = (token: string) => `${ROUTE_PREFIX}${RESET_ROUTE}?t=${token}`;
export const getVerificationPath = (token: string) => `${ROUTE_PREFIX}${VERIFICATION_ROUTE}?t=${token}`;

View File

@@ -1,13 +0,0 @@
export const parseTimeoutToMs = (timeout: string) => {
const match = timeout.match(/(?<number>\d+)(?<unit>d|h|m)/gi)?.groups || {};
const { number, unit } = match;
switch (unit) {
case 'd':
return 1000 * 60 * 60 * 24 * parseInt(number);
case 'h':
return 1000 * 60 * 60 * parseInt(number);
case 'm':
default:
return 1000 * 60 * parseInt(number) || 1;
}
};

View File

@@ -1,11 +0,0 @@
import { sign } from './jwt';
import { LOGIN_VALID_TIMEOUT } from '../constants/env';
import { Status } from '../constants/auth';
import { parseTimeoutToMs } from './parseTimeoutToMs';
export const generateLoginToken = (sub: string, status: Status) =>
sign({
sub,
status,
exp: Date.now() + parseTimeoutToMs(LOGIN_VALID_TIMEOUT),
});

View File

@@ -1,16 +1,16 @@
{ {
"name": "@mifi/auth-db", "name": "@mifi/auth-db",
"version": "1.0.4", "version": "1.0.20",
"author": "mifi (Mike Fitzpatrick)", "author": "mifi (Mike Fitzpatrick)",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"build": "tsc", "build": "tsc",
"build:production": "tsc -p .", "build:production": "tsc -p ./tsconfig.production.json",
"format": "prettier:fix && lint:fix", "format": "prettier:fix && lint:fix",
"lint": "eslint --ext .ts,.tsx lib/", "lint": "eslint --ext .ts,.tsx src/",
"lint:fix": "eslint --fix --ext .ts,.tsx lib/", "lint:fix": "eslint --fix --ext .ts,.tsx src/",
"prettier": "prettier --check 'lib/**/*.ts'", "prettier": "prettier --check 'src/**/*.ts'",
"prettier:fix": "prettier --write 'lib/**/*.ts'", "prettier:fix": "prettier --write 'src/**/*.ts'",
"test": "jest --passWithNoTests" "test": "jest --passWithNoTests"
}, },
"devDependencies": { "devDependencies": {
@@ -35,10 +35,12 @@
"prettier-eslint": "^15.0.1", "prettier-eslint": "^15.0.1",
"prettier-eslint-cli": "^7.1.0", "prettier-eslint-cli": "^7.1.0",
"reflect-metadata": "^0.1.13", "reflect-metadata": "^0.1.13",
"ts-node": "^10.9.1",
"typescript": "^4.9.5" "typescript": "^4.9.5"
}, },
"dependencies": { "dependencies": {
"@mifi/services-common": "1.x.x", "@mifi/auth-common": "^1.0.15",
"@mifi/services-common": "^1.0.16",
"dotenv": "^16.0.3", "dotenv": "^16.0.3",
"jsonwebtoken": "^9.0.0", "jsonwebtoken": "^9.0.0",
"mongoose": "^6.9.2" "mongoose": "^6.9.2"
@@ -47,5 +49,6 @@
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://git.mifi.dev/mifi/auth-db.git" "url": "https://git.mifi.dev/mifi/auth-db.git"
} },
"packageManager": "yarn@3.5.1"
} }

18
src/api/authenticate.ts Normal file
View File

@@ -0,0 +1,18 @@
import { Action } from '@mifi/auth-common/lib/enums/action';
import { generateLoginToken } from '@mifi/auth-common/lib/utils/generateLoginToken';
import { Auth, Log } from '..';
export const authenticate = async (username: string, password: string, includeToken = false) => {
const doc = await Auth.findByUsername(username).catch();
if (!!doc && (await doc.authenticate(password))) {
Log.add(doc.id, Action.AUTHENTICATE);
return { sub: doc._id, record: doc.record, token: includeToken ? generateLoginToken(doc) : undefined };
}
if (doc) {
Log.add(doc.id, Action.AUTHENTICATE_FAILURE, { ...doc });
}
return false;
};

View File

@@ -1,4 +1,5 @@
import { StringSchemaDefinition } from 'mongoose'; import { StringSchemaDefinition } from 'mongoose';
import { Auth, Strategy } from '..'; import { Auth, Strategy } from '..';
export const deleteStrategy = async (id: StringSchemaDefinition) => { export const deleteStrategy = async (id: StringSchemaDefinition) => {

View File

@@ -1,7 +1,8 @@
import { Action } from '@mifi/auth-common/lib/enums/action';
import { TokenType } from '@mifi/auth-common/lib/enums/tokens';
import { readOneByUsername } from '../dao/readOneByUsername'; import { readOneByUsername } from '../dao/readOneByUsername';
import { Log, Token } from '..'; import { Log, Token } from '..';
import { TokenType } from '../constants/tokens';
import { Action } from '../constants/action';
export const resetPasswordGet = async (username: string) => { export const resetPasswordGet = async (username: string) => {
const doc = await readOneByUsername(username); const doc = await readOneByUsername(username);

View File

@@ -1,18 +1,22 @@
import { Types } from 'mongoose'; import { Types } from 'mongoose';
import { Log, Strategy, Token } from '..'; import { Action } from '@mifi/auth-common/lib/enums/action';
import { STRATEGIES } from '../constants/strategies'; import { STRATEGIES } from '@mifi/auth-common/lib/enums/strategies';
import { generateLoginToken } from '@mifi/auth-common/lib/utils/generateLoginToken';
import { AuthDocument } from '../schema/auth'; import { AuthDocument } from '../schema/auth';
import { getLoginToken } from '../utils/getLoginToken';
import { StrategyDocument } from '../schema/strategy'; import { StrategyDocument } from '../schema/strategy';
import { Action } from '../constants/action'; import { Log, Strategy, Token } from '..';
export const resetPasswordPost = async (token: string, password: string) => { export const resetPasswordPost = async (token: string, password: string) => {
const parentId = await Token.validateResetToken(token); const parentId = await Token.validateResetToken(token);
if (parentId) { if (parentId) {
let parent: AuthDocument; let parent: AuthDocument;
let strategy: StrategyDocument | null = await Strategy.findOne({ parent: parentId, method: STRATEGIES.LOCAL }); let strategy: StrategyDocument | null = await Strategy.findOne({
parent: parentId,
method: STRATEGIES.LOCAL,
});
if (strategy) { if (strategy) {
parent = await strategy.getAuthRecord(); parent = await strategy.getAuthRecord();
@@ -31,7 +35,7 @@ export const resetPasswordPost = async (token: string, password: string) => {
} }
Log.add(parent._id, Action.RESET); Log.add(parent._id, Action.RESET);
return { record: parent.record, token: getLoginToken(parent) }; return { record: parent.record, token: generateLoginToken(parent) };
} }
return false; return false;

View File

@@ -0,0 +1,4 @@
export const LOGIN_VALID_TIMEOUT = process.env.LOGIN_VALID_TIMEOUT || '12h'; // ###d|h|m
export const RESET_VALID_TIMEOUT = process.env.RESET_VALID_TIMEOUT || '15m'; // ###d|h|m
export const VERIFY_VALID_TIMEOUT = process.env.VERIFY_VALID_TIMEOUT || '60d'; // ###d|h|m
export const DEFAULT_TOKEN_DAYS = process.env.DEFAULT_TOKEN_DAYS || 365;

65
src/dao/auth/create.ts Normal file
View File

@@ -0,0 +1,65 @@
import { Action } from '@mifi/auth-common/lib/enums/action';
import { Status } from '@mifi/auth-common/lib/enums/status';
import { STRATEGIES } from '@mifi/auth-common/lib/enums/strategies';
import { TokenType } from '@mifi/auth-common/lib/enums/tokens';
import { REQUIRE_VERIFICATION } from '@mifi/auth-common/lib/settings';
import { DatabaseError } from '@mifi/services-common/lib/domain/errors/DatabaseError';
import { Auth as AuthProps } from '../../schema/auth';
import { Auth, Log, Strategy, Token } from '../..';
type CreateProps = Pick<AuthProps, 'username'> & {
externalId?: string;
handle?: AuthProps['handle'];
password?: string;
publicKey?: string;
record?: AuthProps['record'];
};
export const create = async ({ record, username, externalId, handle, password, publicKey }: CreateProps) => {
const status = REQUIRE_VERIFICATION ? Status.UNVERIFIED : Status.ACTIVE;
const doc = await Auth.create({
handle,
record,
status,
username,
}).catch((err) => {
throw new DatabaseError('failed to create user', { err });
});
if (doc) {
const method = externalId && publicKey ? STRATEGIES.FIDO2 : STRATEGIES.LOCAL;
const strategy = await Strategy.create({
externalId,
key: password || publicKey,
method,
parent: doc._id,
}).catch((err) => {
throw new DatabaseError(`failed to create strategy ${STRATEGIES[method]}`, { err });
});
if (strategy) {
doc.strategies.push(strategy._id);
await doc.save();
Log.add(doc._id, Action.CREATE);
return {
doc,
token:
method === STRATEGIES.LOCAL &&
REQUIRE_VERIFICATION &&
(await Token.getToken(TokenType.VERIFICATION, doc._id)),
};
}
await doc.deleteOne((err) => {
throw new DatabaseError('failed to remove invalid auth record', {
err,
doc,
});
});
}
return null;
};
export type Fido2UserProps = Pick<AuthProps, 'handle' | 'username'> & { externalId: string; publicKey: string };
export const createFido2User = (props: Fido2UserProps) => create(props);
export type LocalUserProps = Pick<AuthProps, 'record' | 'username'> & { password: string };
export const createLocalUser = (props: LocalUserProps) => create(props);

View File

@@ -0,0 +1,21 @@
import { StringSchemaDefinition } from 'mongoose';
import { Action } from '@mifi/auth-common/lib/enums/action';
import { Status } from '@mifi/auth-common/lib/enums/status';
import { Auth, Log, Strategy, Token } from '../..';
export const deleteById = async (id: StringSchemaDefinition) => {
if (
await Auth.findByIdAndUpdate(id, {
status: Status.DELETED,
strategies: [],
}).catch()
) {
await Strategy.deleteMany({ parent: id });
await Token.deleteMany({ auth: id });
Log.add(id, Action.DELETE);
return true;
}
return false;
};

View File

@@ -1,8 +1,9 @@
import { FilterQuery } from 'mongoose'; import { FilterQuery } from 'mongoose';
import { Auth } from '..'; import { Status } from '@mifi/auth-common/lib/enums/status';
import { Status } from '../constants/auth';
import { AuthDocument } from '../schema/auth'; import { Auth } from '../../model/auth';
import { AuthDocument } from '../../schema/auth';
export const readAll = async (query: FilterQuery<AuthDocument> = {}) => Auth.find(query); export const readAll = async (query: FilterQuery<AuthDocument> = {}) => Auth.find(query);

View File

@@ -1,5 +1,5 @@
import { Types } from 'mongoose'; import { Types } from 'mongoose';
import { Auth } from '..'; import { Auth } from '../../model/auth';
export const readOneById = async (id: Types.ObjectId) => Auth.findById(id); export const readOneById = async (id: Types.ObjectId) => Auth.findById(id);

View File

@@ -1,5 +1,5 @@
import { Types } from 'mongoose'; import { Types } from 'mongoose';
import { Auth } from '..'; import { Auth } from '../../model/auth';
export const readOneByRecord = async (record: Types.ObjectId) => Auth.findOne({ record }); export const readOneByRecord = async (record: Types.ObjectId) => Auth.findOne({ record });

View File

@@ -1,3 +1,3 @@
import { Auth } from '..'; import { Auth } from '../../model/auth';
export const readOneByUsername = async (username: string) => Auth.findOne({ username }); export const readOneByUsername = async (username: string) => Auth.findOne({ username });

3
src/dao/create.ts Normal file
View File

@@ -0,0 +1,3 @@
import { create } from './auth/create';
export { create };

3
src/dao/deleteById.ts Normal file
View File

@@ -0,0 +1,3 @@
import { deleteById } from './auth/deleteById';
export { deleteById };

3
src/dao/readAll.ts Normal file
View File

@@ -0,0 +1,3 @@
import { readAll } from './auth/readAll';
export { readAll };

3
src/dao/readOneById.ts Normal file
View File

@@ -0,0 +1,3 @@
import { readOneById } from './auth/readOneById';
export { readOneById };

View File

@@ -0,0 +1,3 @@
import { readOneByRecord } from './auth/readOneByRecord';
export { readOneByRecord };

View File

@@ -0,0 +1,3 @@
import { readOneByUsername } from './auth/readOneByUsername';
export { readOneByUsername };

View File

@@ -0,0 +1,24 @@
import { DatabaseError } from '@mifi/services-common/lib/domain/errors/DatabaseError';
import { Strategy } from '../../model/strategy';
import { Strategy as StrategyProps } from '../../schema/strategy';
const create = async ({ externalId, key, method, parent, profile }: StrategyProps) =>
Strategy.create({
externalId,
key,
method,
parent,
profile,
}).catch((err) => {
throw new DatabaseError(err, {
externalId: externalId || null,
key,
method,
parent,
profile: profile || null,
});
});
export const createFido2Strategy = (props: Omit<StrategyProps, 'profile'>) => create(props);
export const createLocalStrategy = (props: Omit<StrategyProps, 'externalId' | 'profile'>) => create(props);

View File

@@ -0,0 +1,8 @@
import { StringSchemaDefinition } from 'mongoose';
import { Strategy } from '../../model/strategy';
export const deleteById = async (id: StringSchemaDefinition) => {
const result = await Strategy.findByIdAndDelete(id).catch();
return !!result;
};

View File

@@ -0,0 +1,6 @@
import { FilterQuery } from 'mongoose';
import { Strategy } from '../../model/strategy';
import { StrategyDocument } from '../../schema/strategy';
export const readAll = async (query: FilterQuery<StrategyDocument> = {}) => Strategy.find(query);

View File

@@ -0,0 +1,7 @@
import { Strategy } from '../../model/strategy';
import { AuthDocument } from '../../schema/auth';
export const readOneByExternalId = async (externalId: string, populate = false) =>
populate
? Strategy.findOne({ externalId }).populate<{ parent: AuthDocument }>('parent')
: Strategy.findOne({ externalId });

View File

@@ -0,0 +1,5 @@
import { Types } from 'mongoose';
import { Strategy } from '../../model/strategy';
export const readOneById = async (id: Types.ObjectId) => Strategy.findById(id);

View File

@@ -0,0 +1,8 @@
import { Types } from 'mongoose';
import { STRATEGIES } from '@mifi/auth-common/lib/enums/strategies';
import { Strategy } from '../../model/strategy';
export const readOneByParentAndMethod = async (parent: Types.ObjectId, method: STRATEGIES) =>
Strategy.findOne({ method, parent });

View File

@@ -1,12 +1,14 @@
import { Document, InferSchemaType, Model, Schema, StringSchemaDefinition, Types } from 'mongoose'; import { Document, InferSchemaType, Model, Schema, StringSchemaDefinition, Types } from 'mongoose';
import { Status } from '../constants/auth'; import { Status } from '@mifi/auth-common/lib/enums/status';
import { STRATEGIES } from '@mifi/auth-common/lib/enums/strategies';
import { COLL_STRATEGY } from '../constants/db'; import { COLL_STRATEGY } from '../constants/db';
import { STRATEGIES } from '../constants/strategies';
import { StrategyDocument } from './strategy';
import { verify } from '../utils/password'; import { verify } from '../utils/password';
import { StrategyDocument } from './strategy';
export interface Auth { export interface Auth {
handle?: string;
is2FA?: boolean; is2FA?: boolean;
record: StringSchemaDefinition; record: StringSchemaDefinition;
username: string; username: string;
@@ -35,9 +37,15 @@ export interface AuthModel extends Model<AuthDocument> {
export const AuthSchema = new Schema<AuthDocument, AuthModel>( export const AuthSchema = new Schema<AuthDocument, AuthModel>(
{ {
handle: { type: String },
is2FA: { type: Boolean, default: false }, is2FA: { type: Boolean, default: false },
record: { type: Types.ObjectId, unique: true }, record: { type: Types.ObjectId, unique: true },
status: { type: Number, enum: Status, default: Status.UNVERIFIED, index: true }, status: {
type: Number,
enum: Status,
default: Status.UNVERIFIED,
index: true,
},
strategies: [{ type: Types.ObjectId, ref: COLL_STRATEGY, default: [] }], strategies: [{ type: Types.ObjectId, ref: COLL_STRATEGY, default: [] }],
username: { type: String, required: true, unique: true }, username: { type: String, required: true, unique: true },
}, },

View File

@@ -1,9 +1,8 @@
import { InferSchemaType, Model, Schema, StringSchemaDefinition, Types } from 'mongoose'; import { InferSchemaType, Model, Schema, StringSchemaDefinition, Types } from 'mongoose';
import { Action } from '@mifi/auth-common/lib/enums/action';
import { Payload } from '@mifi/services-common/lib/types/Payload'; import { Payload } from '@mifi/services-common/lib/types/Payload';
import { Action } from '../constants/action';
export interface Log { export interface Log {
action: Action; action: Action;
auth: StringSchemaDefinition; auth: StringSchemaDefinition;

View File

@@ -1,6 +1,7 @@
import { Document, InferSchemaType, Model, Schema, StringSchemaDefinition, Types } from 'mongoose'; import { Document, InferSchemaType, Model, Schema, StringSchemaDefinition, Types } from 'mongoose';
import { STRATEGIES } from '../constants/strategies'; import { STRATEGIES } from '@mifi/auth-common/lib/enums/strategies';
import { encrypt } from '../utils/password'; import { encrypt } from '../utils/password';
import { COLL_AUTH } from '../constants/db'; import { COLL_AUTH } from '../constants/db';
import { AuthDocument } from './auth'; import { AuthDocument } from './auth';

View File

@@ -1,8 +1,9 @@
import { InferSchemaType, Model, Schema, StringSchemaDefinition, Types } from 'mongoose'; import { InferSchemaType, Model, Schema, StringSchemaDefinition, Types } from 'mongoose';
import { TokenType } from '../constants/tokens'; import { TokenType } from '@mifi/auth-common/lib/enums/tokens';
import { getDefaultExpiresFor } from '../utils/getDefaultExpiresFor'; import { getDefaultExpiresFor } from '@mifi/auth-common/lib/helpers/getDefaultExpiresFor';
import { sign, verify } from '../utils/jwt'; import { sign, verify } from '@mifi/auth-common/lib/utils/jwt';
import { SignProps } from '@mifi/auth-common/lib/utils/jwt/sign';
export interface Token { export interface Token {
auth: StringSchemaDefinition; auth: StringSchemaDefinition;
@@ -30,7 +31,9 @@ export const TokenSchema = new Schema<Token, TokenModel>(
TokenSchema.statics = { TokenSchema.statics = {
async cleanupExpiredTokens() { async cleanupExpiredTokens() {
const { acknowledged, deletedCount } = await this.deleteMany({ expires: { $lte: Date.now() } }); const { acknowledged, deletedCount } = await this.deleteMany({
expires: { $lte: Date.now() },
});
return { success: acknowledged, deletedCount }; return { success: acknowledged, deletedCount };
}, },
@@ -40,11 +43,15 @@ TokenSchema.statics = {
await existing.deleteOne(); await existing.deleteOne();
} }
const doc = await this.create({ type, auth, expires: expires || getDefaultExpiresFor(type) }); const doc = await this.create({
type,
auth,
expires: expires || getDefaultExpiresFor(type),
});
return sign({ return sign({
sub: `${doc._id}`, sub: `${doc._id}`,
exp: doc.expires, exp: doc.expires,
}); } as SignProps);
}, },
async validateResetToken(token: string) { async validateResetToken(token: string) {

View File

@@ -5,8 +5,3 @@ export const encrypt = (password: string) => {
const hash = pbkdf2Sync(password, salt, 10000, 512, 'sha512').toString('hex'); const hash = pbkdf2Sync(password, salt, 10000, 512, 'sha512').toString('hex');
return `${salt}:${hash}`; return `${salt}:${hash}`;
}; };
export const verify = (test: string, secret: string) => {
const [salt, hash] = secret.split(':');
return pbkdf2Sync(test, salt, 10000, 512, 'sha512').toString('hex') === hash;
};

View File

@@ -0,0 +1,4 @@
import { encrypt } from './encrypt';
import { verify } from './verify';
export { encrypt, verify };

View File

@@ -0,0 +1,6 @@
import { pbkdf2Sync } from 'crypto';
export const verify = (test: string, secret: string) => {
const [salt, hash] = secret.split(':');
return pbkdf2Sync(test, salt, 10000, 512, 'sha512').toString('hex') === hash;
};

View File

@@ -2,11 +2,16 @@
"extends": "@tsconfig/node16/tsconfig.json", "extends": "@tsconfig/node16/tsconfig.json",
"compilerOptions": { "compilerOptions": {
"allowSyntheticDefaultImports": true, "allowSyntheticDefaultImports": true,
"declaration": true,
"experimentalDecorators": true, "experimentalDecorators": true,
"emitDecoratorMetadata": true, "emitDecoratorMetadata": true,
"noImplicitAny": true, "noImplicitAny": true,
"outDir": "./dist/", "outDir": "lib/",
"rootDirs": ["lib"], "rootDirs": ["./", "src/"],
"sourceMap": true "strict": true,
} "esModuleInterop": true,
"sourceMap": true,
"removeComments": false
},
"include": ["src"]
} }

17
tsconfig.production.json Normal file
View File

@@ -0,0 +1,17 @@
{
"extends": "@tsconfig/node16/tsconfig.json",
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"declaration": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"noImplicitAny": true,
"outDir": "lib/",
"rootDirs": ["./", "src/"],
"strict": true,
"esModuleInterop": true,
"sourceMap": true,
"removeComments": false
},
"include": ["src"]
}

1166
yarn.lock

File diff suppressed because it is too large Load Diff