Breaking down mega-package. Hello auth-db 1.0.0!
This commit is contained in:
37
lib/dao/create.ts
Normal file
37
lib/dao/create.ts
Normal 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;
|
||||
};
|
||||
Reference in New Issue
Block a user