Breaking down mega-package. Hello auth-db 1.0.0!

This commit is contained in:
2023-05-23 14:15:34 -04:00
commit 2d341e5a9a
33 changed files with 641 additions and 0 deletions

37
lib/dao/create.ts Normal file
View File

@@ -0,0 +1,37 @@
import { DatabaseError } from '@mifi/services-common/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;
};