38 lines
1.5 KiB
TypeScript
38 lines
1.5 KiB
TypeScript
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;
|
|
};
|