How to create custom Registration and Login API using Strapi? - javascript

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?

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')
}
}

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

in order to create custom users-permissons apis on server side you have to create
src/extensions/users-permissions/strapi-server.js
and in that file can write or override existing user-permissions plugin apis
here is the example for users/me
const _ = require('lodash');
module.exports = (plugin) => {
const getController = name => {
return strapi.plugins['users-permissions'].controller(name);
};
// Create the new controller
plugin.controllers.user.me = async (ctx) => {
const user = ctx.state.user;
// User has to be logged in to update themselves
if (!user) {
return ctx.unauthorized();
}
console.log('calling about meeeeeeeeeee------')
return;
};
// Add the custom route
plugin.routes['content-api'].routes.unshift({
method: 'GET',
path: '/users/me',
handler: 'user.me',
config: {
prefix: '',
}
});
return plugin;
};

Related

How to delete child object in Strapi

I used this topic to delete upload related to articles and it work :
How to delete file from upload folder in strapi?
Now i want a cascade deletion. For when i delete a project, articles and upload will deleted also.
Somebody know how to delete a project which will delete an article & upload file ?
This code work to delete a project and children but not the file. And if i try to delete just an article, the controller is called and the file is deleted.
/api/projects/controllers/projects.js
module.exports = {
async delete(ctx) {
const { id } = ctx.params;
const project = await strapi.services.projects.delete({ id });
if (project){
for (let article of project.articles) {
strapi.services.articles.delete({ 'id' : article._id } );
}
}
return sanitizeEntity(project, { model: strapi.models.projects });
}
/api/articles/services/articles.js
delete(params) {
return strapi.query('articles').delete(params);
}
/api/articles/controllers/article.js
module.exports = {
async delete(ctx) {
const { id } = ctx.params;
const entity = await strapi.services.articles.delete({ id });
if (entity) {
strapi.plugins.upload.services.upload.remove(entity.articleFile);
}
return sanitizeEntity(entity, { model: strapi.models.articles });
}
}
The controller is called when i used the url in API like that :
DELETE http://localhost:port/banners/<project_ID>
The strapi.services.xxx.delete is called in the code
Actually you remove articles files only when you pass into your article controller. But in project controller context, you never remove files.
To fix it, remove article files into the article service.
/api/articles/services/articles.js
async delete(params) {
const entity = await strapi.query('articles').delete(params);
if (entity) {
await strapi.plugins.upload.services.upload.remove(entity.articleFile);
}
return entity;
}
/api/articles/controllers/article.js
module.exports = {
async delete(ctx) {
const { id } = ctx.params;
const entity = await strapi.services.articles.delete({ id });
// here articles files have been deleted by services.articles.delete
return sanitizeEntity(entity, { model: strapi.models.articles });
}
}
According to strapi concepts :
Services are a set of reusable functions. They are particularly useful to respect the DRY (don’t repeat yourself) programming concept and to simplify controllers logic.
https://strapi.io/documentation/v3.x/concepts/services.html#concept
Controllers are JavaScript files which contain a set of methods called actions reached by the client according to the requested route. It means that every time a client requests the route, the action performs the business logic coded and sends back the response. They represent the C in the MVC pattern. In most cases, the controllers will contain the bulk of a project's business logic.
https://strapi.io/documentation/v3.x/concepts/controllers.htm

SAPUI5 mock server doesn't receive requests

I didn't find a solution for this problem. I'm currently working with the CRUD Master-Detail Application WebIDE template and added some custom functions with OData calls. When running the app with mock server it loads the mock data. So far so good. But if I send a read request to the mock server it throws a 404 not found error.
Request URL
https://webidetesting[...].dispatcher.hana.ondemand.com/here/goes/your/serviceurl/MyEntity(12345)
Here's the mock server part in my index file flpSandboxMockServer.html:
<script>
sap.ui.getCore().attachInit(function() {
sap.ui.require([
"my/project/localService/mockserver"
], function (mockserver) {
// set up test service for local testing
mockserver.init();
// initialize the ushell sandbox component
sap.ushell.Container.createRenderer().placeAt("content");
});
});
</script>
The OData read call looks like:
onRemoveMyEntityBtnPress: function () {
let oEntityTable = this.byId("lineItemsList");
let aSelectedItems = oEntityTable.getSelectedItems();
let oModel = this.getModel();
for (let oSelectedItem of aSelectedItems) {
let sBindingPath = oSelectedItem.getBindingContext().getPath();
let sGuid = this._selectGuidFromPath(sBindingPath);
this._loadEntityFromService(sGuid, oModel).then((oData) => {
// Next step: change a property value
}).catch((oError) => {
jQuery.sap.log.error(oError);
});
}
if (oModel.hasPendingChanges()) {
oModel.submitChanges();
}
},
_loadEntityFromService: function (sGuid, oModel) {
return new Promise((resolve, reject) => {
oModel.read(`/MyEntity(${sGuid})`, {
success: (oData) => {
resolve(oData);
},
error: (oError) => { // call always ends up here with 404 error
reject(oError);
}
});
});
},
Does someone have an idea what I else have to do to send my read request to the mock service?
Finally found the solution!
I used the OData entity type to read my entity. I changed the destination to my entity set and now it doesn't throw a 404 error.

(Reddit API) How to get a list of subreddits user is subscribed to, using snoowrap?

So I'm using snoowrap to write a Chrome extension that gets a list of subreddits the user is subscribed, and subscribes to them on a different account.
I'm trying to get the list of subreddits currently but can't figure out how to do it. I've tried simply getting the JSON from https://www.reddit.com/subreddits/mine.json, which returns an empty object (persumably because no auth) and I have no idea how to do it via snoowrap. I looked through the documentation and can't find an option for it.
My code:
document.addEventListener('DOMContentLoaded', function() {
var login = document.getElementById('login');
login.addEventListener('click', function() {
const r = new snoowrap({
userAgent: '???',
clientId: '<id>',
clientSecret: '<clientsecret>',
username: '<username-here>',
password: '<password-here>'
});
r.getHot().map(post => post.title).then(console.log);
});
var getSubs = document.getElementById('get-subs');
getSubs.addEventListener('click', function() {
fetch('https://www.reddit.com/subreddits/mine.json')
.then(function(data) {
console.log(JSON.stringify(data));
})
.catch(function(error) {
console.log('error');
});
});
});
Not sure how else to try. Anyone have suggestions? I'd like to use snoowrap for this ideally.
When using snoowrap as API wrapper, after connecting to the api with:
const r = new snoowrap({...});
They provide a function for getting your own subscribed subreddits:
r.getSubscriptions();
This will return a Listing Object, which you can use like an Array.

Ember.js with Cloudkit JS

I have built a small prototype project using CloudKit JS and am now starting to build the next version of it and am wanting to use Ember as I have some basic experience with it. However, I am not too sure where to place the CloudKit JS code. For example where should I add the configure part and the auth function? I think that once I find the spot for the auth code, I could then add some of my query functions into the individual views and components, right?
Here is my configure code (with the container and id removed):
CloudKit.configure({
containers: [{
containerIdentifier: '###',
// #todo Must generate a production token for app store version
apiToken: '###',
auth: {
persist: true
},
// #todo Must switch to production for app store version
environment: 'development'
}]
});
Here is the auth function:
function setupAuth() {
// Get the container.
var container = CloudKit.getDefaultContainer();
//Function to call when user logs in
function gotoAuthenticatedState( userInfo ) {
// Checks if user allows us to look up name
var userName = '';
if ( userInfo.isDiscoverable ) {
userName = userInfo.firstName + ' ' + userInfo.lastName;
} else {
userName = 'User record name: ' + userInfo.userRecordName;
}
//Calls out initialization function
init();
//Sets up UI for logged in users
setAuthenticatedUI( userName );
//Register logged out function
container
.whenUserSignsOut()
.then( gotoUnauthenticatedState );
}
//Function to call when user logs out
function gotoUnauthenticatedState( error ) {
//Checks if error occurred
if ( error && error.ckErrorCode === 'AUTH_PERSIST_ERROR' ) {
displayError( logOutError, 'Error code: AUTH_PERSIST_ERROR' );
}
// Sets up the UI for logged out users
setUnauthenticatedUI();
//Register logged in function
container
.whenUserSignsIn()
.then( gotoAuthenticatedState )
.catch( gotoUnauthenticatedState );
}
// Check a user is signed in and render the appropriate button.
return container.setUpAuth()
.then( function( userInfo ) {
// userInfo is the signed-in user or null.
if ( userInfo ) {
gotoAuthenticatedState( userInfo );
} else {
gotoUnauthenticatedState();
}
});
}
The init() then calls functions to setup the queries to adds a chart to the page using records. The setAuthenticatedUI() and setUnauthenticatedUI() functions simply apply and remove classes once the user has been authenticated.
The answer pretty much depends on the version of Ember you're using and if how you are planning on using it. With routes? Simple routes? RouteHandlers?
For example, if you are at Ember v2.3.0, you could consider using dependency injection (https://guides.emberjs.com/v2.3.0/applications/dependency-injection/) to provide a configured container instance to the rest of your app, e.g.:
export function initialize(application) {
var container = CloudKit.configure(config).getDefaultContainer();
application.register('ckcontainer:main', container);
application.inject('route', 'ckcontainer', 'ckcontainer:main');
}
export default {
name: 'ckcontainer',
initialize: initialize
};
Then in a route, you can obtain a reference like so:
export default Ember.Route.extend({
activate() {
// The ckcontainer property is injected into all routes
var db = this.get('ckcontainer').privateCloudDatabase;
}
});
-HTH

How should I store current user details in EmberJS?

I have an EmberJS application generated using ember-cli. I'm currently using simple-auth with a custom authenticator.
In the authenticator, when the user logs in I want to save his details so that I can use it later.
I have the following code:
authenticate: function(options) {
var self = this;
return new Ember.RSVP.Promise(function(resolve, reject){
API.user.login(options.username, options.password, true).done(function(data) {
// #TODO: Save current user
resolve(data.id);
}).fail(function() {
reject();
});
});
},
User data is available in the variable data.user.
I tried using Ember.set('App.currentUser', data.user); but it's not working. What should I do?
I think it works easiest to use an initializer. Theres several ways you can resolve the user, I think it is easiest if you pass the user_email alongside the grant token from the API
//initializers/session-user.js
import Ember from "ember";
import Session from "simple-auth/session";
export function initialize(container) {
Session.reopen({
setCurrentUser: function() {
var accessToken = this.get('access_token');
var self = this;
if (!Ember.isEmpty(accessToken)) {
return container.lookup('store:main').find('user', {
email: self.get('user_email')
}).then(function (users){
self.set('currentUser', users.get('firstObject'));
});
}
}.observes('access_token')
});
}
export default {
name: 'session-user',
before: 'simple-auth',
initialize: initialize
};
Check this thread for where the idea of this came from: http://discuss.emberjs.com/t/best-practice-for-loading-and-persisting-current-user-in-an-authenticated-system/6987
And if you are using simple-auth > 0.8.0-beta.1 you will need to adjust the initializer
I ended up creating a custom Sessions controller and setting the current user object there, and then creating an alias from the application controller.
Something like what's in this article.

Categories

Resources