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
All checks were successful
continuous-integration/drone/pr Build is passing
This commit is contained in:
62
src/dao/auth/create.ts
Normal file
62
src/dao/auth/create.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
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';
|
||||
|
||||
type CreateProps = Pick<AuthProps, 'record' | 'username'> & {
|
||||
externalId?: string;
|
||||
password?: string;
|
||||
publicKey?: string;
|
||||
};
|
||||
|
||||
export const create = async ({ record, username, externalId, password, publicKey }: CreateProps) => {
|
||||
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 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, 'record' | '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);
|
||||
Reference in New Issue
Block a user