I have this directory structure:
app/router.js
app/oauth2-home-client/oauth2-client.js
And the sources:
app/oauth2-home-client/oauth2-client.js
//SOME CODE
exports.Bearer = {
authenticate : passport.authenticate('bearer', { session : false }),
initialize : passport.initialize()
// session : passport.session()
};
app/router.js
var oauth2 = require('./oauth2-home-client/oauth2-client');
console.log(JSON.stringify(oauth2.Bearer));
//SOME CODE
When I print oauth2.Bearer (and oauth2, too) content, I get {}.
What am I doing wrong?
Thanks.
Your code:
exports.Bearer = {
authenticate : passport.authenticate('bearer', { session : false }),
initialize : passport.initialize()
// session : passport.session()
};
Will result in:
exports.Bearer = {
authenticate :undefined,
initialize : undefined
};
because both passport.authenticate and passport.initialize return undefined.
And the keys having the value undefined are omitted by JSON.stringify.
[...]If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array).[...]
Its value may point to the module instantiation.
Have you try this?
module.exports = {...};
Related
I use Express ( node.js ) and MongoDB. When I try to view or update user profile I get an error
middleware token check worked
getProfileFields:::::::::::::>>>>e: TypeError: Cannot read properties of null (reading 'minAge')
at module.getProfileFields (C:\localhost\website\app\controllers\api\profile.js:34:22)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
it seems problem with this part of code
module.getProfileFields = async (req, res) => {
var successMessage = { status: 'success', message:"", data:{}};
var failedMessage = { status: 'fail', message:"", data:{}};
try {
var profileFields = await model.ProfileFields.find({isDeleted:false},{slug:1, options:1,type: 1});
var obj = {
...
educationLevel: [],
hobbies: [],
whatYouSay: [],
minAge: settings.minAge ? settings.minAge : 0,
maxAge: settings.maxAge ? settings.maxAge : 0,
religion: []
};
}
successMessage.message = "Successfully loaded profile reference";
successMessage.data = obj;
res.send(successMessage);
} catch (e) {
console.log('getProfileFields:::::::::::::>>>>e: ',e);
failedMessage.message = "Something went wrong";
res.send(failedMessage);
}
}
How to solve this problem?
Settings are empty, maybe they are not exported correctly. Check your settings file.
I think you're not using the find API call for MongoDB properly,
find usually takes up a filter object and an object of properties as a second argument.
Check the syntax required for find(){} function and probably you'll get through with it.
Hope it helps.
Happy coding!!
I have a very basic feathers service which stores data in mongoose using the feathers-mongoose package. The issue is with the get functionality. My model is as follows:
module.exports = function (app) {
const mongooseClient = app.get('mongooseClient');
const { Schema } = mongooseClient;
const messages = new Schema({
message: { type: String, required: true }
}, {
timestamps: true
});
return mongooseClient.model('messages', messages);
};
When the a user runs a GET command :
curl http://localhost:3030/messages/test
I have the following requirements
This essentially tries to convert test to ObjectID. What i would
like it to do is to run a query against the message attribute
{message : "test"} , i am not sure how i can achieve this. There is
not enough documentation for to understand to write or change this
in the hooks. Can some one please help
I want to return a custom error code (http) when a row is not found or does not match some of my criterias. How can i achive this?
Thanks
In a Feathers before hook you can set context.result in which case the original database call will be skipped. So the flow is
In a before get hook, try to find the message by name
If it exists set context.result to what was found
Otherwise do nothing which will return the original get by id
This is how it looks:
async context => {
const messages = context.service.find({
...context.params,
query: {
$limit: 1,
name: context.id
}
});
if (messages.total > 0) {
context.result = messages.data[0];
}
return context;
}
How to create custom errors and set the error code is documented in the Errors API.
I am setting up authentication in ReactJS app using AzureAD MSAL. I am able to obtain id_token and access_token. But while getting access token, I am not able tot refer to local variables via this keyword. I tried to bind 'this' to the call back function but that leads to other issues.
I am implementing all the login functionality as a class.
import { UserAgentApplication } from "msal";
export default class AuthService {
constructor() {
this.applicationConfig = {
clientID: "<clientId>",
authority: "<azureADTenantUrl>"
};
this.scopes = [
"openid",
"<Other scopes>"
];
this.client = new UserAgentApplication(
this.applicationConfig.clientID,
this.applicationConfig.authority,
this.authCallback,
{
redirectUri: "http://localhost:3000/"
}
);
}
login = () => {
this.client.loginRedirect(this.scopes);
};
logout = () => {
this.client.logout();
};
authCallback = (erroDesc, token, error, tokenType) => {
if (tokenType == "id_token") {
this.acquireTokenSilent(this.scopes).then(
function(accessToken) {
console.log(accessToken);
},
function(error) {
console.log(error);
}
);
}
};
}
(this is not the actual error message, but a friendly description)
this.scopes is undefined as 'this' is scoped to UserAgentApplication.
to avoid this, I tried to bind the this to the callback function. I have added the following statement in the constructor.
this.authCallback = this.authCallback.bind(this);
this leads to another error.
(this is not the actual error message, but a friendly description)
this.acquireTokenSilent is undefined and 'this' do not have a definition for client to reference using this.client.acquireTokenSilent
So I have hard coded the scopes in the original code and was able to get access token, but again same problem in the call back. This time 'this' is null in the call back.
I tried to move the authCallback to the react component and pass it as a parameter to the service, but that also has same kind of problems.
Any help with how to configure this properly is really appreciated. thanks.
Try this replacement for authCallback. It doesn't entirely solve the problem, but can get you past the UserAgentApplication's hijacking of "this" object.
authCallback = (erroDesc, token, error, tokenType) => {
const client = window.client as Msal.UserAgentApplication;
if (tokenType == "id_token") {
client.acquireTokenSilent(["openid"]).then(
function(accessToken) {
console.log(accessToken);
},
function(error) {
console.log(error);
}
);
}
};
Alternatively, use the loginPopup function instead of loginRedirect as it does not have "this" problem that still exists in current MSAL v0.2.3.
I was able to get it working in msal 1.1.1. Try this way:
this.msalClient = new Msal.UserAgentApplication(config);
this.msalClient.handleRedirectCallback(authCallback.bind(this));
function authCallback(error,response)
{
if (response.tokenType === 'access_token' && response.accessToken)
{
this.accesstoken = response.accessToken;
}
}
I have the following code in my Model.js file.
Model.observe('loaded', (ctx, next) => {
const {
data,
options: {
user
}
} = ctx;
const owner = (user && data && user.uid === data.userId) || false;
console.log(
`${data.id}: loaded - access by ${user && user.name}, owner:${owner}`
);
if (!owner) {
delete data.testProp1;
}
console.log('returning: ', ctx.data);
next();
});
When I make a request, I see the following log output (server logs):
f3f9ffd6-14dc-42e5-94ba-503aa3426faa: loaded - access by User1, owner:false
returning:
{
testProp2: true,
id: 'f3f9ffd6-14dc-42e5-94ba-503aa3426faa',
userId: 'sfeywkKSuBTlf0DwE4ZOFd8RX5E3'
}
But then in the actual response the browser receives I actually get:
{
testProp1: true,
testProp2: true,
id: 'f3f9ffd6-14dc-42e5-94ba-503aa3426faa',
userId: 'sfeywkKSuBTlf0DwE4ZOFd8RX5E3'
}
Is there something in the documentation I am missing? Deleting the property is exactly what it shows in the Loopback docs here. Also, I actually see the modified data as the data property on the ctx object before calling next(). Anyone run into this issue or know some caveat to the docs that isn't explicitly stated?
I'm trying to write a frontend with ember.js and ember-data for a REST service. The server returns the data (I do see this using fiddler) but I always get the error Unable to set property 'store' of undefined or null reference. My JS code:
window.Cube = Ember.Application.create({
LOG_TRANSITIONS: true,
LOG_TRANSITIONS_INTERNAL: true
});
var attr = DS.attr;
Cube.Subject = DS.Model.extend({
name: attr(),
change_date: attr(),
create_date: attr()
});
Cube.ApplicationAdapter = DS.RESTAdapter.extend({
namespace: 'backend/v1/api',
host: 'http://localhost:58721'
});
Cube.Store = DS.Store.extend({
revision: 12,
url: "http://localhost:58721",
adapter: Cube.ApplicationAdapter
});
Cube.IndexRoute = Ember.Route.extend({
model: function (params) {
var store = this.get('store');
return store.findAll('Subject');
}
});
The error originates in ember-data.js:
modelFor: function(key) {
if (typeof key !== 'string') {
return key;
}
var factory = this.container.lookupFactory('model:'+key);
Ember.assert("No model was found for '" + key + "'", factory);
factory.store = this; // error here
factory.typeKey = key;
return factory;
}
As far as I understand ember, the store should be automatically set, but it is always null.
How to define the model, so the store is available? What am I missing?
Update 1:
Updated ember. Now I use the following versions:
DEBUG: Ember : 1.1.0
DEBUG: Ember Data : 1.0.0-beta.3
DEBUG: Handlebars : 1.0.0
DEBUG: jQuery : 1.9.1
No I get the following errors in the console:
No model was found for 'nextObject'
Error while loading route: TypeError: Unable to set property 'store' of undefined or null reference
subject should be lower case, additionally findAll is an internal method, you should be using find with no additional parameters (which then calls findAll).
Cube.IndexRoute = Ember.Route.extend({
model: function (params) {
var store = this.get('store');
return store.find('subject');
}
});