Strapi: Enhancing User Experience with Unique Passwordless Customization Services

I have been attempting to modify the "passwordless" strapi plugin in order to generate verification codes consisting exclusively of digits. To achieve this, I need to override the createToken function within the plugin's service.

Following the instructions provided in the Strapi documentation, I created a folder for the plugin within the extensions directory. Inside this folder (strapi-plugin-passwordless), I added a file called strapi-server.js where I exported a function:

module.exports = (plugin) => {
  plugin.services.passwordless.createToken = async (email, context) => {
    const settings = await this.settings();
    const tokensService = strapi.query("plugin::passwordless.token");
    tokensService.update({ where: { email }, data: { is_active: false } });
    const body = customAlphabet("1234567890", 6);

    const tokenInfo = {
      email,
      body,
      context: JSON.stringify(context),
    };
    return tokensService.create({ data: tokenInfo });
  };

  return plugin;
};

The only distinction between the original createToken function and my customized version is that the variable "body" consists of six digits.

Unfortunately, when running Strapi, it does not execute this modified function; instead, it continues to use the original one found in the node_modules directory. I'm uncertain as to what mistake I might be making. Any suggestions?

Answer №1

While working on customizing Strapi's Passwordless plugin, I came across a similar issue and found a solution that could benefit others in the same situation.

To successfully modify the functionality of the service within the Passwordless plugin, it is important to understand that the service is not just a basic object but actually a function that returns the service object.

const customizePasswordless = (plugin) => {
  // Obtain the original passwordlessFactory function
  const originalPasswordlessFactory = plugin.services.passwordless;

  // Override the passwordless service
  plugin.services.passwordless = function (...args) {
    // Extend the original passwordlessFactory function
    return {
      ...originalPasswordlessFactory(...args),
      async createToken(email, context) {
        const settings = await this.settings();
        const { token_length = 20, stays_valid = false } = settings;

        await strapi
          .query('plugin::passwordless.token')
          .update({ where: { email }, data: { is_active: false } });

        const body = generateRandomToken(token_length);
        const tokenInfo = {
          email,
          body,
          stays_valid,
          context: JSON.stringify(context),
        };

        return strapi
          .query('plugin::passwordless.token')
          .create({ data: tokenInfo });
      },
    };
  };

  return plugin;
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Locating the ASP.NET validator's Control with the help of JQUERY or basic Javascript

On my webpage, I have several textboxes with corresponding ASP.NET validators for validation. I know that I can validate all the validators using a JavaScript function: Page_ClientValidate("myvalidators") where "myvalidators" is the group name of my val ...

AngularJS: Unable to preserve the data

I'm currently working on an issue with saving updated functions using angularJS. I've managed to edit the data and update it on the database side, but the changes aren't reflecting on the frontend side unless I logout and login again. I need ...

Error: Requested URLs must be absolute and valid

Encountering an error while using the latest version of openid-client in a next-js application. Unhandled Runtime Error TypeError: only valid absolute URLs can be requested 3 | 4 | const oidcConfig = async () => { > 5 | const issuer = await I ...

Is there a way to customize the appearance of a MUI5 Tooltip using emotion?

I went through the information in this Stack Overflow post and experimented with the styled method. The code snippet I used is as follows: import * as React from 'react'; import { styled } from '@mui/material/styles'; import Tooltip, { ...

"There seems to be an issue with the backend functionality on Heroku following the

My backend stops running on Heroku after deployment. The console shows an Axios error. enter image description here When I run the app locally (without changing the code), no errors occur. However, currently, I can only access the frontend home page and ...

What is the best way to modify the state of a nested component?

I am facing a challenge in my React project where I have two buttons in my App.js. When either of the buttons is clicked, I want to change the current state (list) to display in descending order based on the button pressed (order by date or order by upvo ...

Is it necessary to utilize a npm git command in order to incorporate git into projects?

Is it necessary to run npm i -g git in order to use git in a VSC project? I recently downloaded git from the official website for my projects and want to confirm. I haven't tested extensively yet because I just completed a factory reset due to an SSL ...

How to retrieve the width of a document using jQuery?

Having a strange issue with determining the document width using $(document).width() during $(window).load and $(window).resize. The problem arises when the browser is initially full screen and then resized to a narrower width, causing content to require ...

Wind - Best practices for managing the status of multiple entities within a single display prior to executing the save changes function

In my system, there are three main entities: Project, Attachment, and Messages. A project can have multiple attachments and messages associated with it. The issue arises on the project detail view, where I display the project's messages and any attac ...

Unable to globally install @angular/cli using Node.js on Red Hat software collection

After installing node.js 8 from Red Hat Software Collection (rh-nodejs8), I encountered an issue where I couldn't globally install TypeScript or @Angular/CLI because my bash session was restricted by scl-utils, requiring admin rights for global instal ...

Exploring Authorization Methods in NodeJS with Mongoose Integration

I am currently developing a NodeJS/express application that utilizes passportJS for user authentication. My goal is to restrict access to certain models within my app only to admin users. I was considering adding an isAdmin boolean field to my user model, ...

Extract the links from the database using AngularJS

Currently, I am utilizing Laravel 5 for the backend and Angular.js for the frontend. The application operates solely through ajax requests. In my view, I have static links that are always visible on any page. Here is an example of how they are displayed: ...

Guide to sending API requests from a React client to an Express server hosted on Heroku

I've been grappling with deploying a Twitch-like application using a combination of react, redux, node media server, and json server module to Heroku. One roadblock I keep hitting is when attempting to establish a connection between my react client an ...

What is the process for extracting information from a middleware within a Next.js framework?

I have been working on developing an authentication system using JWT in Next.js. In order to achieve this, I created a middleware that can validate the JWT token and establish an authentication process as shown below: export default function middleware(req ...

Tips for using Angular's formatDate function to format dates

I am attempting to achieve a specific format using Angular's formatDate "2019-01-01T00:00:00Z" Here is the code I am using: formatDate( '2019-01-01', 'yyyy-MM-ddT00:00:00Z', 'en-US' ) The output I am getting is ...

Encountering a problem with `npm install` in Github Actions

One of the tasks in my workflow is to install npm packages using the command npm install, but unfortunately I am encountering an error that I cannot seem to understand. The specific error message is displayed below, and I am at a loss on how to resolve it. ...

Display JSON information in a table using AngularJS

As I delve back into an old project, I've encountered a hurdle. My goal is to display some data in a table, but I seem to have forgotten the intricacies of working with JSON objects and Angular. The API response I'm receiving looks something lik ...

Tips for confirming a date format within an Angular application

Recently, I've been diving into the world of Angular Validations to ensure pattern matching and field requirements are met in my projects. Despite finding numerous resources online on how to implement this feature, I've encountered some challenge ...

Checkbox in Angular FormGroup not triggering touched state

There seems to be an issue with the Angular form when checking if the form is touched, especially in relation to a checkbox element. Despite the value of the checkbox changing on click, I am seeing !newDeviceGroup.touched = true. I'm not quite sure wh ...

I'm curious if anyone has tried implementing delta compression for JSON data on Android devices

In an effort to minimize the large file sizes of JSON data used in our Android native application, I have been exploring various optimization techniques. My research has pointed me towards potential solutions for JSON optimization: 1) JSON minimization ...