How can I override builtin login method in Loopback? - authentication

I've created a new User model, based on builtin one. I'm trying this:
module.exports = function(TiUser) {
TiUser.on('dataSourceAttached', function(obj) {
var login = TiUser.login;
TiUser.login = function(credentials, include, cb) {
var result = login.apply(this, credentials);
// Do my stuff
cb(null, my_data);
};
});
};
But I can't get it working... What is wrong? or how could this be done right?
Thanks

You may want to consider adding an afterRemote() hook to login(). Now you can achieve to add role( using Role model ) to user. For example:
TiUser.afterRemote('login', function(ctx, next) {
//add role to the user.
next();
});

At the end I've created a new method instead of overriding a current one:
module.exports = function(TiUser) {
TiUser.auth = function(credentials, include, fn) {
var self = this;
self.login(credentials, include, function(err, token) {
authInfo = {
token: token
};
fn(err, authInfo);
});
};
TiUser.remoteMethod(
'auth',
{
description: 'Login method with Role data information embedded in return',
accepts: [
{arg: 'credentials', type: 'object', required: true, http: {source: 'body'}},
{arg: 'include', type: ['string'], http: {source: 'query' },
description: 'Related objects to include in the response. ' +
'See the description of return value for more details.'}
],
returns: {
arg: 'accessToken', type: 'object', root: true,
description: 'User Model'
},
http: {verb: 'post'}
}
);
};

Related

How can I set Next-Auth callback url? and next-auth session return null

I want to set login, logout callback url.
So, I set the callback url like this.
//signIn
const signInResult = await signIn("credentials", {
message,
signature,
redirect: false,
callbackUrl: `${env.nextauth_url}`,
});
//signOut
signOut({ callbackUrl: `${env.nextauth_url}`, redirect: false });
But, When I log in, I look at the network tab.
api/auth/providers, api/auth/callback/credentials? reply with
callbackUrl(url) localhost:3000
It's api/auth/callback/credentials? reply.
It's api/auth/providers reply
and api/auth/session reply empty object.
When I run on http://localhost:3000, everything was perfect.
But, After deploy, the login is not working properly.
How can I fix the error?
I added [...next-auth] code.
import CredentialsProvider from "next-auth/providers/credentials";
import NextAuth from "next-auth";
import Moralis from "moralis";
import env from "env.json";
export default NextAuth({
providers: [
CredentialsProvider({
name: "MoralisAuth",
credentials: {
message: {
label: "Message",
type: "text",
placeholder: "0x0",
},
signature: {
label: "Signature",
type: "text",
placeholder: "0x0",
},
},
async authorize(credentials: any): Promise<any> {
try {
const { message, signature } = credentials;
await Moralis.start({
apiKey: env.moralis_api_key,
});
const { address, profileId } = (
await Moralis.Auth.verify({ message, signature, network: "evm" })
).raw;
if (address && profileId) {
const user = { address, profileId, signature };
if (user) {
return user;
}
}
} catch (error) {
console.error(error);
return null;
}
},
}),
],
pages: {
signIn: "/",
signOut: "/",
},
session: {
maxAge: 3 * 24 * 60 * 60,
},
callbacks: {
async jwt({ token, user }) {
user && (token.user = user);
return token;
},
async session({ session, token }: any) {
session.user = token.user;
return session;
},
async redirect({ url, baseUrl }) {
// Allows relative callback URLs
if (url.startsWith("/")) return `${baseUrl}${url}`;
// Allows callback URLs on the same origin
else if (new URL(url).origin === baseUrl) return url;
return baseUrl;
},
},
secret: env.nextauth_secret,
});

Should a new Collection be created upon Model.create()

Am working with mongoose and have two models. The User model and the Service model, when a user logs in the method will findOne() user if one exists or create() a new user based on the what's passed in from req.body.
My Service Schema is like this:
const serviceSchema = new mongoose.Schema({
name: {
type: String,
default: 'contentEditor'
},
display: {
type: String,
default: 'Content Editor'
},
accessLevel: {
type: Number,
min: 0,
max: 4,
default: 4
}
});
My User Schema is a bit bigger, I've removed some of the field/value pairs but the part where I embed the Service Schema looks like this:
const userSchema = new mongoose.Schema(
{
email: {
type: String,
required: [true, 'Must have a email address'],
trim: true,
unique: true,
},
firstName: {
type: String,
},
lastName: {
type: String,
},
services: {
type: [serviceSchema],
ref: 'Services',
default: [serviceSchema],
},
},
);
When I hit the /api/v1/login endpoint a new user will be created with the Service document correctly but within the Mongoose database only a User collection exists. How do I make it so that both a Users collection and Services collection are created?
Edit: Below is the function that I create/find the user with when they login. When an existing User is found, by their email it will return that user if the user is not found then it will create a new one...
Both behaviours are as expected including adding the Services to the newly created User. What isn't expected is that only ONE collection is added to the DB.
const login = catchAsync(async ({ body: { email, password } }, res, next) => {
if (!email || !password) {
return next(new AppError('Please provide email and password', 400));
}
const { Success } = await webApi(email, password);
const mongoUser = await User.findOne({ email });
if (Success && mongoUser) {
return createSendtoken(mongoUser, 200, res);
}
if (Success && !mongoUser) {
const newUser = await User.create({ email });
return createSendtoken(newUser, 201, res);
}
return next(new AppError('User not found', 404));
});
Make sure you are making the serviceSchema a mongoose model.
const Services = mongoose.model('Service', serviceSchema)
You also have to save it using mongooses model.save() function

Relay mutation for React native returning 400 bad request?

I have been having SO much trouble trying to get a mutation to work.
Given this GraphQL Schema, can anyone PLEASE help me create a simple create User mutation? I don't understand what I am missing. I got it to a point where it throws a 400 error from the GraphQL server and it does not fire the resolve function.
var userType = new GraphQLObjectType({
name: 'User',
description: 'User creator',
fields: () => ({
id: {
type: new GraphQLNonNull(GraphQLString),
description: 'The id of the user.'
},
email: {
type: GraphQLString,
description: 'The email of the user.'
},
business: {
type: GraphQLString,
description:
'The name of the business of the user as the app refers to it.'
},
businessDisplayName: {
type: GraphQLString,
description: 'The name of the business of the user as they typed it in.'
},
trips: {
type: new GraphQLList(tripType),
description: 'The trips of the user, or an empty list if they have none.',
resolve: (user, params, source, fieldASTs) => {
var projections = infoToProjection(fieldASTs)
return Trip.find(
{
_id: {
// to make it easily testable
$in: user.trips.map(id => id.toString())
}
},
projections,
function(err, docs) {
return docs
}
)
}
}
})
})
var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'root',
fields: {
trips: {
type: new GraphQLList(tripType),
resolve: function() {
return Trip.find({})
}
},
users: {
type: new GraphQLList(userType),
resolve: function() {
return User.find({})
}
},
user: {
type: userType,
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (root, { id }, source, fieldASTs) => {
return User.findOne(
{ _id: id },
infoToProjection(fieldASTs),
function(err, doc) {
return doc
}
)
}
},
trip: {
type: tripType,
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (root, { id }, source, fieldASTs) => {
var projections = infoToProjection(fieldASTs)
return Trip.findOne({ _id: id }, projections, function(err, doc) {
return doc
})
}
}
}
}),
// mutation
mutation: new GraphQLObjectType({
name: 'Mutation',
fields: {
createUser: {
name: 'createUser',
type: userType,
args: {
input: { type: new GraphQLInputObjectType({
name: 'user',
fields: {
business: { type: GraphQLString },
email: { type: GraphQLString },
businessDisplayName: { type: GraphQLString }
}
})
}},
resolve: (parentValue, args) => {
let user = new User({ ...args.input })
user.save()
return user
}
}
})
})
export var getProjections = infoToProjection
export default schema
This works with GraphiQL using the following queries or mutations:
mutation {
createUser(input:{business:"business", email: "e#mai.l", businessDisplayName: "businessDN"}) {
id
email
business
businessDisplayName
}
}
fragment UserFragment on User {
id
business
businessDisplayName
trips{
title
}
}
{
hideya: user(id: "someid") {
...UserFragment
}
}
I finally fixed the problem. Tried to understand the source of the problem so I used a new NetworkLayer to enable appropriate logging and meaningful error messages. Then threw the an error when my mutation failed. The error message was : "Cannot query field clientMutationId". Looked that up and found that to be able to mutate objects you need to have that field on your GraphQL type. So I added it.
Lesson learned: I highly recommend using react-relay-network-layer.
More details:
Here is my code for it:
import {
RelayNetworkLayer,
urlMiddleware,
batchMiddleware,
} from 'react-relay-network-layer';
Relay.injectNetworkLayer(new RelayNetworkLayer([
batchMiddleware({
batchUrl: 'http://localhost:3000/graphql',
}),
urlMiddleware({
url: 'http://localhost:3000/graphql',
}),
]));
Note: This enables logging and by default it's a simple console.log.
Here is how I threw the error:
const params = {
email: email.toLowerCase(),
businessDisplayName: business,
business: business.toLowerCase()
}
var onSuccess = () => {
console.log('Mutation successful!')
}
var onFailure = transaction => {
var error = transaction.getError() || new Error('Mutation failed.')
console.error(error)
}
Relay.Store.commitUpdate(new FindOrCreateUser({ user: { ...params } }), { onFailure, onSuccess })
And of course you always need to clean your cache and restart your packager.

Hapi Lab The following leaks were detected:lr

Here Hapi Lab why Test failed when all the tests are passed why the test is failed.
In this new question why I get The following leaks were detected:lr even if there is no global var in the code.
Running this simple test
var Code = require('code');
var Lab = require('lab');
var lab = exports.lab = Lab.script();
var server = require('../../');
lab.experiment('Users', function () {
lab.test('create joi required', function (done) {
var options = {
method: 'POST',
url: '/api/users',
payload: {
lastname: 'Bedini',
username: 'whisher',
email: 'me#ilwebdifabio.it',
password: 'mysecret'
}
};
server.inject(options, function(response) {
var result = response.result;
Code.expect(response.statusCode).to.equal(422);
Code.expect(result.message).to.equal('child "firstname" fails because ["firstname" is required]');
done();
});
});
lab.test('create', function (done) {
var options = {
method: 'POST',
url: '/api/users',
payload:{
firstname: 'Fabio',
lastname: 'Bedini',
username: 'whisher',
email: 'me#ilwebdifabio.it',
password: 'mysecret'
}
};
server.inject(options, function(response) {
var token = response.result.token;
var payload = options.payload;
Code.expect(response.statusCode).to.equal(201);
done();
});
});
});
2 tests complete
Test duration: 363 ms
The following leaks were detected:lr
but I don't see any lr var !
and the strange is if I run this
payload.passdword
instead of
payload.password
var Code = require('code');
var Lab = require('lab');
var lab = exports.lab = Lab.script();
var server = require('../../');
lab.experiment('Users', function () {
lab.test('create joi required', function (done) {
var options = {
method: 'POST',
url: '/api/users',
payload: {
lastname: 'Bedini',
username: 'whisher',
email: 'me#ilwebdifabio.it',
password: 'mysecret'
}
};
server.inject(options, function(response) {
var result = response.result;
Code.expect(response.statusCode).to.equal(422);
Code.expect(result.message).to.equal('child "firstname" fails because ["firstname" is required]');
done();
});
});
lab.test('create', function (done) {
var options = {
method: 'POST',
url: '/api/users',
payload:{
firstname: 'Fabio',
lastname: 'Bedini',
username: 'whisher',
email: 'me#ilwebdifabio.it',
passdword: 'mysecret'
}
};
server.inject(options, function(response) {
var token = response.result.token;
var payload = options.payload;
Code.expect(response.statusCode).to.equal(201);
done();
});
});
});
I've got
1 of 2 tests failed
Test duration: 73 ms
No global variable leaks detected
with no warning about lr var.
So I don't know which way to turn :(
Can help me, please ?
UPDATE
controller
'use strict';
/**
* Module dependencies.
*/
var BcryptUtil = require('../utils/bcrypt');
var JwtUtil = require('../utils/jwt');
var Models = require('../models');
var ReplyUtil = require('../utils/reply');
var User = Models.users;
exports.create = function create(request, reply) {
var params = request.payload;
params.password = BcryptUtil.generateHash(params.password);
params.roles =JSON.stringify(['user']);
User
.create(params)
.then(function(user) {
var token = JwtUtil.getUserToken(user);
var redisClient = request.server.plugins['hapi-redis'].client;
redisClient.set('user_'+user.userId, token);
return reply(ReplyUtil.ok(token)).created('/api/users/' + user.userId);
})
.catch(function(err){
if(err instanceof Models.Sequelize.ValidationError){
return reply(ReplyUtil.badData(err,params));
}
return reply(ReplyUtil.badImplementation(err));
});
};
exports.findAll = function (request, reply) {
User
.findAll({
order: [['createdAt','DESC']],
attributes: ['userId', 'firstname', 'lastname', 'username', 'email']
})
.then(function(users) {
return reply(ReplyUtil.ok(users));
})
.catch(function(err){
return reply(ReplyUtil.badImplementation(err));
});
};
exports.findById = function (request, reply) {
var userId = request.params.userId;
User
.findById(
userId,
{
attributes: ['userId', 'firstname', 'lastname', 'username', 'email']
})
.then(function(user) {
if(!user){
return reply(ReplyUtil.notFound({userId:userId}));
}
return reply(ReplyUtil.ok(user));
})
.catch(function(err){
return reply(ReplyUtil.badImplementation(err));
});
};
exports.update = function (request, reply) {
var userId = request.params.userId;
var params =request.payload;
User
.update(params,{
where: {
userId: userId
}
})
.then(function(rows) {
var affectedRows = rows.pop();
if(!affectedRows){
return reply(ReplyUtil.notFound({userId:userId}));
}
return reply(ReplyUtil.ok(affectedRows));
})
.catch(function(err){
if(err instanceof Models.Sequelize.ValidationError){
return reply(ReplyUtil.badData(err,params));
}
return reply(ReplyUtil.badImplementation(err));
});
};
exports.destroy = function (request, reply) {
var userId = request.params.userId;
User
.destroy({
where: {
userId: userId
}
})
.then(function(rows) {
if(!rows){
return reply(ReplyUtil.notFound({userId:userId}));
}
return reply(ReplyUtil.ok(rows));
})
.catch(function(err){
return reply(ReplyUtil.badImplementation(err));
});
};
exports.signIn = function (request, reply) {
var params = request.payload;
User
.findOne({
where: {
email: params.email
}
})
.then(function(user) {
if(!user){
return reply(ReplyUtil.invalidPassword());
}
if(BcryptUtil.authenticate(params.password, user.password)){
var token = JwtUtil.getUserToken(user);
var redisClient = request.server.plugins['hapi-redis'].client;
redisClient.set('user_'+user.userId, token);
return reply(ReplyUtil.ok(token));
}
return reply(ReplyUtil.invalidPassword());
})
.catch(function(err){
return reply(ReplyUtil.badImplementation(err));
});
};
exports.logOut = function (request, reply) {
var userId = request.auth.credentials.jti;
var redisClient = request.server.plugins['hapi-redis'].client;
redisClient.del('user_'+userId);
return reply();
};
exports.methodNotAllowed = function (request, reply) {
return reply( ReplyUtil.methodNotAllowed() );
};
route
'use strict';
/**
* Module dependencies.
*/
var User = require('../controllers/users');
var Validator = require('../validations/users');
/**
* Resource configuration.
*/
var internals = {};
internals.resourcePath = '/users';
module.exports = function() {
return [
{
method: 'POST',
path: internals.resourcePath,
config : {
handler: User.create,
validate: Validator.create
}
},
{
method: 'GET',
path: internals.resourcePath,
config : {
handler : User.findAll,
auth: {
strategy: 'token',
scope: ['admin']
}
}
},
{
method: 'GET',
path: internals.resourcePath + '/{userId}',
config : {
handler : User.findById,
validate: Validator.findById,
auth: {
strategy: 'token',
scope: ['user']
}
}
},
{
method: 'PUT',
path: internals.resourcePath + '/{userId}',
config : {
handler: User.update,
validate: Validator.update,
auth: {
strategy: 'token',
scope: ['user']
}
}
},
{
method: 'DELETE',
path: internals.resourcePath + '/{userId}',
config : {
handler: User.destroy,
validate: Validator.destroy,
auth: {
strategy: 'token',
scope: ['user']
}
}
},
{
method: 'POST',
path: internals.resourcePath + '/signin',
config : {
handler: User.signIn,
validate: Validator.signIn
}
},
{
method: 'GET',
path: internals.resourcePath + '/logout',
config : {
handler : User.logOut,
auth: {
strategy: 'token',
scope: ['user']
}
}
},
{
method: '*',
path: internals.resourcePath + '/{somethingss*}',
config : {
handler: User.methodNotAllowed
}
}
];
}();
I no I am a little late, but just in case anyone else has this problem. It's a problem with bcrypt. I had a similar problem where whenever I used bcrypt-nodejs it would give me The following leaks were detected:lr, password, but when I changed to reqular bycrypt it worked with no leaks. Try updating your bycrypt version.
Just add all leakimg elements to ignore list
"test": "lab -c -L -I 'Reflect,core,_babelPolyfill,regeneratorRuntime,__core-js_shared__ css'",

How to use api attribute on proxy

I would like to know how to use the api attribute of a proxy in ST2
For now, I have this in my proxy configuration:
api: {
create : App.urls.create_object,
read : App.urls.load_object,
update : App.urls.update_object,
destroy : App.urls.destroy_object
}
But then, I don't know how to use it.
For instance, when I wanted to create a new object, I created an Ext.Ajax.request with these parameters :
url: App.urls.create_object,
params: {
'object': object
},
But now, how could I do the same with the api attribute ?
Could you help ?
Assuming you have a model like this:
Ext.define('User', {
fields: ['name', 'email'],
proxy: {
type: 'ajax',
api: {
create: 'my_create_url',
read: 'my_read_url',
update: 'my_update_url',
destroy: 'my_destroy_url'
}
}
});
create
var user = Ext.create('User', {name: 'Ed Spencer', email: 'ed#sencha.com'});
user.save(); // will POST to the create url
update
var user = Ext.create('User', {name: 'Ed Spencer', email: 'ed#sencha.com'});
user.save({
success: function(user) {
user.set('name', 'Robert Dougan');
user.save(); // will PUT update URL
}
});
read
Using a store:
var store = Ext.create('Ext.data.Store', {
model: 'User'
});
store.load(); // will GET to read URL
Using the model:
// will GET the read URL with the specified ID.
User.load(12, {
success: function(user) {
console.log(user);
}
});
destroy
var user = Ext.create('User', {name: 'Ed Spencer', email: 'ed#sencha.com'});
user.save({
success: function(user) {
user.destroy(); // will DELETE destroy URL
}
});
There is more information about this on the Rest proxy in the Sencha Docs: http://docs.sencha.com/touch/2-0/#!/api/Ext.data.proxy.Rest
sync
You can also use the store sync method to batch create/update/destroy all the records in your store.
var store = Ext.create('Ext.data.Store', {
model: 'User'
});
store.add({ name: 'Robert Dougan', email: 'rob#sencha.com' });
store.sync(); // will batch update all the needed records