125 lines
2.7 KiB
JavaScript
125 lines
2.7 KiB
JavaScript
import Joi from 'joi';
|
|
import createHttpError from 'http-errors';
|
|
// import jwt from 'jsonwebtoken';
|
|
// import { uid } from 'rand-token';
|
|
|
|
// import { jwtKey } from '../config';
|
|
import { isEmpty } from '../helpers/object';
|
|
|
|
const schema = Joi.object({
|
|
username: Joi.string().min(3).max(30).required(),
|
|
password: Joi.string().required(),
|
|
}).with('username', 'password');
|
|
|
|
/**
|
|
* Create new user
|
|
* @param {Object} req
|
|
*
|
|
* @return {Object}
|
|
*/
|
|
export const createUser = async (req) => {
|
|
// INFO: On commence par vérifier que l'on reçoit bien un objet dans le body
|
|
if (isEmpty(req.body)) {
|
|
throw createHttpError(406);
|
|
}
|
|
|
|
// INFO: On vérifie ensuite que l'objet reçu correspond au schéma autorisé
|
|
const { value, error } = schema.validate(req.body, { abortEarly: false });
|
|
|
|
// INFO: Ce n'est pas le cas, on retourne une erreur
|
|
if (error) {
|
|
throw createHttpError(406, error);
|
|
}
|
|
|
|
console.log('Valeurs reçues:', value);
|
|
|
|
// INFO: Sinon on créé l'utilisateur
|
|
// const user = await models.Users.create(value);
|
|
|
|
// INFO: Puis on le retourne
|
|
// return user;
|
|
};
|
|
|
|
/**
|
|
* Auth user
|
|
* @param {Object} req
|
|
*
|
|
* @return {Object}
|
|
*/
|
|
export const authUser = async (req) => {
|
|
if (isEmpty(req.body)) {
|
|
throw createHttpError(406);
|
|
}
|
|
|
|
const { value, error } = schema.validate(req.body, { abortEarly: false });
|
|
|
|
if (error) {
|
|
throw createHttpError(406, error);
|
|
}
|
|
|
|
const { username, password } = value;
|
|
|
|
console.log('Valeurs reçues:', username, password);
|
|
|
|
// const user = await models.Users.findOne({
|
|
// where: {
|
|
// username,
|
|
// },
|
|
// });
|
|
|
|
// if (!user) {
|
|
// throw createHttpError(404);
|
|
// }
|
|
|
|
// if (!(await user.validPassword(password, user.password))) {
|
|
// throw createHttpError(401);
|
|
// }
|
|
|
|
// const payload = {
|
|
// id: user.id,
|
|
// token: uid(32),
|
|
// };
|
|
|
|
// const bearer = jwt.sign(payload, jwtKey, {
|
|
// expiresIn: '30d',
|
|
// });
|
|
|
|
// const date = new Date();
|
|
// date.setDate(date.getDate() + 30);
|
|
|
|
// return {
|
|
// bearer,
|
|
// expireAt: date,
|
|
// };
|
|
};
|
|
|
|
/**
|
|
* Update user profile (password)
|
|
* @param {Object} req
|
|
*
|
|
* @return {Object}
|
|
*/
|
|
export const updateMyProfile = async (req) => {
|
|
if (isEmpty(req.body)) {
|
|
throw createHttpError(406);
|
|
}
|
|
|
|
const schemaMyProfile = Joi.object({
|
|
password: Joi.string().required(),
|
|
});
|
|
|
|
const { value, error } = schemaMyProfile.validate(req.body, {
|
|
abortEarly: false,
|
|
});
|
|
|
|
if (error) {
|
|
throw createHttpError(406, error);
|
|
}
|
|
|
|
console.log('Valeurs reçues:', value);
|
|
|
|
// await req.user.update(value);
|
|
|
|
return {};
|
|
};
|