2026-04-16 21:40:18 +04:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
|
|
const yup = require('yup');
|
|
|
|
|
|
|
|
|
|
module.exports = (plugin) => {
|
|
|
|
|
/**
|
|
|
|
|
* Validation custom (équivalent Strapi)
|
|
|
|
|
*/
|
|
|
|
|
const registerSchema = yup.object({
|
|
|
|
|
username: yup.string().required(),
|
|
|
|
|
email: yup.string().email().required(),
|
|
|
|
|
password: yup.string().min(6).required(),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const validateRegisterBody = async (data) => {
|
|
|
|
|
try {
|
|
|
|
|
return await registerSchema.validate(data, {
|
|
|
|
|
abortEarly: false,
|
|
|
|
|
stripUnknown: true,
|
|
|
|
|
});
|
|
|
|
|
} catch (err) {
|
|
|
|
|
const message = err.errors.join(', ');
|
|
|
|
|
throw new Error(message);
|
|
|
|
|
}
|
2022-05-20 00:04:50 +04:00
|
|
|
};
|
2026-04-16 21:40:18 +04:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Override du controller register
|
|
|
|
|
*/
|
|
|
|
|
plugin.controllers.auth.register = async (ctx) => {
|
|
|
|
|
const { body } = ctx.request;
|
|
|
|
|
|
|
|
|
|
// 🔒 1. Validation
|
|
|
|
|
let params;
|
|
|
|
|
try {
|
|
|
|
|
params = await validateRegisterBody(body);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
return ctx.badRequest(err.message);
|
2022-05-20 00:04:50 +04:00
|
|
|
}
|
|
|
|
|
|
2026-04-16 21:40:18 +04:00
|
|
|
const { email, username, password } = params;
|
|
|
|
|
|
|
|
|
|
// 🔎 2. Vérifier si user existe déjà
|
|
|
|
|
const userService = strapi.service('plugin::users-permissions.user');
|
|
|
|
|
|
|
|
|
|
const existingUser = await userService.fetchAll({
|
|
|
|
|
filters: {
|
|
|
|
|
$or: [{ email }, { username }],
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (existingUser.length > 0) {
|
|
|
|
|
return ctx.badRequest('Email or Username already taken');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ⚙️ 3. Récupérer rôle "authenticated"
|
|
|
|
|
const role = await strapi
|
|
|
|
|
.query('plugin::users-permissions.role')
|
|
|
|
|
.findOne({ where: { type: 'authenticated' } });
|
|
|
|
|
|
|
|
|
|
if (!role) {
|
|
|
|
|
return ctx.badRequest('Default role not found');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 👤 4. Création user
|
|
|
|
|
const newUser = await userService.add({
|
|
|
|
|
username,
|
|
|
|
|
email,
|
|
|
|
|
password,
|
|
|
|
|
role: role.id,
|
|
|
|
|
confirmed: false,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// 🔑 5. Générer JWT
|
|
|
|
|
const jwtService = strapi.service('plugin::users-permissions.jwt');
|
|
|
|
|
|
|
|
|
|
const token = jwtService.issue({ id: newUser.id });
|
|
|
|
|
|
|
|
|
|
// 📤 6. Réponse
|
|
|
|
|
ctx.send({
|
|
|
|
|
jwt: token,
|
|
|
|
|
user: newUser,
|
|
|
|
|
});
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return plugin;
|
|
|
|
|
};
|