Invalid credentials postman - sql

I hard coded the users in my seed file
I can view the the users in the database
But when i try to test the details in the database i get an error "invalid credentials"
I don't know why it says that when the user is already in the database
This is the seeds file
const noPassword = "$2a$12$ZQwXBTq7UMgmugpy5zz9SOdG4JvEa3Bj5MofQl9fIMFb1wTSGU9.C"; exports.seed = function (knex) { // Deletes ALL existing entries return knex("users") .truncate() .then(function () { // Inserts seed entries return knex("users").insert([ { email: "danielAsuquo15#gmail.com", first_name: "Daniel", last_name: "Asuquo", password:noPassword, }, { email: "josiahdamiwilliams#gmail.com", first_name: "josiah", last_name: "williams", password:noPassword, }, ]); }); };

Related

How to modify currentUserStore in mobx-state-tree

I'm trying to wrap my head around mobx-state-tree and whipped up a simple currentUserStore to hold some data for a logged in user and allow login/logout:
import { types } from "mobx-state-tree";
import { client } from '../../../helpers/client';
const User = types
.model("User", {
name: types.string,
email: types.string,
type: types.string,
token: types.string,
roles: types.array(types.string),
})
export const CurrentUserStore = types
.model("CurrentUserStore", {
user: types.optional(types.maybeNull(User), () => null)
})
.actions((currentUserStore) => ({
async login(login, password) {
const result = await client.post(`auth`, {
email: login,
password,
});
const { name, email, type, token, roles } = result
currentUserStore.user = User.create({ name, email, type, token, roles })
localStorage.setItem('authUser', JSON.stringify(result));
},
logout() {
currentUserStore.user = null
localStorage.removeItem('authUser')
},
}));
When calling the login function, I get the error Cannot modify 'CurrentUserStore#/currentUserStore', the object is protected and can only be modified by using an action.. There's something I'm missing here, but not exactly sure why I shouldn't be able to do something like this after reading through example where the store is modified directly in an action like this.
Once I moved the modification out of an async func, it worked. Just changed to this:
async login(login, password) {
const result = await client.post(`auth`, {
email: login,
password,
});
this.setUser(User.create(result))
localStorage.setItem('authUser', JSON.stringify(result));
},
logout() {
currentUserStore.user = null
localStorage.removeItem('authUser')
},
setUser(user) {
self.user = user
}

Unit Test with Express, TypeScript, Prisma and Jest

I'm trying to unit test with Prisma and Jest following this link https://www.prisma.io/docs/guides/testing/unit-testing.
Here is my test code:
test("should create a user ", async () => {
var user: any = {
store_id: "601d6dea-9b89-4c0d-adfc-6ed52424a2a0",
password: '1234',
user_name: "username",
first_name: "Rich",
last_name: "hello#prisma.io",
phone: "12345",
is_phone_verified: true,
is_email_verified: true, };
prismaMock.sec_user_fs.create.mockImplementation(user)
await expect(createUser(user)).resolves.toEqual({
store_id: "601d6dea-9b89-4c0d-adfc-6ed52424a2a0" }); });
createUser method is save data to database. Here is code:
export async function createUser(user: CreateUser) {
user = await prisma.sec_user_fs.create({
data: user,
})
return {"store_id": user.store_id} }
So my questions are:
prismaMock.sec_user_fs.create.mockImplementation(user) - In my understanding this line mocked database table, it prevent not insert data to table while testing. But, it does. How can mock without inserting, updating,deleting to table?
createUser method return json object. But if i test my api end point /code is below/ how expect result? Because it does return res.status(200) etc.?
export default asyncHandler(async (req: CustomRequest, res: Response)=> {
const body = {
user_name: req.body.user_name,
first_name: req.body.first_name,
last_name: req.body.last_name,
phone: req.body.phone,
phone_country_code: req.body.phone_country_code }
const user_id = req.params.id
const user = await prisma.sec_user_fs.updateMany({
where: {
user_id,
status: 'A'
},
data: body });
res.status(200).send({
status: 'Success',
message: req.t('success'),
errors: [],
data: user, }); });
Thanks in advance :)

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

Mongoose - Promise then() not triggered on save

I'm using ExpressJS + Mongoose + TypeScript. I have created a schema as below
const schema: Schema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true
},
gender: {
type: Boolean,
required: true
},
mobile: {
type: String,
required: false
},
password: {
type: String,
required: true
},
activationKey: {
type: String,
required: false
},
isActivated: {
type: Boolean,
required: true
},
imagePath: {
type: String,
required: false
},
});
I'm using the below code to save (insert) a new entry
MongoClient.connect('mongodb://MyUsername:MyPassword#ds135757.mlab.com:35777/my-db-us', (err, db) => {
if (err) {
console.log('mongoose error: ' + err);
} else {
console.log('mongoose db: ' + db);
const user = new User({
firstName: 'ee',
lastName: 'ee',
email: 'eee#fff.com',
gender: true,
mobile: '333',
password: '333',
isActivated: true
});
user.save().then((someValue) => {
console.log('saved');
}).catch((err) => {
console.log('not saved:' + err);
});
}
});
Console Messages
When correct data is sent. saved isn't printed
mongoose db: [object Object]
When incorrect data is sent
mongoose db: [object Object]
not saved:ValidationError: gender: Path `gender` is required.
When unable to connect to MongoDB if internet is disconnected
mongoose error: MongoError: failed to connect to server [ds135777.mlab.com:35777] on first connect [MongoError: connection 0 to ds135777.mlab.com:35777 timed out]
Module versions
"mongodb": "^2.2.34",
"#types/mongodb": "^3.0.5",
"mongoose": "^5.0.4",
"#types/mongoose": "^5.0.2",
Re-written example (Solution)
const mongoose = require('mongoose');
mongoose.connect('mongodb://MyUsername:MyPassword#ds135757.mlab.com:35777/my-db-us', function(err) {
if (err) {
console.log('err: ' + err);
} else {
console.log('connected');
const user = new User({
firstName: 'ee',
lastName: 'ee',
email: 'eee#fff.com',
gender: true,
mobile: '333',
password: '333',
isActivated: true
});
user.save().then((someValue) => {
console.log('saved');
}).catch((err) => {
console.log('not saved:' + err);
});
}
});
The messages printed are
connected
saved
I am guessing a funny problem with your code(Just guessing looking at your variable name convention ;-)).
You are saying you use mongoose but you connect using native MongoClient (again guessing based on variable name) you must be connecting using mongoose
const mongoose = require('mongoose');
then just replace your MongoClient with mongoose
then doesn't print anything as nothing is happening there and catch prints error as validation happens before connection
The reason is you are using native client for connecting and using mongoose for modelling which is not the correct way. Do connect to the Mongo DB URI using mongoose and save schema.
You are creating a standard MongoClient connection, this will not effect mongoose models. The connection that created the User model must be open for the various database actions to work. Assuming that the User model was created using the global mongoose object (e.g. mongoose.model('User', userSchema)) then you must call mongoose.connect() to activate the model's connection. If the User model was created via a non-global connection (e.g. mongoose.createConnection()) then you should ensure that the connection is in the open state.

Meteor.loginWithPassword returns Error: Incorrect password [403]

I would like to add programmatically few users and login with one of them in my meteor app. I could not find any methods to add users at server side; so I added two buttons at client side to generate users and login with one of them. I can create users (I see them in mogodb) but I cannot login, getting Error: Incorrect password [403]. What I am missing?
This is client.js code
Template.hello.events({
'click #createUsers': function () {
console.log("Creating users...");
var users = [
{ email: "dgra#gmail.com", username: "gra", name: "gra", roles: ['admin'] }
];
_.each(users, function (user) {
Accounts.createUser({
email: user.email,
password: "admin",
profile: { username: user.username },
profile: { name: user.name },
roles: user.roles
});
});
},
'click #logIn': function () {
console.log("logIn gra...");
Meteor.loginWithPassword("dgra#gmail.com", "admin", function (err) {
if (err) {
console.log("loginError: " + err);
}
});
}
});
I could not find any methods to add users at server side
You can add users from the server. As the docs point out, Accounts.createUser runs anywhere. Here is a working example:
server/initialize.js
var insertUser = function() {
var user = {
email: 'dgra#gmail.com',
username: 'gra',
name: 'gra'
};
Accounts.createUser({
username: user.username,
email: user.email,
password: 'admin',
profile: {
name: user.name
}
});
};
Meteor.startup(function() {
if (Meteor.users.find().count() === 0) {
insertUser();
}
});
A few points:
You can add only one profile object.
Accounts.createUser only takes the arguments shown in the docs, so you can't add arbitrary objects.
If you are trying to use roles, the example there shows the roles being added after the account is created.
In the code above, I only add the user if there are no users in the database. This is convenient for testing since the user will automatically be inserted after a meteor reset (no button pushing requred).