From a58212b384cc2c8d6de0b31c2a61e20f8a3275a8 Mon Sep 17 00:00:00 2001 From: dhzdhd Date: Tue, 31 Oct 2023 20:43:32 +0530 Subject: [PATCH] Fix backend --- .../users-permissions/strapi-server.js | 402 +++++++++--------- backend/src/index.ts | 94 ++-- 2 files changed, 248 insertions(+), 248 deletions(-) diff --git a/backend/src/extensions/users-permissions/strapi-server.js b/backend/src/extensions/users-permissions/strapi-server.js index abca5de..4862359 100644 --- a/backend/src/extensions/users-permissions/strapi-server.js +++ b/backend/src/extensions/users-permissions/strapi-server.js @@ -1,228 +1,248 @@ /* eslint-disable no-useless-escape */ -const crypto = require('crypto'); -const _ = require('lodash'); - +const crypto = require("crypto"); +const _ = require("lodash"); const { - validateCallbackBody, - validateRegisterBody, - validateSendEmailConfirmationBody, -} = require('../../../node_modules/@strapi/plugin-users-permissions/server/controllers/validation/auth'); - - -const utils = require('@strapi/utils'); -const { getService } = require('../../../node_modules/@strapi/plugin-users-permissions/server/utils'); + validateCallbackBody, + validateRegisterBody, + validateSendEmailConfirmationBody, +} = require("../../../node_modules/@strapi/plugin-users-permissions/server/controllers/validation/auth"); +const utils = require("@strapi/utils"); +const { + getService, +} = require("../../../node_modules/@strapi/plugin-users-permissions/server/utils"); const { getAbsoluteAdminUrl, getAbsoluteServerUrl, sanitize } = utils; const { ApplicationError, ValidationError } = utils.errors; -const emailRegExp = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; +const emailRegExp = + /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; const sanitizeUser = (user, ctx) => { - const { auth } = ctx.state; - const userSchema = strapi.getModel('plugin::users-permissions.user'); + const { auth } = ctx.state; + const userSchema = strapi.getModel("plugin::users-permissions.user"); - return sanitize.contentAPI.output(user, userSchema, { auth }); + return sanitize.contentAPI.output(user, userSchema, { auth }); }; module.exports = (plugin) => { + plugin.controllers.auth.callback = async (ctx) => { + const provider = ctx.params.provider || "local"; + const params = ctx.request.body; + + const store = strapi.store({ type: "plugin", name: "users-permissions" }); + + if (provider === "local") { + if (!_.get(await store.get({ key: "grant" }), "email.enabled")) { + throw new ApplicationError("This provider is disabled"); + } + + await validateCallbackBody(params); + + const query = { provider }; + + // Check if the provided identifier is an email or not. + const isEmail = emailRegExp.test(params.identifier); + + // Set the identifier to the appropriate query field. + if (isEmail) { + query.email = params.identifier.toLowerCase(); + } else { + query.username = params.identifier; + } + + // Check if the user exists. + const user = await strapi + .query("plugin::users-permissions.user") + .findOne({ where: query }); + + if (!user) { + throw new ValidationError("Invalid identifier or password"); + } + + if ( + _.get(await store.get({ key: "advanced" }), "email_confirmation") && + user.confirmed !== true + ) { + throw new ApplicationError("Your account email is not confirmed"); + } + + if (user.blocked === true) { + throw new ApplicationError( + "Your account has been blocked by an administrator" + ); + } + + // The user never authenticated with the `local` provider. + if (!user.password) { + throw new ApplicationError( + "This user never set a local password, please login with the provider used during account creation" + ); + } + + const validPassword = await getService("user").validatePassword( + params.password, + user.password + ); + + if (!validPassword) { + throw new ValidationError("Invalid identifier or password"); + } else { + const account = await strapi + .service("api::account.account") + .getUserAccount(user.id); + + ctx.send({ + jwt: getService("jwt").issue({ + id: user.id, + }), + user: { + ...(await sanitizeUser(user, ctx)), + balance: account.balance, + account: account.id, + }, + }); + } + } else { + if (!_.get(await store.get({ key: "grant" }), [provider, "enabled"])) { + throw new ApplicationError("This provider is disabled"); + } + + // Connect the user with the third-party provider. + try { + const user = await getService("providers").connect(provider, ctx.query); + //Import the account service to fetch account details + const account = await strapi + .service("api::account.account") + .getUserAccount(user.id); + + ctx.send({ + jwt: getService("jwt").issue({ id: user.id }), + user: { + ...(await sanitizeUser(user, ctx)), + balance: account.balance, + account: account.id, + }, + }); + } catch (error) { + throw new ApplicationError(error.message); + } + } + }; + plugin.controllers.auth.register = async (ctx) => { + const pluginStore = await strapi.store({ + type: "plugin", + name: "users-permissions", + }); + const settings = await pluginStore.get({ + key: "advanced", + }); + if (!settings.allow_register) { + throw new ApplicationError("Register action is currently disabled"); + } - plugin.controllers.auth.callback = async (ctx) => { - const provider = ctx.params.provider || 'local'; - const params = ctx.request.body; - - const store = strapi.store({ type: 'plugin', name: 'users-permissions' }); - - if (provider === 'local') { - if (!_.get(await store.get({ key: 'grant' }), 'email.enabled')) { - throw new ApplicationError('This provider is disabled'); - } - - await validateCallbackBody(params); - - const query = { provider }; - - // Check if the provided identifier is an email or not. - const isEmail = emailRegExp.test(params.identifier); - - // Set the identifier to the appropriate query field. - if (isEmail) { - query.email = params.identifier.toLowerCase(); - } else { - query.username = params.identifier; - } - - // Check if the user exists. - const user = await strapi.query('plugin::users-permissions.user').findOne({ where: query }); - - if (!user) { - throw new ValidationError('Invalid identifier or password'); - } - - if ( - _.get(await store.get({ key: 'advanced' }), 'email_confirmation') && - user.confirmed !== true - ) { - throw new ApplicationError('Your account email is not confirmed'); - } - - if (user.blocked === true) { - throw new ApplicationError('Your account has been blocked by an administrator'); - } - - // The user never authenticated with the `local` provider. - if (!user.password) { - throw new ApplicationError( - 'This user never set a local password, please login with the provider used during account creation' - ); - } - - const validPassword = await getService('user').validatePassword( - params.password, - user.password - ); - - if (!validPassword) { - throw new ValidationError('Invalid identifier or password'); - } else { - - - const account = await strapi.service('api::account.account').getUserAccount(user.id); - - ctx.send({ - jwt: getService('jwt').issue({ - id: user.id, - }), - user: { ...await sanitizeUser(user, ctx), balance: account.balance, account: account.id }, - - }); - } - } else { - if (!_.get(await store.get({ key: 'grant' }), [provider, 'enabled'])) { - throw new ApplicationError('This provider is disabled'); - } - - // Connect the user with the third-party provider. - try { - const user = await getService('providers').connect(provider, ctx.query); - //Import the account service to fetch account details - const account = await strapi.service('api::account.account').getUserAccount(user.id); - - ctx.send({ - jwt: getService('jwt').issue({ id: user.id }), - user: { ...await sanitizeUser(user, ctx), balance: account.balance, account: account.id }, - }); - - } catch (error) { - throw new ApplicationError(error.message); - } - } + const params = { + ..._.omit(ctx.request.body, [ + "confirmed", + "confirmationToken", + "resetPasswordToken", + ]), + provider: "local", }; + await validateRegisterBody(params); + // Throw an error if the password selected by the user + // contains more than three times the symbol '$'. + if (getService("user").isHashed(params.password)) { + throw new ValidationError( + "Your password cannot contain more than three times the symbol `$`" + ); + } - plugin.controllers.auth.register = async (ctx) => { - const pluginStore = await strapi.store({ type: 'plugin', name: 'users-permissions' }); - - const settings = await pluginStore.get({ - key: 'advanced', - }); - - if (!settings.allow_register) { - throw new ApplicationError('Register action is currently disabled'); - } + const role = await strapi + .query("plugin::users-permissions.role") + .findOne({ where: { type: settings.default_role } }); - const params = { - ..._.omit(ctx.request.body, ['confirmed', 'confirmationToken', 'resetPasswordToken']), - provider: 'local', - }; + if (!role) { + throw new ApplicationError("Impossible to find the default role"); + } - await validateRegisterBody(params); + // Check if the provided email is valid or not. + const isEmail = emailRegExp.test(params.email); - // Throw an error if the password selected by the user - // contains more than three times the symbol '$'. - if (getService('user').isHashed(params.password)) { - throw new ValidationError( - 'Your password cannot contain more than three times the symbol `$`' - ); - } + if (isEmail) { + params.email = params.email.toLowerCase(); + } else { + throw new ValidationError("Please provide a valid email address"); + } - const role = await strapi - .query('plugin::users-permissions.role') - .findOne({ where: { type: settings.default_role } }); + params.role = role.id; - if (!role) { - throw new ApplicationError('Impossible to find the default role'); - } + const user = await strapi.query("plugin::users-permissions.user").findOne({ + where: { email: params.email }, + }); - // Check if the provided email is valid or not. - const isEmail = emailRegExp.test(params.email); + if (user && user.provider === params.provider) { + throw new ApplicationError("Email is already taken"); + } - if (isEmail) { - params.email = params.email.toLowerCase(); - } else { - throw new ValidationError('Please provide a valid email address'); - } + if (user && user.provider !== params.provider && settings.unique_email) { + throw new ApplicationError("Email is already taken"); + } - params.role = role.id; + try { + if (!settings.email_confirmation) { + params.confirmed = true; + } - const user = await strapi.query('plugin::users-permissions.user').findOne({ - where: { email: params.email }, - }); + const user = await getService("user").add(params); + const account = await strapi + .service("api::account.account") + .newUser(user.id); - if (user && user.provider === params.provider) { - throw new ApplicationError('Email is already taken'); - } - - if (user && user.provider !== params.provider && settings.unique_email) { - throw new ApplicationError('Email is already taken'); - } + const sanitizedUser = await sanitizeUser(user, ctx); + if (settings.email_confirmation) { try { - if (!settings.email_confirmation) { - params.confirmed = true; - } - - const user = await getService('user').add(params); - const account = await strapi.service('api::account.account').newUser(user.id); - - const sanitizedUser = await sanitizeUser(user, ctx); - - if (settings.email_confirmation) { - try { - await getService('user').sendConfirmationEmail(sanitizedUser); - } catch (err) { - throw new ApplicationError(err.message); - } - - return ctx.send({ user: { ...sanitizedUser, balance: account.balance, account: account.id } }); - } - - const jwt = getService('jwt').issue(_.pick(user, ['id'])); - - - return ctx.send({ - jwt, - user: { ...sanitizedUser, balance: account.balance, account: account.id }, - }); + await getService("user").sendConfirmationEmail(sanitizedUser); } catch (err) { - if (_.includes(err.message, 'username')) { - throw new ApplicationError('Username already taken'); - } else if (_.includes(err.message, 'email')) { - throw new ApplicationError('Email already taken'); - } else { - strapi.log.error(err); - throw new ApplicationError('An error occurred during account creation'); - } + throw new ApplicationError(err.message); } - } - - - + return ctx.send({ + user: { + ...sanitizedUser, + balance: account.balance, + account: account.id, + }, + }); + } + + const jwt = getService("jwt").issue(_.pick(user, ["id"])); + + return ctx.send({ + jwt, + user: { + ...sanitizedUser, + balance: account.balance, + account: account.id, + }, + }); + } catch (err) { + if (_.includes(err.message, "username")) { + throw new ApplicationError("Username already taken"); + } else if (_.includes(err.message, "email")) { + throw new ApplicationError("Email already taken"); + } else { + strapi.log.error(err); + throw new ApplicationError("An error occurred during account creation"); + } + } + }; - return plugin; -}; \ No newline at end of file + return plugin; +}; diff --git a/backend/src/index.ts b/backend/src/index.ts index c231b02..4e08a9f 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -5,7 +5,7 @@ export default { * * This gives you an opportunity to extend code. */ - register(/*{ strapi }*/) { }, + register(/*{ strapi }*/) {}, /** * An asynchronous bootstrap function that runs before @@ -15,115 +15,95 @@ export default { * run jobs, or perform some special logic. */ bootstrap({ strapi }) { - - /* - + verify(token) */ let interval; - var io = require('socket.io')(strapi.server.httpServer, { + var io = require("socket.io")(strapi.server.httpServer, { cors: { - origin: "http://localhost:8080", - methods: ["GET", "POST"] - - } + origin: "*", + methods: ["GET", "POST"], + }, }); io.use(async (socket, next) => { - - try { - //Socket Authentication const result = await strapi.plugins[ - 'users-permissions' + "users-permissions" ].services.jwt.verify(socket.handshake.query.token); //Save the User ID to the socket connection socket.user = result.id; next(); } catch (error) { - - - console.log(error) + console.log(error); } - - - - }).on('connection', function (socket) { - - - - + }).on("connection", function (socket) { if (interval) { clearInterval(interval); } - console.log('a user connected'); + console.log("a user connected"); interval = setInterval(() => { - io.emit('serverTime', { time: new Date().getTime() }); // This will emit the event to all connected sockets - + io.emit("serverTime", { time: new Date().getTime() }); // This will emit the event to all connected sockets }, 1000); - - socket.on('loadBids', async (data) => { - + socket.on("loadBids", async (data) => { let params = data; try { - - let data = await strapi.service('api::product.product').loadBids(params.id); + let data = await strapi + .service("api::product.product") + .loadBids(params.id); io.emit("loadBids", data); - - } catch (error) { console.log(error); } - }); - - socket.on('makeBid', async (data) => { - + socket.on("makeBid", async (data) => { let params = data; try { + let found = await strapi.entityService.findOne( + "api::product.product", + params.product, + { fields: "bid_price" } + ); - - let found = await strapi.entityService.findOne('api::product.product', params.product, { fields: "bid_price" }); - - const account = await strapi.service('api::account.account').getUserAccount(socket.user); + const account = await strapi + .service("api::account.account") + .getUserAccount(socket.user); //Check whether user has enough more to make the bid - - - if (parseInt(account.balance) >= parseInt(found.bid_price)) { - await strapi.service('api::bid.bid').makeBid({ ...params, account: account.id }); - let product = await strapi.service('api::product.product').findAndUpdateBidPrice(found, params.bidValue); - let updatedProduct = await strapi.service('api::product.product').loadBids(product.id); + await strapi + .service("api::bid.bid") + .makeBid({ ...params, account: account.id }); + let product = await strapi + .service("api::product.product") + .findAndUpdateBidPrice(found, params.bidValue); + let updatedProduct = await strapi + .service("api::product.product") + .loadBids(product.id); io.emit("loadBids", updatedProduct); } else { - console.log("Balance Is low") + console.log("Balance Is low"); } - - - } catch (error) { console.log(error); } - }); - socket.on('disconnect', () => { - console.log('user disconnected'); + socket.on("disconnect", () => { + console.log("user disconnected"); clearInterval(interval); }); }); - strapi.io = io - + strapi.io = io; }, };