stackpress
Version:
Incept is a content management framework.
113 lines (112 loc) • 3.22 kB
JavaScript
import { email } from '../schema/assert';
import { hash, encrypt } from '../schema/helpers';
export async function signup(input, seed, engine, client) {
const errors = assert(input);
if (errors) {
return { code: 400, error: 'Invalid Parameters', errors };
}
const profile = client.model.profile;
const response = await profile.actions(engine, seed).create({
name: input.name,
type: input.type || 'person',
roles: input.roles || []
});
if (response.code !== 200) {
return response;
}
const results = response.results;
results.auth = {};
const actions = client.model.auth.actions(engine, seed);
if (input.email) {
const auth = await actions.create({
profileId: results.id,
type: 'email',
token: String(input.email),
secret: String(input.secret)
});
if (auth.code !== 200) {
return auth;
}
results.auth.email = auth.results;
}
if (input.phone) {
const auth = await actions.create({
profileId: results.id,
type: 'phone',
token: String(input.phone),
secret: String(input.secret)
});
if (auth.code !== 200) {
return auth;
}
results.auth.phone = auth.results;
}
if (input.username) {
const auth = await actions.create({
profileId: results.id,
type: 'username',
token: String(input.username),
secret: String(input.secret)
});
if (auth.code !== 200) {
return auth;
}
results.auth.username = auth.results;
}
return { ...response, results };
}
;
export async function signin(type, input, seed, engine, client) {
const actions = client.model.auth.actions(engine);
const token = encrypt(String(input[type]), seed);
const response = await actions.search({
columns: ['*', 'profile.*'],
filter: { type, token }
});
const results = response.results?.[0];
if (response.code !== 200) {
return { ...response, results };
}
else if (!results) {
return {
code: 404,
status: 'Not Found',
error: 'User Not Found'
};
}
const secret = hash(String(input.secret));
if (secret !== String(results.secret)) {
return {
code: 401,
status: 'Unauthorized',
error: 'Invalid Password'
};
}
await actions.update({ id: results.id }, {
consumed: new Date()
});
return {
code: 200,
status: 'OK',
results: results,
total: 1
};
}
;
export function assert(input) {
const errors = {};
if (!input.name) {
errors.name = 'Name is required';
}
if (!input.username && !input.email && !input.phone) {
errors.type = 'Username, email, or phone is required';
}
else if (input.email && !email(input.email)) {
errors.email = 'Invalid email';
}
if (!input.secret) {
errors.secret = 'Password is required';
}
return Object.keys(errors).length ? errors : null;
}
;