Translate
Friday, 28 February 2020
GhostCat: New High-Risk Vulnerability Affects Servers Running Apache Tomcat
Week in security with Tony Anscombe
ESET research uncovers a vulnerability in Wi-Fi chips – How to protect yourself against tax refund fraud – Clearview AI suffers a data breach
The post Week in security with Tony Anscombe appeared first on WeLiveSecurity
Digital Age Challenges: Data Breaches of 2019
The digital era has come with its fair share of scams with data breaches being the most prevalent. This problem
Digital Age Challenges: Data Breaches of 2019 on Latest Hacking News.
Signal Jamming: Different Techniques And Where They Are Used
The way we communicate has changed a lot over the years. From handwritten letters to electronic e-mails to smoke signals
Signal Jamming: Different Techniques And Where They Are Used on Latest Hacking News.
Firefox turns on DNS over HTTPS by default for US users
People in other parts of the world also have the option to flip on DNS encryption
The post Firefox turns on DNS over HTTPS by default for US users appeared first on WeLiveSecurity
Let's Encrypt Issued A Billion Free SSL Certificates in the Last 4 Years
Cyberbullying: How is it different from face‑to‑face bullying?
The digital age has added a whole new dimension to hurtful behavior, and we look at some of the key features that set in-person and online bullying apart
The post Cyberbullying: How is it different from face‑to‑face bullying? appeared first on WeLiveSecurity
Why Businesses Should Consider Managed Cloud-Based WAF Protection
Thursday, 27 February 2020
OpenSMTPD Email Server Vulnerability Threatens Many Linux and BSD Systems
A critical vulnerability has been discovered in the OpenBSD email server OpenSMTPD. Exploiting the flaw could allow remote code execution
OpenSMTPD Email Server Vulnerability Threatens Many Linux and BSD Systems on Latest Hacking News.
How to Design for Screen Readers with Adobe XD CC
When it comes to accessibility, designers tend to focus on colors (i.e. contrast) and UX copy (i.e. wording), whereas developers tend to focus on ARIA attributes (i.e. code that makes websites more accessible). This is due to the fact that, often enough, thick lines are drawn between “who does what”.
Also, because creating accessible apps and websites isn’t considered to be exciting, this line is hardly ever questioned.
Accessibility is still a black sheep, even in 2020.
So, since UX copy is the responsibility of the designer and ARIA attributes are the responsibility of the developer, exactly whose responsibility is it to cater for screen readers? Since:
- Screen reader UX copy is expressed as Braille or dictation (so how do we communicate this when our UI tools are visual?)
- Implementation is developer territory (so can we really shift the responsibility of writing UX copy to developers?)
As you can see, it’s a two-person job — and yet, the tools simply don’t exist to facilitate this. I mean, make no mistake, some aspects of accessibility design are one-sided (for example, UI designers can very easily take care of color contrast by themselves). However, other aspects such as designing for screen readers requires collaboration between designers and developers.
This is where Adobe XD CC’s design handoff and voice prototyping features come in handy. In this article, we’ll discuss what to consider when designing for screen readers, and we’ll also walk through how to use the features mentioned above.
What Are Screen Readers?
A screen reader is a type of assistive technology that communicates what’s happening on the screen (for those with visual impairments). Screen reader software can be used in combination with the keyboard (for example, users will tab and enter as opposed to using the mouse), but it can also be used in combination with screen reader hardware, which allows for more efficient navigation and also caters for users that use Braille.
If you’re an Apple user, for example, you’ll be somewhat aware of Apple VoiceOver, which is the native Apple dictation software that acts as a screen reader. Windows users, however, commonly use either JAWS or NVDA, since there aren’t any native screen reader tools in the Windows operating system.
Let’s dive in.
1. Use Headings
Screen readers often use headings as a way of deciphering a website’s structure, and if we think too visually we run the risk of leaving out these headings. In the example below, the omission of the “Chapters” heading causes screen readers to assume that the list of chapters is a continuation of the content on the left-hand side, which it obviously isn’t.
As a result, screen-reader users won’t be able to skip to “Chapters”, and they might not discover the information within.
While there are code workarounds available (such as the aria-label
attribute), having a visible heading inclusively offers a clearer experience for everybody, whether disabled or not.
Of course, the section is very obviously a list of chapters, as we can infer from the context (i.e. the content). However, those using screen readers very rarely have the luxury of context. It’s like trying to find an object in storage where none of the boxes are labeled. Our designs need these labels and headings.
On the technical side, the rule is that every section (as defined by a <section>
or <article>
tag) should have not only a heading, but an explicit heading that conflicts with no other heading. As an example, if the highest level heading within a section is an <h2>
, then there should be no other <h2>
heading within that section. Otherwise, screen readers are clueless as to which heading is the label for the section.
The post How to Design for Screen Readers with Adobe XD CC appeared first on SitePoint.
Facial recognition company Clearview AI hit by data theft
The startup came under scrutiny after it emerged that it had amassed 3 billion photos for facial recognition software
The post Facial recognition company Clearview AI hit by data theft appeared first on WeLiveSecurity
RSA 2020 – Hacking humans
What the human battle against biological viruses can teach us about fighting computer infections – and vice versa
The post RSA 2020 – Hacking humans appeared first on WeLiveSecurity
Zyxel Patched Zero-Day RCE Vulnerability In NAS Devices
The latest victim of an actively exploited zero-day vulnerability is the Taiwan-based firm ‘Zyxel’ whom manufacture networking devices. Zyxel has
Zyxel Patched Zero-Day RCE Vulnerability In NAS Devices on Latest Hacking News.
Did someone file your taxes before you?
With tax season – and tax scams – in full swing, here’s how fraudsters can steal your tax refund and how you can avoid becoming a victim
The post Did someone file your taxes before you? appeared first on WeLiveSecurity
Python Read File Into List
In this tutorial we are going to see how we can read a file and store the content of the file into a python list. While working with python many a times data is stored into text files or csv files and to use that data into our code it must be brought to the python code.
In this tutorial we will see different methods on how it can be done efficiently and with as little code as possible.
Python Read File Into List
Using with Keyword
We can use the with keyword provided by python for our job. First we need to open the file with the open() method which will take the filepath as argument and return a file descriptor to the file. We can then loop over all the lines in the file and append them one by one to our list. The code will look as below:
with open("./readfile.txt") as file : for line in file : line.strip() lines.append(line) print(lines)
Note: Watch your backslashes in windows path names, as those are also escape chars in strings. You can use forward slashes or double backslashes instead.
The strip method is only used to remove any whitespace characters like \n at the end of the lines.
There is a small problem with the above code, once opened we cannot close the file again so it is advised to first open file using a file descriptor which can be then used to close the same.
lines = [] file = open("./readfile.txt") for line in file : lines.append(line) file.close() print(lines)
The code can further shortened as:
file = open("./readfile.txt") lines = [line for line in file] file.close() print(lines)
Traditional Method of Reading File
We can use the traditional method where we will first read the file and separate the file when we encounter some special character. If we want to split the file line by line the special character will be \n. If we want to split the file word by word then we can use space as a special character. The code will look like :
file = open("./readfile.txt") lines = file.read().split('\n') file.close() print(lines)
Using readlines() Method
The readlines() method can also be used directly to read lines and store them into a list in python. The code for the same will look as below:
file = open("./readfile.txt") lines = file.readlines() file.close() print(lines)
readlines() will not remove the \n at the end of the file so if we want the \n to be removed we again need to use the strip method to get the work done.
Using splitlines() Method
The splitlines method will strip all the whitespace characters at the end of the lines and return a list containing the lines of the file.
file = open("./readfile.txt") lines = file.read().splitlines() file.close() print(lines)
Using list() Method:
We can use the list method provided by python to convert a file into list. list method will not remove the \n at the end of the file.
file = open("./readfile.txt") lines = list(file) file.close() print(lines)
Using tuple() Method
tuple can take an iterator and instantiate a tuple instance for you from the iterator that you give it. lines is a tuple created from the lines of the file. This will yield an array of lines from the file.
file = open("./readfile.txt") lines = tuple(file) file.close() print(lines)
The use of method depends on the application on which python is used. splitlines() method is most commonly used for splitting a file into lines. The split() method is considered more generic as it allows split lines using the character of our choice and not just when a new line appears.
The post Python Read File Into List appeared first on The Crazy Programmer.
Wednesday, 26 February 2020
New Wi-Fi Encryption Vulnerability Affects Over A Billion Devices
Is bug hunting a viable career choice?
With earnings of top ethical hackers surpassing hundreds of thousands of dollars, some would say yes
The post Is bug hunting a viable career choice? appeared first on WeLiveSecurity
KrØØk: Serious vulnerability affected encryption of billion+ Wi‑Fi devices
ESET researchers uncover a previously unknown security flaw allowing an adversary to decrypt some wireless network packets transmitted by vulnerable devices
The post KrØØk: Serious vulnerability affected encryption of billion+ Wi‑Fi devices appeared first on WeLiveSecurity
New LTE Network Flaw Could Let Attackers Impersonate 4G Mobile Users
Google Patch Serious Chrome Bugs Including A Zero-Day Under Active Exploit
Google have recently fixed numerous security bugs in their Chrome browser. These Chrome bugs include two serious vulnerabilities as well
Google Patch Serious Chrome Bugs Including A Zero-Day Under Active Exploit on Latest Hacking News.
Google Advises Android Developers to Encrypt App Data On Device
The History of the Flash Drive
Flash drives and memory cards are the two types of data storage devices that are the most mobile. Bulk Memory
The History of the Flash Drive on Latest Hacking News.
Tuesday, 25 February 2020
10 Ways to Hide Elements in CSS
There are multiple ways to hide an element in CSS, but they differ in the way they affect accessibility, layout, animation, performance, and event handling.
Animation
Some CSS hiding options are all or nothing. The element is either fully visible or fully invisible and there’s no in-between state. Others, such as transparency, can have a range of values, so interpolated CSS animations become possible.
Accessibility
Each method described below will visually hide an element, but it may or may not hide the content from assistive technologies. For example, a screen reader could still announce tiny transparent text. Further CSS properties or ARIA attributes such as aria-hidden="true"
may be necessary to describe the appropriate action.
Be wary that animations can also cause disorientation, migraines, seizures, or other physical discomfort for some people. Consider using a prefers-reduced-motion
media query to switch off animations when specified in user preferences.
Event Handling
Hiding will either stop events being triggered on that element or have no effect — that is, the element is not visible but can still be clicked or receive other user interactions.
Performance
After a browser loads and parses the HTML DOM and CSS object model, the page is rendered in three stages:
- Layout: generate the geometry and position of each element
- Paint: draw out the pixels for each element
- Composition: position element layers in the appropriate order
An effect which only causes composition changes is noticeably smoother than those affecting layout. In some cases, the browser can also use hardware acceleration.
1. opacity
and filter: opacity()
The opacity: N
and filter: opacity(N)
properties can be passed a number between 0 and 1, or a percentage between 0% and 100% denoting fully transparent and fully opaque accordingly.
See the Pen
hide with opacity: 0 by SitePoint (@SitePoint)
on CodePen.
There’s little practical difference between the two in modern browsers, although filter
should be used if multiple effects are applied at the same time (blur, contrast, grayscale etc.)
Opacity can be animated and offers great performance, but be wary that a fully transparent element remains on the page and can trigger events.
metric | effect |
---|---|
browser support | good, but IE only supports opacity 0 to 1 |
accessibility | content not read if 0 or 0% is set |
layout affected? | no |
rendering required | composition |
performance | best, can use hardware acceleration |
animation frames possible? | yes |
events triggered when hidden? | yes |
2. color
Alpha Transparency
opacity
affects the whole element, but it's also possible to set the color
, background-color
, and border-color
properties separately. Applying a zero alpha channel using rgba(0,0,0,0)
or similar renders an item fully transparent:
See the Pen
hide with color alpha by SitePoint (@SitePoint)
on CodePen.
Each property can be animated separately to create interesting effects. Note that transparency can’t be applied to elements with image backgrounds unless they're generated using linear-gradient
or similar.
The alpha channel can be set with:
transparent
: fully transparent (in-between animations are not possible)rgba(r, g, b, a)
: red, green, blue, and alphahsla(h, s, l, a)
: hue, saturation, lightness, and alpha#RRGGBBAA
and#RGBA
metric | effect |
---|---|
browser support | good, but IE only supports transparent and rgba |
accessibility | content still read |
layout affected? | no |
rendering required | painting |
performance | good, but not as fast as opacity |
animation frames possible? | yes |
events triggered when hidden? | yes |
3. transform
The transform
property can be used to translate (move), scale, rotate, or skew an element. A scale(0)
or translate(-999px, 0px)
off-screen will hide the element:
See the Pen
hide with transform: scale(0); by SitePoint (@SitePoint)
on CodePen.
transform
offers excellent performance and hardware acceleration because the element is effectively moved into a separate layer and can be animated in 2D or 3D. The original layout space remains as is, but no events will be triggered by a fully hidden element.
metric | effect |
---|---|
browser support | good |
accessibility | content still read |
layout affected? | no — the original dimensions remain |
rendering required | composition |
performance | best, can use hardware acceleration |
animation frames possible? | yes |
events triggered when hidden? | no |
The post 10 Ways to Hide Elements in CSS appeared first on SitePoint.
Build a Simple Beginner App with Node, Bootstrap and MongoDB
If you’re just getting started with Node.js and want to try your hand at building a web app, things can often get a little overwhelming. Once you get beyond the “Hello, World!” tutorials, much of the material out there has you copy-pasting code, with little or no explanation as to what you’re doing or why.
This means that, by the time you’ve finished, you’ve built something nice and shiny, but you also have relatively few takeaways that you can apply to your next project.
In this tutorial, I’m going to take a slightly different approach. Starting from the ground up, I’ll demonstrate how to build a no-frills web app using Node.js, but instead of focusing on the end result, I’ll focus on a range of things you’re likely to encounter when building a real-world app. These include routing, templating, dealing with forms, interacting with a database and even basic authentication.
This won’t be a JavaScript 101. If that’s the kind of thing you’re after, look here. It will, however, be suitable for those people who feel reasonably confident with the JavaScript language, and who are looking to take their first steps in Node.js.
What We’ll Be Building
We’ll be using Node.js and the Express framework to build a simple registration form with basic validation, which persists its data to a MongoDB database. We’ll add a view to list successful registration, which we’ll protect with basic HTTP authentication, and we’ll use Bootstrap to add some styling. The tutorial is structured so that you can follow along step by step. However, if you’d like to jump ahead and see the end result, the code for this tutorial is also available on GitHub.
Basic Setup
Before we can start coding, we’ll need to get Node, npm and MongoDB installed on our machines. I won’t go into depth on the various installation instructions, but if you have any trouble getting set up, please visit our forums and ask for help there.
Node.js
Many websites will recommend that you head to the official Node download page and grab the Node binaries for your system. While that works, I would suggest that you use a version manager instead. This is a program which allows you to install multiple versions of Node and switch between them at will. There are various advantages to using a version manager. For example, it negates potential permission issues which would otherwise see you installing packages with admin rights.
If you fancy going the version manager route, please consult our quick tip: Install Multiple Versions of Node.js Using nvm. Otherwise, grab the correct binaries for your system from the link above and install those.
npm
npm is a JavaScript package manager which comes bundled with Node, so no extra installation is necessary here. We’ll be making quite extensive use of npm throughout this tutorial, so if you’re in need of a refresher, please consult A Beginner’s Guide to npm — the Node Package Manager.
MongoDB
MongoDB is a document database which stores data in flexible, JSON-like documents. If you’ve never worked with Mongo before, you might like to check out our beginner-friendly introduction to MongoDB.
The quickest way to get up and running with Mongo is to use a service such as mLabs. They have a free sandbox plan which provides a single database with 0.5GB of storage running on a shared virtual machine. This is more than adequate for a simple app with a handful of users. If this sounds like the best option for you, please consult their quick-start guide.
You can also install Mongo locally. To do this, please visit the official download page and download the correct version of the community server for your operating system. There’s a link to detailed, OS-specific installation instructions beneath every download link, which you can consult if you run into trouble.
A MongoDB GUI
Although not strictly necessary for following along with this tutorial, you might also like to install Compass, the official GUI for MongoDB. This tool helps you visualize and manipulate your data, allowing you to interact with documents with full CRUD functionality.
Check that Everything is Installed Correctly
To check that Node and npm are installed correctly, open your terminal and type:
node -v
followed by:
npm -v
This will output the version number of each program (12.14.1
and 6.13.6
respectively at the time of writing).
If you installed Mongo locally, you can check the version number using:
mongo --version
This should output a bunch of information, including the version number (4.2.2
at the time of writing).
Check the Database Connection Using Compass
If you’ve installed Mongo locally, you start the server by typing the following command into a terminal:
mongod
Next, open Compass. You should be able to accept the defaults (server: localhost
, port: 27017), press the CONNECT button, and establish a connection to the database server.
MongoDB Compass connected to localhost
Note that the databases admin
, config
and local
are created automatically.
Using a Cloud-hosted Solution
If you’re using mLabs, create a database subscription (as described in their quick-start guide), then make a note of the connection details.
Open Compass, click New Connection, then Fill in connection fields individually. Select Username / Password as the authentication method, then fill out the rest of the details. Finally, click CONNECT and you should be off to the races.
Note: if you wish to use a connection string, it should look like this: mongodb://<dbuser>:<dbpassword>@ds211709.mlab.com:11709/?authSource=<dbname>
.
MongoDB Compass connected to mLabs
Note that I called my database sp-node-article
. You can call yours what you like.
Initialize the Application
With everything set up correctly, the first thing we need to do is initialize our new project. To do this, create a folder named demo-node-app
, enter that directory and type the following in a terminal:
npm init -y
This will create and auto-populate a package.json
file in the project root. We can use this file to specify our dependencies and to create various npm scripts, which will aid our development workflow.
Install Express
Express is a lightweight web application framework for Node.js, which provides us with a robust set of features for writing web apps. These features include such things as route handling, template engine integration and a middleware framework, which allows us to perform additional tasks on request and response objects. There’s nothing you can do in Express that you couldn’t do in plain Node.js, but using Express means we don’t have to re-invent the wheel and it reduces boilerplate.
So let’s install Express. To do this, run the following in your terminal:
npm install express
This will see Express added to the dependencies
section of the package.json
file. This signals to anyone else running our code that Express is a package our app needs to function properly.
Install nodemon
nodemon is a convenience tool. It will watch the files in the directory it was started in, and if it detects any changes, it will automatically restart your Node application (meaning you don’t have to). In contrast to Express, nodemon is not something the app requires to function properly (it just aids us with development), so install it using:
npm install --save-dev nodemon
This will add nodemon to the dev-dependencies
section of the package.json
file.
Create Some Initial Files
We’re almost through with the setup. All we need to do now is create a couple of initial files before kicking off the app.
In the demo-node-app
folder create an app.js
file and a start.js
file. Also create a routes
folder, with an index.js
file inside. After you’re done, things should look like this:
.
├── app.js
├── node_modules
│ └── ...
├── package.json
├── package-lock.json
├── routes
│ └── index.js
└── start.js
Now, let’s add some code to those files.
In app.js
:
const express = require('express');
const routes = require('./routes/index');
const app = express();
app.use('/', routes);
module.exports = app;
Here, we’re importing both the express
module and (the export value of) our routes file into the application. The require
function we’re using to do this is a built-in Node function which imports an object from another file or module. If you’d like a refresher on importing and exporting modules, read Understanding module.exports and exports in Node.js.
After that, we’re creating a new Express app using the express function and assigning it to an app
variable. We then tell the app that, whenever it receives a request from forward slash anything, it should use the routes file.
Finally, we export our app variable so that it can be imported and used in other files.
In start.js
:
const app = require('./app');
const server = app.listen(3000, () => {
console.log(`Express is running on port ${server.address().port}`);
});
Here we’re importing the Express app we created in app.js
. (Note that we can leave the .js
off the file name in the require
statement.) We then tell our app to listen on port 3000 for incoming connections and output a message to the terminal to indicate that the server is running.
And in routes/index.js
:
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('It works!');
});
module.exports = router;
Here, we’re importing Express into our routes file and then grabbing the router from it. We then use the router to respond to any requests to the root URL (in this case http://localhost:3000
) with an “It works!” message.
Kick off the App
Finally, let’s add an npm script to make nodemon start watching our app. Change the scripts
section of the package.json
file to look like this:
"scripts": {
"watch": "nodemon ./start.js"
},
The scripts
property of the package.json
file is extremely useful, as it lets you specify arbitrary scripts to run in different scenarios. This means that you don’t have to repeatedly type out long-winded commands with a difficult-to-remember syntax. If you’d like to find out more about what npm scripts can do, read Give Grunt the Boot! A Guide to Using npm as a Build Tool.
Now, type npm run watch
from the terminal and visit http://localhost:3000.
You should see “It works!”
The post Build a Simple Beginner App with Node, Bootstrap and MongoDB appeared first on SitePoint.
Many Private WhatsApp And Telegram Group Invite Links Are Appearing On Search Engines
A critical issue might have exposed your WhatsApp or Telegram group to the public. As discovered by a researcher, many
Many Private WhatsApp And Telegram Group Invite Links Are Appearing On Search Engines on Latest Hacking News.
Firefox enables DNS-over-HTTPS by default (with Cloudflare) for all U.S. users
How to Prepare for a Remote Job Search
The number of people working remotely is at an all-time high, and that’s not just because telecommuting is pants-optional. By giving employees more control over their schedule and work environment, remote jobs can enhance the work-life balance that so many people struggle to maintain.
But if you’ve held in-house positions for most of your career, properly preparing for your remote job search can up your chances of impressing remote employers, nailing the interview, and landing a remote job that best fits your needs.
What Are Remote Employers Looking For?
Remote employers are looking for three things in particular.
Independence
The office may at times feel like a panopticonic prison, but there is something to be said for workplace accountability. Can you stay focused without a boss periodically checking in on you? Can you stay productive without the sight and sound of other co-workers clacking away on their computers? When you work from home, the Damocles of the deadline is blunted and the motivating effect of being in close proximity to your team members weakens.
Remote employers understand these challenges, which is why they look for candidates who can motivate themselves without external prompting. As trite as buzzwords like self-starter and proactive can be, they carry a significant amount of weight in the remote job search. Not only do you need to possess these qualities, you’ll need to be able demonstrate them to potential employers.
Communication
Working in an office allows employees to be more passive. Don’t know what’s going on? A co-worker can fill you in via a few seconds of conversation. Your boss is only a few steps away. Maybe there’s a whiteboard in the break room with announcements. Sharing a space with people just makes it much easier to stay in the loop.
But if you’re on your own, you need to take initiative. To compensate for the lack of face-to-face, a good remote worker will put effort into the virtual communication tools at their disposal. They’ll reach out to people through email or Slack. They’ll suggest video chats or calls to hash things out. Even swapping memes in a group chat can help you stay engaged. But if you give in to the temptation of solitude, communication could suffer, and so could your work.
Rational Thinking
When communicating primarily through text, it’s all too common for our imaginations to run wild with unfounded anxieties. Emailed your boss a question and they didn’t respond within whatever time frame you’ve arbitrarily decided was reasonable? They must think it’s a dumb question and you’re dumb for asking it. They must not deem you important enough to expediently respond to. They must be offended by something you wrote. Asked a co-worker to do something and they responded with “k”? They hate you. They’re telling everyone how much they hate you. Everyone hates you. You’re garbage!
Or … absolutely none of that is true and the coldness of non-verbal communication is messing with your head. Like any good employer, remote employers don’t want drama. They want rational critical thinkers who can vault the pitfalls of remote communication and maintain healthy work relationships. K?
How Do You Demonstrate These Skills On Your Resume?
Even if you have little to no remote work experience, there are ways to frame your in-house work experience so that it demonstrates remote work skills. What have you done that demonstrates independence? Communication? Rational thinking? Figure it out and integrate it into your resume.
For example, if you took the initiative on anything in a previous position, emphasize it. Say you independently devised and implemented project x or volunteered to plan, create, and maintain project y. Explain that you created and ran program z with little oversight.
Here are some other ideas to get you thinking:
The post How to Prepare for a Remote Job Search appeared first on SitePoint.
Slickwraps Website Breached After Disgruntled Researcher Publicly Exposed Findings
A researcher with the alias Lynx0x00 discovered security flaws in Slickwraps systems after which they sent emails to customers using
Slickwraps Website Breached After Disgruntled Researcher Publicly Exposed Findings on Latest Hacking News.
Free Download: The Ultimate Security Pros' Checklist
Install Latest Chrome Update to Patch 0-Day Bug Under Active Attacks
New OpenSMTPD RCE Flaw Affects Linux and OpenBSD Email Servers
Why Minimizing Human Error is the Only Viable Defense Against Spear Phishing
VMware Patch Numerous Bugs In vRealize Operations for Their Horizon Adapter
VMware has disclosed multiple security bugs in its software product vRealize Operations for Horizon Adapter. VMware have released fixes for
VMware Patch Numerous Bugs In vRealize Operations for Their Horizon Adapter on Latest Hacking News.
Monday, 24 February 2020
Department of Defense’s DISA Confessed Data Breach
The United States Department of Defense (DOD) holds significant importance owing to its sensitive operations. Perhaps, that is why it
Department of Defense’s DISA Confessed Data Breach on Latest Hacking News.
Cisco Patch Static Password Vulnerability In Smart Software Manager
Cisco have recently disclosed a security flaw in one of their products that could have serious consequences. As revealed, a
Cisco Patch Static Password Vulnerability In Smart Software Manager on Latest Hacking News.
Top Cybersecurity Trends In 2020
In the digital age, where many of our tasks and chores have been taken care of by machines or by
Top Cybersecurity Trends In 2020 on Latest Hacking News.
Adobe Patch Two Critical Code Execution Bugs A Week After Patch Tuesday
Last week, Adobe released its monthly Patch Tuesday updates addressing different bugs. But it seems their work wasn’t over as
Adobe Patch Two Critical Code Execution Bugs A Week After Patch Tuesday on Latest Hacking News.
Is your phone listening to you?
Do social media listen in on our conversations in order to target us with ads? Or are we just a bit paranoid? A little test might speak a thousand words.
The post Is your phone listening to you? appeared first on WeLiveSecurity
Actively Exploited Duplicator WordPress Plugin Exploit Risks 1 Million Websites
Joining the trail of vulnerable WordPress plugins, here comes another plugin that threatens the security of over 1 million websites.
Actively Exploited Duplicator WordPress Plugin Exploit Risks 1 Million Websites on Latest Hacking News.
Sunday, 23 February 2020
An Introduction to MongoDB
MongoDB is a cross-platform, open-source, NoSQL database, used by many modern Node-based web applications to persist data.
In this beginner-friendly tutorial, I’ll demonstrate how to install Mongo, then start using it to store and query data. I’ll also look at how to interact with a Mongo database from within a Node program, and also highlight some of the differences between Mongo and a traditional relational database (such as MySQL) along the way.
Terminology and Basic Concepts
MongoDB is a document-oriented database. This means that it doesn’t use tables and rows to store its data, but instead collections of JSON-like documents. These documents support embedded fields, so related data can be stored within them.
MongoDB is also a schema-less database, so we don’t need to specify the number or type of columns before inserting our data.
Here’s an example of what a MongoDB document might look like:
{
_id: ObjectId(3da252d3902a),
type: "Tutorial",
title: "An Introduction to MongoDB",
author: "Manjunath M",
tags: [ "mongodb", "compass", "crud" ],
categories: [
{
name: "javascript",
description: "Tutorialss on client-side and server-side JavaScript programming"
},
{
name: "databases",
description: "Tutorialss on different kinds of databases and their management"
},
],
content: "MongoDB is a cross-platform, open-source, NoSQL database..."
}
As you can see, the document has a number of fields (type
, title
etc.), which store values (“Tutorial”, “An Introduction to MongoDB” etc.). These values can contain strings, numbers, arrays, arrays of sub-documents (for example, the categories
field), geo-coordinates and more.
The _id
field name is reserved for use as a primary key. Its value must be unique in the collection, it’s immutable, and it may be of any type other than an array.
Tip: for those wondering what “JSON-like” means, internally Mongo uses something called BSON (short for Binary JSON). In practice, you don’t really need to know much about BSON when working with MongoDB.
As you might guess, a document in a NoSQL database corresponds to a row in an SQL database. A group of documents together is known as a collection, which is roughly synonymous with a table in a relational database.
Here’s a table summarizing the different terms:
SQL Server | MongoDB |
---|---|
Database | Database |
Table | Collection |
Row | Document |
Column | Field |
Index | Index |
If you’re starting a new project and are unsure whether to choose Mongo or a relational database such as MySQL, now might be a good time to read our tutorial SQL vs NoSQL: How to Choose.
With that said, let’s go ahead and install MongoDB.
Installing MongoDB
Note: if you’d just like to follow along with this tutorial without installing any software on your PC, there are a couple of online services you can use. Mongo playground, for example, is a simple sandbox to test and share MongoDB queries online.
MongoDB comes in various editions. The one we’re interested in is the MongoDB Community Edition.
The project’s home page has excellent documentation on installing Mongo, and I won’t try to replicate that here. Rather, I’ll offer you links to instructions for each of the main operating systems:
- Install MongoDB Community Edition on Windows
- Install MongoDB Community Edition on macOS
- Install MongoDB Community Edition on Ubuntu
If you use a non-Ubuntu-based version of Linux, you can check out this page for installation instructions for other distros. MongoDB is also normally available through the official Linux software channels, but sometimes this will pull in an outdated version.
Post Installation Configuration
Once you have MongoDB installed for your system, you might encounter this error:
dbpath (/data/db) does not exist.
Create this directory or give existing directory in --dbpath.
See http://dochub.mongodb.org/core/startingandstoppingmongo
This means that Mongo can’t find (or access) the directory it uses to store its databases. This is pretty easy to remedy:
sudo mkdir -p /data/db
sudo chown -R `id -un` /data/db
The first command creates the data/db
directory. The second sets permissions so that Mongo can write to that directory.
Install the Compass GUI
We’ll be using the command line in this tutorial, but MongoDB also offers a tool called Compass to connect to and manage your databases using a GUI.
If you’re on Windows, Compass can be installed as part of the main Mongo installation (just select the appropriate option from the wizard). Otherwise, you can download Compass for your respective OS here.
This is what it looks like:
The Mongo Shell
We can test our installation by opening the Mongo shell. You can do this by opening a terminal window and typing mongo
.
Note: this assumes that <mongodb installation dir>/bin
is in your path. If for any reason this isn’t the case, change into the <mongodb installation dir>/bin
directory and rerun the command.
If you get an Error: couldn't connect to server
error, you’ll need to start the Mongo server (in a second terminal window) with the command mongod
.
Once you’re in the Mongo shell, type in db.version()
to see the version of MongoDB you’re running. At the time of writing, this should output 4.2.2
.
Please note that you can exit the Mongo shell by running quit()
and the Mongo daemon by pressing Ctrl + C at any time.
Now let’s get acquainted with some MongoDB basics.
Basic Database Operations
Enter the Mongo shell if you haven’t already (by typing mongo
into a terminal):
[mj@localhost ~]$ mongo
MongoDB shell version v4.2.2
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("08a624a0-b330-4233-b56b-1d5b15a48fea") }
MongoDB server version: 4.2.2
Let’s start off by creating a database to work with. To create a database, MongoDB has a use DATABASE_NAME
command:
> use exampledb
switched to db exampledb
To display all the existing databases, try show dbs
:
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
The exampledb
isn’t in the list because we need to insert at least one document into the database. To insert a document, you can use db.COLLECTION_NAME.insertOne({"key":"value"})
. Here’s an example:
> db.users.insertOne({name: "Bob"})
{
"acknowledged" : true,
"insertedId" : ObjectId("5a52c53b223039ee9c2daaec")
}
MongoDB automatically creates a new users
collection and inserts a document with the key–value pair 'name':'Bob'
. The ObjectId returned is the ID of the document inserted. MongoDB creates a unique ObjectId for each document on creation, and it becomes the default value of the _id
field.
Now we should be able to see our database:
>show dbs
admin 0.000GB
config 0.000GB
exampledb 0.000GB
local 0.000GB
Similarly, you can confirm that the collection was created using the show collections
command:
> show collections
users
We’ve created a database, added a collection named users
and inserted a document into it. Now let’s try dropping it. To drop an existing database, use the dropDatabase()
command, as exemplified below:
>db.dropDatabase()
{ "dropped" : "exampledb", "ok" : 1 }
show dbs
confirms that the database was indeed dropped:
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
For more database operations, please consult the MongoDB reference page on database commands.
The post An Introduction to MongoDB appeared first on SitePoint.
Why Are There So Few Women in Computer Science?
It is widely accepted that women play a key role in our lives. Women are mothers and the modern female entrepreneur is ubiquitous, however women have made vast contributions to the IT field and yet are still underrepresented.
Women developed some of the most significant elements making IT into what it is today. The contribution of women to modern IT is outsized and begs the question as to why there are not many women in the IT workplace.
According to the Guardian, top organizations like Google and Uber have only women engineers composing 20% of their IT workforce. Unfortunately, most of the big organizations match that figure.
This brings us to the most critical question, why are there few famous women in computer science?
Let’s analyze a few of those reasons.
Fewer Number of Women Prefer CS
It appears there is a massive difference between female and male cognitive aptitudes in America and other parts of the world. This is slowly changing in Asian countries like China and India, where both men and women are in a CS classroom.
Few women pursue careers in CS. Instead, they wish to study in fields like medicine in the West. This could be due to the “male geek” concept. Computers were sold as toys for mainly boys during the 1970s to 1990s.
It is possible that women are put off by the term “computer science.” It is probably a cultural stigma sticking in the West. The best solution would be to get rid of the stigma as soon as possible.
Fewer Opportunities for Higher Responsibilities
The IT field is extremely punishing for employees. There are many instances where women usually are not preferred for higher positions. Many women could feel unwanted and discouraged due to a lack of senior responsibilities.
Large organizations and small businesses equally fail to acknowledge the benefits of women in management. Many skilled and talented women have no choice but to look elsewhere.
Lack of Funding
According to The Guardian, a woman entrepreneur has an 80% chance of not being funded, something that impacts motivation in the field. Men have the opposite experience.
However, ROI is greater than 60% when women lead the company. The issue does not seem to be about corporate social responsibility but a diverse range of thinking.
Sexual Harassment
Unfortunately, sexual harassment is the principle cause for women leaving IT jobs. In many cases, women are happy with the work environment, salary, and position. But in the face of harassment in the form of physical abuse and mental torture from superiors, women have no choice.
Their complaints often fall on deaf ears. Women will likely search for another career. According to The Guardian, the IT field leads in the number of sexual harassment cases.
Here is a List of Women Pioneers in IT
- Ada Lovelace created and designed the first computer program.
- Grace Hopper invented devices and computing methods including compilers.
- Margaret Hamilton helped the development of programs in which today’s PCs work.
- Stephanie Shirley developed programs studying the impact of technology on social issues.
- Megan Smith promoted diversity throughout the IT firms.
Women Pioneers in the IT Space
Below is a list of famous women in computer science who’ve made an impact on the IT field.
Sheryl Sandberg
Sheryl Sandberg has carved out a name for herself. She is the COO of Facebook. Sandberg previously worked at the World Bank after completing her economics degree at Harvard.
Her book, Lean In: Women, Work, and the Will to Lead, is a top seller having sold several million copies around the world. Apart from being the COO of a company, she is the author of a top-seller and is active as a speaker and entrepreneur.
Ada Lovelace
Ada Lovelace was born in London during the 19th century. She had an affinity for math during her school days. This passion for the subject enabled her to develop the first computer program.
Ada also designed a method through which analytical engines perform successful computations with the help of the machine designed and invented by her friend, Charles Babbage.
Every year, on 2nd Tuesday, in the month of October, the Ada Lovelace Day is celebrated globally for recognizing talented and skilled women in the field of STEM.
Grace Hopper
Grace Hopper was born in America during the 1900s. She worked in the Navy, after which her scientific knowledge enabled her to develop the Harvard Mark I computer. Grace was the first woman to have invented the compiler.
Every year, women scientists from all over the world celebrate her hard work and dedication with the Grace Hopper Celebration.
Katherine Johnson
Katherine Johnson was born in West Virginia and developed and refined the use of computers for NASA. A 2014 movie, “Hidden Figures,” was based on her experiences.
Katherine performed accurate calculations for space travel during the 1940s. Johnson co-authored a research report based on spaceflight equations used on the desktop mechanical calculating machine.
She has worked on critical projects, including Apollo’s Lunar Lander, the Earth Resources Satellite, and the Space Shuttle.
Megan Smith
Megan Smith served in the White House until 2017. Smith initially worked at Google before doing federal work. It was under her watchful eye that the tech hackathon was developed for health workers.
She is currently working with Tech Job Toursand conducting job fairs throughout the country to hire talent through coding boot-camps, career fairs, and mentoring sessions.
Future of Women in IT
Unsurprisingly, women find themselves in dominant roles in the IT field. They are developing new programs, coming up with new technologies, and offering society tools allowing them to lead more comfortable lives.
You can find women in management roles in technology companies making significant decisions. Women developing advanced IT systems, designing 3D animation for box office hit movies, and enabled laptop computer developments that are suitable for work from home environments.
Karen Spärck Jones, a famous computer scientist and woman campaigner once said, “Computing is a too important field that must not be left in the hands of men.”
The post Why Are There So Few Women in Computer Science? appeared first on The Crazy Programmer.
New Email Extortion Scam Threatens Banning of Google AdSense Accounts
Heads up all Google AdSense users. A new email extortion scam is in the wild that threatens website owners serving
New Email Extortion Scam Threatens Banning of Google AdSense Accounts on Latest Hacking News.
NextMotion Leaked Sensitive Plastic Surgery Images Online Via an Unsecured Database
Researchers from vpnMentor have discovered another unsecured database exposing sensitive details about users. As reported, they discovered an unprotected Amazon
NextMotion Leaked Sensitive Plastic Surgery Images Online Via an Unsecured Database on Latest Hacking News.
Friday, 21 February 2020
US Department of Homeland Warns Of Ransomware Attacks After Pipeline Operations Affected
US Department of Homeland has issued an alert regarding the threat of ransomware attacks. DHS warns about it after a
US Department of Homeland Warns Of Ransomware Attacks After Pipeline Operations Affected on Latest Hacking News.
Zero-Day Bug In ThemeREX WordPress Plugin Exploited In The Wild
Researchers have discovered a zero-day vulnerability in WordPress plugin ThemeREX. Exploiting the flaw allows an unauthenticated adversary to execute codes
Zero-Day Bug In ThemeREX WordPress Plugin Exploited In The Wild on Latest Hacking News.
PhotoSquared App Leaked Personal Data And Sensitive Photos Online
Once again, a popular photo-editing application has breached users’ privacy, consequently exposing sensitive information online. This time, the guilty application
PhotoSquared App Leaked Personal Data And Sensitive Photos Online on Latest Hacking News.
Week in security with Tony Anscombe
Hunting down Linux threats – The implications of DNS encryption for business security – MGM Resorts breach hits millions of people
The post Week in security with Tony Anscombe appeared first on WeLiveSecurity
Windows & Linux Devices at Risk From Unsigned Peripheral Firmware
Reportedly, researchers from Eclypsium have discovered how a problem in peripheral devices can risk the security of entire systems. Specifically,
Windows & Linux Devices at Risk From Unsigned Peripheral Firmware on Latest Hacking News.
Up close and personal with Linux malware
What are the main security threats facing Linux? A Q&A with ESET Senior Malware Researcher Marc‑Etienne M.Léveillé, whose work has been instrumental in uncovering a number of malware strains hitting Linux servers.
The post Up close and personal with Linux malware appeared first on WeLiveSecurity
Thursday, 20 February 2020
How to Properly Organize Files in Your Codebase & Avoid Mayhem
The main library, data, UI, docs and wiki, tests, legacy and third-party components … How do we keep track and maintain order within all of this? Organizing the files in your codebase can become a daunting task.
Relax — we've got this! In this article, we’ll review the most common systems for both small and large projects, with some easy-to-follow best practices.
Why Bother?
As with pretty much all of the tasks related to project management — documentation, software commits, deployment — you’ll benefit from taking a conscious, programmatic approach. Not only it will reduce problems now, but it will also save you and your team quality time in the future when you need to quickly access and review things.
You surely can recall function names from the top of your head for whatever is it that you're coding right now, and quickly find a file you need to edit, and sharply tell what works from what doesn't — or so you think. But could you say the same about that project you were working on last year?
Let's admit it: software projects can go on spans of inactivity that last for months, and even years. A simple README file could do a lot for your colleagues or your future self. But let's think about the other ways you could structure your project, and establish some basic rules to name files, address project documentation, and to some degree organize an effective workflow that would stand the test of time.
Making Sense of Things
We’ll establish a "baseline" for organizing files in a project — a logic that will serve us for a number of situations within the scope of software development.
As with our rules for committing changes to your codebase the right way, none of this is carved in stone, and for what it's worth, you and your team might come up with different guidelines. In any case, consistency is the name of the game. Be sure you understand (and discuss or dispute) what the rules are, and follow them once you've reached a consensus.
The Mandatory Set
This is a reference list of files that nearly every software project should have:
- README: this is what GitHub renders for you right under the sourcetree, and it can go a long way to explaining what the project is about, how files are organized, and where to find further information.
- CHANGELOG: to list what's new, modified or discontinued on every version or revision — normally in a reverse chronological order for convenience (last changes first).
- COPYING LICENSE: a file containing the full text of the license covering the software, including some additional copyright information, if necessary (such as third-party licenses).
- .gitignore: assuming you use Git (you most probably do), this will also be a must to tell what files not to sync with the repository. (See Jump Start Git's primer on .gitignore and the documentation for more info, and have a look at a collection of useful .gitignore templates for some ideas.)
Supporting Actors
The post How to Properly Organize Files in Your Codebase & Avoid Mayhem appeared first on SitePoint.
MGM Resorts data breach exposes details of 10.6 million guests
A number of celebrities, government officials and tech CEOs were also caught up in the incident
The post MGM Resorts data breach exposes details of 10.6 million guests appeared first on WeLiveSecurity
Ring Makes Two-Factor Authentication Mandatory For All Customers
After back-to-back security incidents, Ring – the smart device vendors, have now upped their game to ensure users’ security. Recently,
Ring Makes Two-Factor Authentication Mandatory For All Customers on Latest Hacking News.
How Clever and Secure is Your Home?
Your home is your fortress. It may be a large fortress, it may be a small fortress. They come in
How Clever and Secure is Your Home? on Latest Hacking News.
Scam Alert: You've Been Selected for 'Like of the Year 2020' Cash Prizes
Deal: Cloud And Networking Certification Training ~ Get 97% OFF
Linux and malware: Should you worry?
Malicious code is nothing to worry about on Linux, right? Hold your penguins. How Linux malware has gone from the sidelines to the headlines.
The post Linux and malware: Should you worry? appeared first on WeLiveSecurity
Adobe Patches Critical Bugs Affecting Media Encoder and After Effects
Vulnerability In WordPress Plugin ThemeGrill Demo Importer Allowed Wiping of a Victim Website
A WordPress plugin threatened the integrity of thousands of websites. This time, the vulnerability appeared in the ThemeGrill Demo Importer
Vulnerability In WordPress Plugin ThemeGrill Demo Importer Allowed Wiping of a Victim Website on Latest Hacking News.
Wednesday, 19 February 2020
Productive Remote Work (When Your Mental Health Says “No”)
Remote work is not easy. It sounds like a dream (and it honestly is in a lot of ways), but there’s a darker side to remote work that one can’t understand until they’ve done it.
Here’s the deal. People that work remotely often suffer from suboptimal mental health, and so you’re probably wondering, why on earth do they do it? Well, the fact is, while remote working comes with some very unique challenges, so does not working remotely. The difference is that remote work can offer the flexibility you need to build a lifestyle that suits you.
Indeed, remote work isn’t a silver bullet for burnout or wanderlust, but if you do happen to try it out and eventually wind up succumbing to loneliness, or a lack of motivation or productivity (as many remote workers do), at least you’ll have the opportunity to change things up and make things better.
In the eyes of many, it’s the lesser of two evils.
That being said, attempting to diagnose what your mind and body needs isn’t that easy. What might work one day might not work on another day, and what might work for one individual might not work for another individual. Humans are complex, and in the case of remote work, everyday productivity tricks often don’t cut it.
Let’s take a look.
“I feel lonely”
Loneliness is a big issue (maybe the biggest?) for freelance remote workers and digital nomads in foreign countries, but it can also affect those that work in distributed teams (especially when some team members aren’t remote, as one can feel like an outsider at work using this setup). Let’s look at the solutions.
Utilize co-working spaces
Co-working spaces aren’t for everyone. If you teach English, it’s obviously a no-no (not because of the noise, but because the noise would be distracting to other remote workers). If you’re only required to dive into the odd video call, though, many co-working spaces include a few hours of “booth time”.
Throw in super-fast Wi-Fi, free coffee, daily events, and a likeminded crowd, joining a co-working space is like joining a community, and some co-working spaces (such as Hubud) and Dojo Bali) are literally famous! Good vibes = a huge motivation boost.
Work from bars and cafés
Cafés and bars work well too. The noise and seating options might be a tad unpredictable, and when going to a new place one has to find the Wi-Fi password, but all in all the experience is very much the same. It’s still fairly easy to meet other people, as it’s likely that you won’t be the only regular customer.
Pro-tip: download Wi-Fi Map app to get the Wi-Fi passwords of networks near you!
The post Productive Remote Work (When Your Mental Health Says “No”) appeared first on SitePoint.
Ring Makes 2-Factor Authentication Mandatory Following Recent Hacks
US Govt Warns Critical Industries After Ransomware Hits Gas Pipeline Facility
What DNS encryption means for enterprise threat hunters
The dawn of the DNS over HTTPS era is putting business security and SOC teams to the challenge
The post What DNS encryption means for enterprise threat hunters appeared first on WeLiveSecurity
World Health Organization Warns About Coronavirus Phishing Attacks
Once again, cybercriminals have proved their indifference to morality by exploiting the panic and hype for the horrifying Coronavirus epidemic
World Health Organization Warns About Coronavirus Phishing Attacks on Latest Hacking News.
Tuesday, 18 February 2020
Forms, File Uploads and Security with Node.js and Express
If you’re building a web application, you’re likely to encounter the need to build HTML forms on day one. They’re a big part of the web experience, and they can be complicated.
Typically the form-handling process involves:
- displaying an empty HTML form in response to an initial
GET
request - user submitting the form with data in a
POST
request - validation on both the client and the server
- re-displaying the form populated with escaped data and error messages if invalid
- doing something with the sanitized data on the server if it’s all valid
- redirecting the user or showing a success message after data is processed.
Handling form data also comes with extra security considerations.
We’ll go through all of these and explain how to build them with Node.js and Express — the most popular web framework for Node. First, we’ll build a simple contact form where people can send a message and email address securely and then take a look what’s involved in processing file uploads.
As ever, the complete code can be found in our GitHub repo.
Setup
Make sure you’ve got a recent version of Node.js installed. node -v
should return 8.9.0
or higher.
Download the starter code from here with Git:
git clone -b starter https://github.com/sitepoint-editors/node-forms.git node-forms-starter
cd node-forms-starter
npm install
npm start
Note: The repo has two branches, starter
and master
. The starter
branch contains the minimum setup you need to follow this article. The master
branch contains a full, working demo (link above).
There’s not too much code in there. It’s just a bare-bones Express setup with EJS templates and error handlers:
// server.js
const path = require('path');
const express = require('express');
const layout = require('express-layout');
const routes = require('./routes');
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
const middlewares = [
layout(),
express.static(path.join(__dirname, 'public')),
];
app.use(middlewares);
app.use('/', routes);
app.use((req, res, next) => {
res.status(404).send("Sorry can't find that!");
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(3000, () => {
console.log('App running at http://localhost:3000');
});
The root url /
simply renders the index.ejs
view:
// routes.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.render('index');
});
module.exports = router;
Displaying the Form
When people make a GET request to /contact
, we want to render a new view contact.ejs
:
// routes.js
router.get('/contact', (req, res) => {
res.render('contact');
});
The contact form will let them send us a message and their email address:
<!-- views/contact.ejs -->
<div class="form-header">
<h2>Send us a message</h2>
</div>
<form method="post" action="/contact" novalidate>
<div class="form-field">
<label for="message">Message</label>
<textarea class="input" id="message" name="message" rows="4" autofocus></textarea>
</div>
<div class="form-field">
<label for="email">Email</label>
<input class="input" id="email" name="email" type="email" value="" />
</div>
<div class="form-actions">
<button class="btn" type="submit">Send</button>
</div>
</form>
See what it looks like at http://localhost:3000/contact
.
Form Submission
To receive POST values in Express, you first need to include the body-parser
middleware, which exposes submitted form values on req.body
in your route handlers. Add it to the end of the middlewares
array:
// server.js
const bodyParser = require('body-parser');
const middlewares = [
// ...
bodyParser.urlencoded({ extended: true }),
];
It’s a common convention for forms to POST data back to the same URL as was used in the initial GET request. Let’s do that here and handle POST /contact
to process the user input.
Let’s look at the invalid submission first. If invalid, we need to pass back the submitted values to the view (so users don’t need to re-enter them) along with any error messages we want to display:
router.get('/contact', (req, res) => {
res.render('contact', {
data: {},
errors: {}
});
});
router.post('/contact', (req, res) => {
res.render('contact', {
data: req.body, // { message, email }
errors: {
message: {
msg: 'A message is required'
},
email: {
msg: 'That email doesn‘t look right'
}
}
});
});
If there are any validation errors, we’ll do the following:
- display the errors at the top of the form
- set the input values to what was submitted to the server
- display inline errors below the inputs
- add a
form-field-invalid
class to the fields with errors.
<!-- views/contact.ejs -->
<div class="form-header">
<% if (Object.keys(errors).length === 0) { %>
<h2>Send us a message</h2>
<% } else { %>
<h2 class="errors-heading">Oops, please correct the following:</h2>
<ul class="errors-list">
<% Object.values(errors).forEach(error => { %>
<li><%= error.msg %></li>
<% }) %>
</ul>
<% } %>
</div>
<form method="post" action="/contact" novalidate>
<div class="form-field <%= errors.message ? 'form-field-invalid' : '' %>">
<label for="message">Message</label>
<textarea class="input" id="message" name="message" rows="4" autofocus><%= data.message %></textarea>
<% if (errors.message) { %>
<div class="error"><%= errors.message.msg %></div>
<% } %>
</div>
<div class="form-field <%= errors.email ? 'form-field-invalid' : '' %>">
<label for="email">Email</label>
<input class="input" id="email" name="email" type="email" value="<%= data.email %>" />
<% if (errors.email) { %>
<div class="error"><%= errors.email.msg %></div>
<% } %>
</div>
<div class="form-actions">
<button class="btn" type="submit">Send</button>
</div>
</form>
Submit the form at http://localhost:3000/contact
to see this in action. That’s everything we need on the view side.
Validation and Sanitization
There’s a handy middleware called express-validator for validating and sanitizing data using the validator.js library. Let’s add it to our app.
Validation
With the validators provided, we can easily check that a message and a valid email address was provided:
// routes.js
const { check, validationResult, matchedData } = require('express-validator');
router.post('/contact', [
check('message')
.isLength({ min: 1 })
.withMessage('Message is required'),
check('email')
.isEmail()
.withMessage('That email doesn‘t look right')
], (req, res) => {
const errors = validationResult(req);
res.render('contact', {
data: req.body,
errors: errors.mapped()
});
});
Sanitization
With the sanitizers provided, we can trim whitespace from the start and end of the values, and normalize the email address into a consistent pattern. This can help remove duplicate contacts being created by slightly different inputs. For example, ' Mark@gmail.com'
and 'mark@gmail.com '
would both be sanitized into 'mark@gmail.com'
.
Sanitizers can simply be chained onto the end of the validators:
// routes.js
router.post('/contact', [
check('message')
.isLength({ min: 1 })
.withMessage('Message is required')
.trim(),
check('email')
.isEmail()
.withMessage('That email doesn‘t look right')
.bail()
.trim()
.normalizeEmail()
], (req, res) => {
const errors = validationResult(req);
res.render('contact', {
data: req.body,
errors: errors.mapped()
});
const data = matchedData(req);
console.log('Sanitized:', data);
});
The matchedData
function returns the output of the sanitizers on our input.
Also, notice our use of the bail method, which stops running validations if any of the previous ones have failed. We need this because if a user submits the form without entering a value into the email field, the normalizeEmail
will attempt to normalize an empty string and convert it to an @
. This will then be inserted into our email field when we re-render the form.
The post Forms, File Uploads and Security with Node.js and Express appeared first on SitePoint.