Login System in NodeJS & Excel - node.js

So, I am creating a basic system which runs a login system in nodejs and express using an Excel file as a base. The excel CSV file will have a list of username and passwords and I am reading it using fast-csv. But when it is authenticating with the listing, it is matching only the first record. Not the other records in the excel. Any clue why? Code is as below:
index.js file
var express = require('express');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var csv = require('fast-csv')
var fs = require('fs')
app.listen(80, function(){
console.log("Server is running")
})
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({extended : true}));
app.post("/", function (req,res) {
fs.createReadStream(path.resolve(__dirname, 'master_data.csv'))
.pipe(csv.parse({ headers: true}))
.on('error', error => console.error(error))
.on('data', row => {
if(req.body.username == row.username && req.body.password === row.password && row.loggedIn == 'FALSE'){
res.send("Login Successful. <br> Your link is available below:" + row.link)
}else{
res.send("Login Failed")
}
})
// Log file created below
var userSchema = {
Username: req.body.username,
loginDateTime: new Date().toString(),
ipAddress: req.ip,
};
fs.appendFile('logfile.txt', JSON.stringify(userSchema) + ",", function(err, file){
if(err) throw (err);
})
});
index.html file
<html>
<head>
<title>School Login Page</title>
<link rel="stylesheet" type="text/css" href="./css/mainCSS.css">
</head>
<body>
<h2>School Login Page</h2><br>
<p>Please enter all details exactly as per details provided to you.</p>
<form action="/" method="POST">
<label for="username">Username</label>
<input type="text" id="username" name="username" value="" required><br><br>
<label for="password">Password</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="submit" id="submitButton">
</form>
</body>
</html>
I also want to create an alert for a failed login but I know that you cannot create alerts server side in nodejs. How can I do this is in the front-end? Thanks

The data event is fired for each row of the CSV. What you want is to check the username and password against all present records.
To achieve this, change the following:
fs.createReadStream(path.resolve(__dirname, 'master_data.csv'))
.pipe(csv.parse({ headers: true}))
.on('error', error => console.error(error))
.on('data', row => {
if(req.body.username == row.username && req.body.password === row.password && row.loggedIn == 'FALSE'){
res.send("Login Successful. <br> Your link is available below:" + row.link)
}else{
res.send("Login Failed")
}
})
to:
let isValid = false, rowLink;
fs.createReadStream(path.resolve(__dirname, 'master_data.csv'))
.pipe(csv.parse({ headers: true}))
.on('error', error => console.error(error))
.on('data', row => {
if(req.body.username == row.username && req.body.password === row.password && row.loggedIn == 'FALSE'){
isValid = true;
rowLink = row.link
}
})
.on('end', () => {
if (isValid) {
res.send("Login Successful. <br> Your link is available below:" + rowLink)
} else {
res.send("Login Failed")
}
})

Related

Connect nodemailer to form

I have a mail.js file that when run independently sends me a mail. And I have a form. I want to send mail to the email id that fils the form. How can I do that? I am not able to connect these two.
Where and how do I add mail.send();? And how to add variable email if both of these codes are in different files?
Also my html is in index.html
Thank you!!
index.html
<form action="/sign_up" method="POST" id="myForm">
<div>
<p class="cuboid-text">Subscribe</p>
</div>
<div>
<label for="submit" class="submit-icon">
<i class="fa fa-chevron-right"></i>
</label>
<input type="text" id="email" class="cuboid-text" placeholder="Your Email" autocomplete="off" name="email"/>
<input type="submit" id="submit" name="submit" class="submit" formaction="/sign_up" formmethod="POST"/>
</div>
<div>
<p class="cuboid-text loader">Just a moment ...
<i class="fa fa-spinner fa-pulse"></i>
</p>
</div>
<div>
<span class="reset-icon"><i class="fa fa-refresh"></i></span>
<p class="cuboid-text">Thankyou, we'll be in touch</p>
</div>
</form>
<script>
$("#email").focus(function () {
$("#cuboid form").addClass("ready");
})
//remove '.ready' when user blus away but only if there is no content
$("#email").blur(function () {
if ($(this).val() == "")
$("#cuboid form").removeClass("ready");
})
//If the user is typing something make the arrow green/.active
$("#email").keyup(function () {
//this adds .active class only if the input has some text
$(".submit-icon").toggleClass("active", $(this).val().length > 0);
})
$("#cuboid #myForm").submit(function () {
const re = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;
const email=document.getElementById("email").value;
const re1='abcd';
console.log(email);
//prevent default form submisson
if(re.test(String(email).toLowerCase())){
console.log("true");
document.getElementById("demo1").style.visibility="hidden";
$(this).removeClass("ready").addClass("loading");
setTimeout(complete, 3000);
return true;}
else{
document.getElementById("demo1").style.visibility="visible";
// setTimeout(complete, 1000);
return false;
}
})
function complete() {
$("#cuboid form").removeClass("loading").addClass("complete");
}
//reset/refresh functionality
$(".reset-icon").click(function () {
$("#cuboid form").removeClass("complete");
})
</script>
index.js
var express = require("express")
var bodyParser = require("body-parser")
var mongoose = require("mongoose")
const app = express()
app.use(bodyParser.json())
app.use(express.static('public'))
app.use(bodyParser.urlencoded({
extended: true
}))
mongoose.connect('mongodb://localhost:27017/mydb123', {
useNewUrlParser: true,
useUnifiedTopology: true
});
var db = mongoose.connection;
db.on('error', () => console.log("Error in Connecting to Database"));
db.once('open', () => console.log("Connected to Database"));
app.post("/sign_up", (req, res) => {
// var name = req.body.name;
var email = req.body.email;
// var phno = req.body.phno;
// var password = req.body.password;
// var initrefnum = req.body.demo;
// var newrefnum = req.body.newdemo;
console.log("step1");
var data = {
// "name": name,
"email": email
// "initrefnum": initrefnum,
// "newrefnum": newrefnum
}
db.collection('users').insertOne(data, (err, collection) => {
if (err) {
throw err;
}
console.log("Record Inserted Successfully");
});
// return res.redirect('index.html')
})
app.get("/", (req, res) => {
res.set({
"Allow-access-Allow-Origin": '*'
})
return res.redirect('index1.html');
}).listen(3000);
console.log("Listening on PORT 3000");
mail.js
const nodemailer=require('nodemailer')
let mailTransporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'mail#gmail.com',
pass: '*********'
}
});
let mailDetails = {
from: 'xyz#gmail.com',
to: 'abc#gmail.com',
subject: 'Test mail',
text: 'Node.js testing mail for GeeksforGeeks'
};
mailTransporter.sendMail(mailDetails, function(err, data) {
if(err) {
console.log('Error Occurs');
} else {
console.log('Email sent successfully');
}
});
Just this <input type="submit" id="submit" />
or
<button type="submit">Submit</button> is fine
app.use(express.static('public')) // this is enough in case if you think what more to do to wire up.
Mail.js
const nodemailer = require('nodemailer');
let mailTransporter = nodemailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
auth: {
user: 'dee#gmail.com', //this should be same as 'from' address
pass: 'workingpassword'
}
});
module.exports = mailTransporter;
App.js
const mailTransporter = require('./mail);
for your form action, in your /sign_up post method do below
app.post('/sign_up', (req, res)=>{
mailTransporter.sendMail({
from: 'dee#gmail.com', //this should be same as above auth.user
to: `${req.body.email}`,
subject: 'Test',
text: 'hello',
html: `Hello ${req.body.name} thank you for contacting. We will get in touch`
}).then(res=>{
console.log("success........", res)
resp.send(`email sent to ${req.body.name}` successfully);
}).catch(e=>{
console.log("failed........", e)
});
});
Things to do to avoid issues,
go to https://myaccount.google.com/lesssecureapps and enable for less secure apps.
go to https://accounts.google.com/DisplayUnlockCaptcha and enable.

Images not appearing in the MongoDB database

I am uploading a form that contains an image to my mongodb database, all the data is there as should be however the images are not appearing on the database. Does it have anything to do with the fact i an unable to add propertyImage: req.file.path as I get the error of 'typeError cannot read property of 'path' od undefined'. The reason I want them in the database is to enable me to fetch them and attach the images to the relevant product.
I have the backend code below, as for the front end I am going to assume that I need to create something with formData in order to send the the text fields with the image. If so could someone point me in the right direction as I am not sure where to start so that It wont affect my user authorization set up as detailed below.
const express = require('express');
const userRouter = express.Router();
const passport = require('passport');
const passportConfig = require('../passport');
const JWT = require('jsonwebtoken');
const User = require('../models/User');
const Property = require('../models/Property');
const multer = require('multer')
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, "./uploads/");
},
filename: (req, file, callback) => {
callback(null, file.originalname);
}
})
const upload = multer({storage: storage});
const signToken = userID => {
return JWT.sign({
iss : "Moove",
sub : userID
},"Moove",{expiresIn :"1h"});
}
userRouter.post('/register',(req,res)=>{
const {username,name,email,password} = req.body;
User.findOne({email},(err,user)=>{
if(err)
res.status(500).json({message : {msgBody: "Error has occured", msgError : true}});
if(user)
res.status(400).json({message : {msgBody: "Email has already been used, Please log in", msgError : true}});
else{
const newUser = new User({username,name,email,password});
newUser.save(err=>{
if(err)
res.status(500).json({message : {msgBody: "Error has occured", msgError : true}});
else
res.status(201).json({message : {msgBody: "Account Successfully Created", msgError : false}});
});
};
});
});
userRouter.post('/login',passport.authenticate('local',{session : false}),(req,res)=>{
if(req.isAuthenticated()){
const {_id,username,password} = req.user;
const token = signToken(_id);
res.cookie('access_token',token,{httpOnly: true, sameSite:true});
res.status(200).json({isAuthenticated : true,user : {username,password}});
}
});
userRouter.get('/logout',passport.authenticate('jwt',{session : false}),(req,res)=>{
res.clearCookie('access_token');
res.json({user:{username:''},success : true})
});
userRouter.post('/property', upload.single('propertyImage'),passport.authenticate('jwt',{session : false}),(req,res)=>{
console.log(req.file);
const property = new Property({
street: req.body.street,
town: req.body.town,
area: req.body.area,
PostCode: req.body.PostCode,
NoBeds: req.body.NoBeds,
NoBath: req.body.NoBath,
NoLivingRooms: req.body.NoLivingRooms,
askingPrice: req.body.askingPrice,
propertyImage: req.file
});
property.save(err=> {
if(err)
res.status(500).json({message : {msgBody: "Error has occured", msgError : true}});
else{
req.user.properties.push(property);
req.user.save(err=> {
if(err)
res.status(500).json({message : {msgBody: "Error has occured", msgError : true}});
else
res.status(200).json({message: {msgBody: "Successfully created property", msgError : false}});
})
}
})
});
userRouter.get('/properties',passport.authenticate('jwt',{session : false}),(req,res)=>{
User.findById({_id : req.user._id}).populate('properties').exec((err,document)=>{
if(err)
res.status(500).json({message : {msgBody : "Error has occured", msgError: true}});
else{
res.status(200).json({properties : document.properties, authenticated : true});
}
});
});
userRouter.get('/property',passport.authenticate('jwt',{session : false}),(req,res)=>{
User.findById({_id : req.user._id}).populate('properties').exec((err,document)=>{
if(err)
res.status(500).json({message : {msgBody : "Error has occured", msgError: true}});
else{
res.status(200).json({properties : document.properties, authenticated : true});
}
});
});
userRouter.get('/authenticated',passport.authenticate('jwt',{session : false}),(req,res)=>{
const {username} = req.user;
res.status(200).json({isAuthenticated : true, user: {username}})
});
module.exports = userRouter;
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import React, {useState,useContext, useEffect} from 'react'
import PropertyItem from './PropertyItem';
import PropertyService from '../Services/PropertyService';
import Message from './Message'
import {AuthContext} from '../Context/AuthContext';
const Properties = props =>{
const [property,setProperty] = useState({
// propertyImage: "",
street : "",
town : "",
area : "",
PostCode : "",
NoBeds : "",
NoBath : "",
NoLivingRooms : "",
askingPrice: "",
})
const [properties,setProperties] = useState ([]);
// const [propertyImage,setPropertyImage] = useState ([]);
const [message,setMessage] = useState(null);
const authContext = useContext(AuthContext);
useEffect(()=>{
PropertyService.getProperties().then(data =>{
setProperties(data.properties);
});
},[]);
const onSubmit = e =>{
e.preventDefault();
PropertyService.postProperty(property).then(data =>{
const {message } = data;
resetForm();
if(!message.msgError){
PropertyService.getProperties().then(getData =>{
setProperties(getData.properties);
setMessage(message);
});
}
else if(message.msgBody === "UnAuthorized"){
setMessage(message);
authContext.setUser({username : ""});
authContext.setIsAuthenticated(false);
}
else{
setMessage(message);
}
},[]);
}
const onChange = e =>{
setProperty({...property,[e.target.name] : e.target.value})
}
// const onChangefile = e =>{
// setPropertyImage(e.target.files[0])
// }
const resetForm = ()=>{
setProperty({
propertyImage: "",
street : "",
town : "",
area : "",
PostCode : "",
NoBeds : "",
NoBath : "",
NoLivingRooms : "",
askingPrice : "",
});
}
return(
<div>
<ul className="">
{
properties.map((property) =>{
return <PropertyItem key={property._id}
property={property}
street={property.street}
town={property.town}
area={property.area}
PostCode={property.PostCode}
NoBeds={property.NoBeds}
NoBath={property.NoBath}
NoLivingRooms={property.NoLivingRooms}
askingPrice={property.askingPrice}
propertyImage={property.propertyImage}
/>
},[])
}
</ul>
<br/>
<form onSubmit={onSubmit} encType="multipart/form-data">
<label htmlFor="street">Street Name</label>
<input type="text"
name="street"
value={property.street}
onChange={onChange}
className=""
placeholder="street name"/>
<label htmlFor="town">Town</label>
<input type="text"
name="town"
value={property.town}
onChange={onChange}
className=""
placeholder="town"/>
<label htmlFor="area">Area</label>
<input type="text"
name="area"
value={property.area}
onChange={onChange}
className=""
placeholder="area"/>
<label htmlFor="postcode">Postcode</label>
<input type="text"
name="PostCode"
value={property.PostCode}
onChange={onChange}
className=""
placeholder="Postcode"/>
<label htmlFor="NoBeds">Beds</label>
<input type="number"
name="NoBeds"
value={property.NoBeds}
onChange={onChange}
className=""
placeholder="Number of beds"/>
<label htmlFor="NoBath">Bathrooms</label>
<input type="number"
name="NoBath"
value={property.NoBath}
onChange={onChange}
className=""
placeholder="Number of bathrooms"/>
<label htmlFor="NoLivingRooms">Living Rroom</label>
<input type="number"
name="NoLivingRooms"
value={property.NoLivingRooms}
onChange={onChange}
className=""
placeholder="Number of living rooms"/>
<label htmlFor="askingPrice">Asking Price(£)</label>
<input type="number"
name="askingPrice"
value={property.askingPrice}
onChange={onChange}
className=""
placeholder="£249,999"/>
<label htmlFor="propertyImage">Property Images</label>
<input type="file"
filename="propertyImage"
onChange={onChange}
className=""
placeholder="Upload property images"/>
<button className=""
type="submit">Submit</button>
</form>
{message ? <Message message={message}/> : null}
</div>
);
}
export default Properties
You have to deal with your file input <input type="file"... differently to normal text fields. File inputs react differently to normal fields. They take an on change event, which updates when a user selects a file, and converts to a blob. You need to convert this to base64 and then send the base64 to the server (or a proper image hosting service such as cloudinary).
Here's a demo:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="file" id='file'/>
<script src='./app.js'></script>
</body>
</html>
app.js
const fileReader = document.getElementById('file')
const getBase64 = (file) => {
return new Promise((resolve, reject) => {
const fr = new FileReader()
console.log(file instanceof Blob) // Should be true
fr.readAsDataURL(file)
fr.onerror = reject
fr.onload = function () {
resolve(fr.result)
}
})
}
fileReader.addEventListener('change', (e) => {
console.log(e.target.files[0])
getBase64(e.target.files[0]).then((res) => console.log(res) )
})
In the JS above, we are getting the file reader input as an element and setting an onChange event to it, which calls the getBase64 function. The getBase64 function returns a Promise, that is fulfilled after the file has been read. Inside that function, we create a new FileReader as fr, then call fr.readDataAsURL(file) which converts your file to base64, and then resolve it in fr.onload. You can then call the output of that using getBase64(file).then(res => doSomething(res)).
Create a directory with those 2 files, and then test out the functionality. When you select a file, you should see a really long string of characters (Base64), and this is what you should post to your image hosting service.
I believe you can post base64 to MongoDB, though it is not recommended.

Inserting Data into phpmyadmin using node.js express and reactjs

I have a table in my database called products and I am trying to insert into in using node.js express server as the web service and react.js as the front-end language.
Below is my react.js form to perform the insertion.
function App() {
return (
<div className="container">
<form onSubmit = {(e) => Add(e)}>
<div className="form-group">
<label htmlFor="examplePname">Name</label>
<input type="text" className="form-control" id="examplePname" aria-describedby=""/>
</div>
<div className="form-group">
<label htmlFor="examplePprice">Price</label>
<input type="number" className="form-control" id="examplePprice"/>
</div>
<div className="form-group form-check">
<input type="checkbox" className="form-check-input" id="exampleCheck1"/>
<label className="form-check-label" htmlFor="exampleCheck1">Check me out</label>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
);
}
function Add(e){
e.preventDefault();
let request = {
name: document.getElementById('examplePname').value,
price: document.getElementById('examplePprice').value,
}
alert("returns this:"+ request)
axios.post('http://localhost:3000/add', request)
.then(resp => {
alert(resp.data.message);
})
.catch(err => {
console.log(err);
})
}
Below is my node.js express Webservice
router.post('/add', (req, res) => {
const {name, price} = req.query;
console.log(name, price); ///Do this before you write the insert query
//res.send('adding product');Do this before you write the insert query (add temp products to view in cmd)
const INSERT_QUERY = `INSERT INTO products (name, price) VALUES('${name}', ${price})`; //after do an insert query to add to db proper
connection.query(INSERT_QUERY, (err, results) => {
if (err) {
return res.send({
message: "failed"
})
} else {
return res.send({
message: "successful"
});
}
});
});
But when I insert I get undefined values for both name and price in console.log.
Use Below code in app.js in node side for parsing parameter
const bodyparser = require('body-parser');
const multer = require('multer');
//Multer
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './Images');
},
filename: function (req, file, cb) {
let fileType = file.originalname.split('.');
cb(null, `${fileType[0]}_${Date.now()}.${fileType[1]}`);
}
})
var upload = multer({ storage: storage });
app.use(upload.any());
// Parse
app.use(bodyparser.json({ limit: '50mb', extended: true }));
app.use(bodyparser.urlencoded({ limit: '50mb', extended: true, parameterLimit: 1000000 }));
Please install above dependencies before restart the server
React side send form data as below
createFormData(props) {
var formData = new FormData();
for (var key in props) {
if (typeof props[key] === "string" || props[key] instanceof Date) {
formData.append(key, props[key]);
}
else if (typeof props[key] === "object") {
if (Array.isArray(props[key]) && key === "file") {
//Multiple File Upload
props[key].length > 0 && props[key].forEach((element) => {
if (element.lastModifiedDate) {
formData.append(key, element);
}
})
}
else if (props[key] && props[key].lastModifiedDate) {
//Single File Upload
formData.append(key, props[key]);
} else {
formData.append(key, JSON.stringify(props[key]));
}
} else {
formData.append(key, JSON.stringify(props[key]));
}
}
return formData;
}
// Axios Request
axios({
url: url here,
method: 'POST',
data: this.createFormData(your form data object),
timeout: 30000
}).then(response => {
if (response.status === 200) {
}
})
you will get data as follow at node side
let data = { ...req.body, ...req.params, ...req.query }

How to insert and retrieve video from mongodb in node js

I new to mean stack. I want to upload video to mongodb and then I want to retrieve it.
this is app.js file
`const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const crypto = require('crypto');
const mongoose = require('mongoose');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const methodOverride = require('method-override');
const app = express();
// Middleware
app.use(bodyParser.json());
app.use(methodOverride('_method'));
app.set('view engine', 'ejs');
// Mongo URI
const mongoURI = 'mongodb://fawad:Fawad123#ds155243.mlab.com:55243/imageupload';
// Create mongo connection
const conn = mongoose.createConnection(mongoURI);
// Init gfs
let gfs;
conn.once('open', () => {
// Init stream
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('uploads');
});
// Create storage engine
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
// #route GET /
// #desc Loads form
app.get('/', (req, res) => {
gfs.files.find().toArray((err, files) => {
// Check if files
if (!files || files.length === 0) {
res.render('index', { files: false });
} else {
files.map(file => {
if (
file.contentType === 'video/mp4' ||
file.contentType === 'video/webm '
) {
file.isVideo = true;
} else {
file.isVideo = false;
}
});
res.render('index', { files: files });
}
});
});
// #route POST /upload
// #desc Uploads file to DB
app.post('/upload', upload.single('file'), (req, res) => {
// res.json({ file: req.file });
res.redirect('/');
});
// #route GET /files
// #desc Display all files in JSON
app.get('/files', (req, res) => {
gfs.files.find().toArray((err, files) => {
// Check if files
if (!files || files.length === 0) {
return res.status(404).json({
err: 'No files exist'
});
}
// Files exist
return res.json(files);
});
});
// #route GET /files/:filename
// #desc Display single file object
app.get('/files/:filename', (req, res) => {
gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
// Check if file
if (!file || file.length === 0) {
return res.status(404).json({
err: 'No file exists'
});
}
// File exists
return res.json(file);
});
});
// #route GET /image/:filename
// #desc Display Image
app.get('/video/:filename', (req, res) => {
gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
// Check if file
if (!file || file.length === 0) {
return res.status(404).json({
err: 'No file exists'
});
}
// Check if image
if (file.contentType === 'video/mp4' || file.contentType === 'video/webm') {
// Read output to browser
const readstream = gfs.createReadStream(file.filename);
readstream.pipe(res);
} else {
res.status(404).json({
err: 'Not an image'
});
}
});
});
// #route DELETE /files/:id
// #desc Delete file
app.delete('/files/:id', (req, res) => {
gfs.remove({ _id: req.params.id, root: 'uploads' }, (err, gridStore) => {
if (err) {
return res.status(404).json({ err: err });
}
res.redirect('/');
});
});
const port = 9000;
app.listen(port, () => console.log(`Server started on port ${port}`));
`
index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<style>
video {
width: 100%;
}
</style>
<title>Mongo File Uploads</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 m-auto">
<h1 class="text-center display-4 my-4">Mongo File Uploads</h1>
<form action="/upload" method="POST" enctype="multipart/form-data">
<div class="custom-file mb-3">
<input type="file" name="file" id="file" class="custom-file-input">
<label for="file" class="custom-file-label">Choose File</label>
</div>
<input type="submit" value="Submit" class="btn btn-primary btn-block">
</form>
<hr>
<% if(files){ %>
<% files.forEach(function(file) { %>
<div class="card card-body mb-3">
<% if(file.isVideo) { %>
<video src="video/<%= file.filename %>" alt="">
<% } else { %>
<%= file.filename %>
<% } %>
<form method="POST" action="/files/<%= file._id %>?_method=DELETE">
<button class="btn btn-danger btn-block mt-4">Delete</button>
</form>
</div>
<% }) %>
<% } else { %>
<p>No files to show</p>
<% } %>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
</body>
</html>
this code work for image..when I used (file.contentType = image/png).
but for video it's not working.. is Image and video upload are same?
You can use Formidable. As It support multipart data. And for retrieve video you can use fs(file system)
Actually you don't save media(image or video) in DB, you store it in some storage drive(locally or cloud) like s3 bucket, and then store its location url in your DB.
and this code might be helpful.
saveImage(urlPath, folderPath, multiple) {
return new Promise((resolve, reject) => {
var timestamp = Date.now();
var filepath = urlPath;
var imageUrl;
var ext = path.extname(filepath || '').split('.');
var extension = ext[ext.length - 1];
var tmp_path = filepath;
imageUrl = folderPath + timestamp + '.' + extension;
if (multiple != '' && multiple != undefined) { imageUrl = folderPath + timestamp + multiple + '.' + extension; }
var target_path = __dirname + '/../' + imageUrl;//Change according to your location.
console.log("target_path", target_path);
mv(tmp_path, target_path, { mkdirp: true }, function (err) { })
return resolve({ status: 1, url: imageUrl });
})
}
Now, urlPath is your media path, foldarPath is path where you want to store your media and multiple is to give unique name.
you can call this method like this.
var multiple = Number(0) + Number(10);
console.log("multiple", multiple);
var saveImage = await 'YOUR_FILE_NAME'.saveImage(files.photo[0].path, 'public/Image/', multiple);
console.log(saveImage);
<video src="video/<%= file.filename %>" controls alt="">
//Try adding the controls command in the video tag. It helps the video run.

expressjs ldap authentication showing basic auth pop up form

I'm a newbie to expressjs and ldap.
Need your help with getting my way through the code flow.
I need to authenticate user credentials against ldap server.
I'm using this ldap library https://github.com/vesse/node-ldapauth-fork for making it work.
I get the pop-up form on my broswer that asks for my basic auth credentials after I have submitted the login credentials with the login form(loginCtrl.js).
When i enter the credentials into the popup, the backends sees them as "undefined"
My question is why is the basic auth form popping up, if I'm already sending teh credentials via loginCtrl.js
This is my front end code that calls the REST api
login.html
app.controller("loginCtrl", ["$scope", "$http", "$location","$document", "$uibModal", "$filter", "$q", function($scope, $http, $location, $document, $uibModal, $filter, $q) {
$scope.keepLoggedIn = false;
$scope.login = function() {
var body = {};
body["username"] = $scope.username;
body["password"] = $scope.password;
var auth = window.btoa($scope.username+":"+$scope.password);
console.log(auth);
/* $http.post('/login', JSON.stringify(credentials)).then(function(success){
console.log("success");
}, function(error){
console.error("error");
});*/
var results = [];
$http({
method: 'POST',
headers: {'Authorization': "Basic " + auth},
url: '/login',
data: JSON.stringify(body)
})
.then(function (success) {
console.log(success);
results.push(success);
}, function (error) {
results.push(error.data);
});
}
}]);
<div id="container">
<form ng-submit="login()">
<label for="username">Username:</label>
<input type="text" ng-model="username" id="username" name="username">
<label for="password">Password:</label>
<input type="password" ng-model="password" id="password" name="password">
<div id="lower">
<input type="checkbox" ng-model="keepLoggedIn"><label for="checkbox">Keep me logged in</label>
<input type="submit" value="Login">
</div><!--/ lower-->
</form>
</div>
This is the expressjs server code that uses ldapauth to authenticate against ldap
var express = require('express');
var basicAuth = require('basic-auth');
var LdapAuth = require('ldapauth-fork');
var app = express();
var ldap = new LdapAuth({
url: 'ldap://ldapserver.net:389',
bindDN: 'uid=root,ou=sample,dc=dept,dc=net',
bindCredentials: 'secret',
searchBase: 'ou=sample,dc=dept,dc=net',
searchFilter: '(uid={{username}})',
reconnect: true
});
ldap.on('error', function (err) {
console.error('LdapAuth: ', err);
});
var rejectBasicAuth = function(res) {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Example"');
res.end('Access denied');
}
var basicAuthMiddleware = function(req, res, next) {
ldap.authenticate(req.body.username, req.body.password, function(err, user) {
console.log("callback:"+user);
if (err) {
console.log(err);
return rejectBasicAuth(res);
}
console.log("success");
req.user = user;
next();
});
};
app.post('/login',basicAuthMiddleware, function(req,res){
res.send({"status":"ok"});
});
app.listen(2500, function(){
console.log('Express started on http://localhost:' + 2500 + '; press Ctrl-C to terminate.');
});

Resources