Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom Registration and Login API using Strapi?

I am using strapi to create APIs. I want to implement my own Registration API and Login API. I checked the documentation of strapi but i am not finding any custom API for this.

can any one help me on this?

like image 302
Sangram Badi Avatar asked Jan 27 '19 02:01

Sangram Badi


2 Answers

Same answer, but in more detail:

Strapi creates an Auth controller automatically for you and you can overwrite its behavior.

Copy the function(s) you need (e.g. register) from this file:

node_modules/strapi-plugin-users-permissions/controllers/Auth.js

to:

your_project_root/extensions/users-permissions/controllers/Auth.js

Now you can overwrite the behavior, e.g. pass a custom field inside the registration process {"myCustomField": "hello world"} and log it to the console:

async register(ctx) {
  ...
  ...
  // log the custom field
  console.log(params.myCustomField)

  // do something with it, e.g. check whether the value already exists
  // in another content type
  const itExists = await strapi.query('some-content-type').findOne({
    fieldName: params.myCustomField
  });
  if (!itExists) {
    return ctx.badRequest(...)
  } else {
    console.log('check success')
  }
}
like image 164
baermathias Avatar answered Sep 28 '22 06:09

baermathias


Actually, strapi creates an Auth controller to handle these requests. You can just change them to fit in your need.

The path to the controller is:

plugins/users-permissions/controllers/Auth.js

like image 25
capaci Avatar answered Sep 28 '22 05:09

capaci