So, this is the post request for my register route using express.js. I am printing the newUser object to console. It prints all the information i.e. name, collage, address, encrypted password but it didn't prints the phone to console why? and also only phone number is not inerting in mongodb database.
app.post("/register", function(req,res){
const newUser=new User({
name:req.body.fname,
phone:req.body.ffphone,
email:req.body.femail,
callege:req.body.fcallege,
password:req.body.fpassword
});
console.log(newUser);
newUser.save(function(err){
if(err){
console.log(err);
}else{
res.send("<h1>Registration done</h1>");
}
});
})
It only prints this output to console:
{
callege: 'MIT',
_id: 60450bd602c55639309f93a1,
name: 'user1',
email: 'abc#gmail.com',
password: '123456'
}
why it didn't showing phone attribute? Though I am taking right input from html form.
Check your Schema for your User model. You probably forgot to add the phone field to it.
Fields that are not included in the schema will not be inserted into the document, which could be why your phone number is not appearing.
Related
I used expo-image-picker to get the URI for the image that I am uploading to the MySQL database using Node.js. I can upload the image URI to the Database. The problem that I am facing is how do I call the image from the database and view it in my Front-End. the URI that I am getting is something like this
file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FdTracker-deb1436b-b1f4-483d-9499-47de5460a3b5/ImagePicker/a156533a-0666-406c-915d-7280e0910d20.jp
Now first of all I don't even know if the Image is stored in this URI. I tried opening it in the Browser, but nothing happened. I searched for the path defined in the URI on my device but couldn't find anything.
Second is how do I get the uploaded Image in my Front-end.
I wrote the following query to call the image back.
Image.getAllImageById = (id, result) => {
dbConn.query('SELECT * FROM receipt WHERE receiptId=?', id, (err, res) => {
if (err) {
console.log('Error while fetching receipt by Id', err);
result(null, err);
}
else {
console.log('Receipt fetched successfully');
result(null, res);
}
})
}
FYI- I am using React Native as Front-End, Node.js as Back-end and MySQL as Database.
Hoping to get a solution for my Problem.
I am trying to setup an Angular app which authenticates users against a back-end server. I am able to get the list of users from server as a JSON in my Angular list. How can I now validate this against user input fields.
Since I have already got the list of users I just have to validate the user entered inputs against that. But for some reason it doesn't work.
Code to get list of all users
getListofUsers() {
return this.httpClient.get(this.userListURL);
}
this.authService.getListofUsers()
.subscribe(resp => {
console.log(resp, "res");
this.data = resp
},
error => {
console.log(error, "error");
})
Data variable contains the response JSON.
I want to validate user input fields against this JSON response
this.authService.authenticateUser({
userId: this.userId.value,
userPassword: this.userPassword.value},this.data)
If userID and password are present in response JSON then the user should be routed to next screen.
this.router.routeToDashboard();
I'm working on a project and I have the following issue.
I want to implement logic for user login with Passport API but I'm having difficulties of understanding how it works, especially the way I want to implement it (with plain SQL queries). I have gone thru several tutorials which explain how this can be done ,but the problem is that in them it is shown only with ORMs, and I do not want it that way. I've wrote a few thousand lines of code so far ,but without success which were deleted after this of course and this is the reason I haven't provided any code below.
I'm using MySQL and Express as frameworks to build the website. If you have any brief or advanced idea of how things can happen I will be happy to hear from you.
Thanks in advance !
Passport can be quite confusing at times, I'll give that to you! I'm assuming based on your question that you want to use the "local" login strategy and not offer something like Google or GitHub Single Sign On. I'll also assume you want to use "Sessions" (cookies) rather than something like JWT.
To do this you'll need to first configure passport with your express app up front. This requires you to initialise passport and a session store (you can use MySQL if you like, or something like Redis).
Then you need to configure your "strategy" which in our cases is the local strategy.
I'll run you through an example with some code that shows how this can be done. I'll shove this all into one code snippet but you may wish to break this out into several files.
Snippet you can clone:
https://gist.github.com/BlueHatbRit/5d07d3f98d41d536a776b74fcb843174
Mirrored here for answer longevity:
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
// Create the express app
const app = express();
// Initialise express-session module effectively deals with serilaising some
// form of ID in a cookie which is secured with the given secret. In this case
// express then remembers this ID in memory. When this cookie is handed
// back to your server, express-session takes that ID and matches it up to
// the data it has stored against that ID in memory. Remember, in production
// you will most probably want to hook this up to some sort of data store,
// either Redis, MySQL, etc...
app.use(session({ secret: "cats" }));
// We need some body parser setup to use Passport with express
// you can checkout the body parser and passport docs to find out why
app.use(bodyParser.urlencoded({ extended: false }));
// Now we initialise passport
app.use(passport.initialize());
// Now setup the session strategy, this happens after the express-session
// initialisation as that must run on a request first. Once we have the data
// from express-session (remember, it converted from a session ID given to
// the user via a cookie, back into the data we stored against the ID) we can
// then pull our any additional information.
app.use(passport.session());
passport.serializeUser(function(user, done) {
// This happens at the end of a request, it recieves the
// req.user object, and you can then choose what to serialise
// into the session (returning the user a new cookie with a
// session ID).
// In most cases you'll want to store as little data as possible
// so just a user.id might be fine.
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
// Assume we stored the user ID in the session in the above
// function call, we can now access it.
// You can now take "id" and pass it into your database and
// get back whatever you want in regards to the user. This may
// just be a small representation of the user, or the entire
// record.
// You can use either SQL or an ORM here. The important bit is
// that you call the "done" callback with whatever object you
// want to represent the user.
User.findById(id, function(err, user) {
// In your main request handlers, you will then call `req.user`
// and get back whatever you passed into the callback.
done(err, user);
});
});
// Now we setup the main "login" route, this will do the first round
// of authentication. It will take a username and password, will check
// those credentails and will then decide whether or not to log the user in.
passport.use(new LocalStrategy(function(username, password, done) {
// Run your SQL here to find the user by their username
// Then check their password is correct
// If something fails then call the "done" callback with a descriptive error
// otherwise call "done" with no error, and pass it the "user" object. This will
// be assigned to req.user which will then later be put through our serialize
// function above.
// In this case I'm using an ORM, but you can use something to execute raw SQL
// if you like.
User.findOne({ username: username }, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
// This is a made up function here, you'll need to create this and fill it out
// if you're using SQL you will probably have a function called "validPassword"
// (not assigned to a user object) where you will then pass in the hashed password
// from your database, and the password they provided you (the password string in this
// case).
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
// We have a user and the passwords match so we can return the user object!
return done(null, user);
}
});
// Now we need to mount our configured strategy to an endpoint
app.post('/login', function(req, res, next) {
passport.authenticate('local', {
successRedirect: '/dashboard', // The user logged in fine, redirect them do the dashboard
failureRedirect: '/login', // The login failed, send them back to the login page
// It is possible to use "connect-flash" here to send back the reason but that's outside of the scope of this
});
});
// Now we'll create some middleware to ensure a user is logged in when trying to access
// a protected endpoint
function protected(req, res, next) {
// req.user will only exist if they've been authenticated
if (!req.user) {
return next(new Error('nice try, but you are not logged in!');
}
return next();
}
app.get('/private-things', protected, function(req, res, next) {
// This code will only be accessible if someone goes to /private-things and
// has a valid session!
console.log(the user is logged in!);
console.log(req.user);
res.sendStatus(200);
});
A warning, I have not run this code. All the code is there though you might spot a few syntax errors and will need to write the SQL to match up to your database.
I have two problems, I need to be able to redirect users from facebook permissions acceptance from passportjs-facebook and from paypal payments redirect but I don't know how to do this in angular. I need to access posted JSON data coming from my own express server with an angular route which receives and uses that data.
If I do an a href="/auth" login button it sends my user to facebook's page to grant app permissions, after they do it redirects them to /auth/facebook/callback which is a blank white page with this json: {"ok":true,"status":"Login successful","success":true,"token":"...", user: {..}, }. How do I make it so they are redirected back to a page on my angular2 app and that this token is read into a json object within my apps so I can put it in local storage? This is my backend code:
userRouter.get('/auth', passport.authenticate('facebook', {scope: ['public_profile', 'user_friends', 'email']}), (req, res) => {});
userRouter.get('/auth/facebook/callback', function(req,res,next){
passport.authenticate('facebook', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Login failed'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful',
success: true,
token: token
});
});
})(req,res,next);
});
I'd use a res.redirect to the URL of one of your Angular pages, and include the token as a query string.
res.redirect('/#!/myprofile?token=MYTOKEN'); instead of the res.status(200).json... code
Alternatively you can parse the query string sent with the redirect right away in Angular as in this example, but I think that way can be a bit messy. That example will also help you through accessing query strings in Angular2.
So I have a html5 form with input fields. Lets say the fields are first name, last name, phone, email, and address.
Now first, last, and address are required while phone and email are optional. I know that the backend has this configured properly. However on the html5 form it will not let me submit without phone or email otherwise it returns a 400 error.
If I remove the optional from the html5 form, it will let me submit it or I can put in a value=" " and will submit also. I can even tag the fields with CSS3 using :required and :optional and it will show appropriately but still won't let me submit.
Now I obviously can't just remove the optional from the html because some users may need those fields but I also don't want to send a default value of " " or "n/a" for users who don't need them. Am I just doing something wrong here or what? I don't get what is going on.
edit 2: This is a node.js api using Hapi.js with Joi validation, request, and couchdb.
edit: I know that 400 is a server error but if I post with a curl omitting the optional ones it goes through fine. It also goes through fine when I remove the optional ones from the html which is why it doesn't make sense. Here is the validation code server side for the api.
handler: function(req, res) {
request({
method: 'POST',
uri: 'https://127.0.0.1:6984/banned',
jar: cookieJar,
strictSSL: false,
json: {
firstn: req.payload.firstn,
lastn: req.payload.lastn,
licno: req.payload.licno,
phone: req.payload.phone,
email: req.payload.email,
address: req.payload.address,
description: req.payload.description
}
},
function(err, resp, body) {
if (err) { res(err) };
if (resp.statusCode === 401) {
res(resp.statusCode + ' Please log in.');
}
else if (resp.statusCode === 201) {
res(body);
}
});
},
validate: {
payload: {
firstn: Joi.string().required(),
lastn: Joi.string().required(),
licno: Joi.string().optional(),
phone: Joi.string().optional(),
email: Joi.string().optional(),
address: Joi.string().optional(),
description: Joi.string().required()
}
}
So a friend helped me figure it out. What is happening is that required or not the html form is sending with a value of "" if no data is put in. That is not " ", "null", "undefined" just "". This is not a valid value for the server so it throws the 400 error. The code that fixed it was by checking if the payload exists before validating and sending it through.