Inicio de sesión con Node.js Express y MySQL

Login with Node.js Express and MySQL

With this tutorial you will simply learn how to implement a login with Node.js, Express and MySQL on your local server, with which you will be able to authenticate the access of your end users from the registry in the database.

It should be added that this application is totally basic, it only shows a landing page where you can enter a username and password; and according to the corresponding validations, it is confirmed if the user can enter a new page, a home or not.

If the user marks the URL with the home without validating his username and password, an invalid username or password message will appear, but in case he has entered the credentials correctly, related to the persistent information in the database, then, You will be redirected to home, with a welcome message.

Node.js is a powerful manager for server functions that based on javascript, is very popular today, node.js is said to be the development of the future and for this reason it is very important to learn from this technology.

Fine-tuning the login system with Node.js Express and MySQL

The first thing is to install NPM, to be able to access the technology, install the necessary libraries and activate the server to run the application.

Download and Install node.js

I will not address the download and installation process in this tutorial, although it should be added that it is very simple, just access the URL below and carry out all the default processes that apply to the installation on your computer, then the following is the nodejs download link:

https://nodejs.org/en/download/

Download and Install Visual Studio Code

After downloading and installing nodejs, I recommend installing Visual Studio Code, which is the most popular code editor in the world. You can download this application at the link below:

https://code.visualstudio.com/download

Download and Install XAMPP

It is necessary to install XAMPP through the database server, we will execute it from XAMPP, with phpMyAdmin and MariaDB.

I will not address the download and installation process either because it is very simple, it is a matter of accessing the following link and clicking next, following all the options that the XAMPP installer offers you, the following is the XAMPP download link:

https://www.apachefriends.org/es/download.html

Installation of Express and MySQL

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

To download and install Express in the login project with Node.js Express and MySQL we are going to use the console from Visual Studio Code.

From VS Code, we click on File, Open Folder and we go where we are going to locate the project, in my case the folder I chose was login-nodejs.

Already located at this point, click on View, Terminal and at the bottom of VS Code a black screen will appear, where we can execute commands already located from terminal in the project folder.

Now from terminal copy and paste the following command:

npm install express --save

Then we install Express Session with the following command line:

npm install express-session --save

Finally, I install a MySQL library for Nodejs with the following script:

npm install mysql --save

At this point, from the console, I can formally start an npm project, with the following script:

npm init

The console is going to ask me certain questions, in the name of the package name, I put login then I hit enter until it asks me for the entry point, in this instance I write login.js

CSS design for the login system form in nodejs

I shall create a folder called static inside the project and in this folder create a document called style.css.

The following is the code with which the styles of the application were adjusted:

* {
    box-sizing: border-box;
    font-family: -apple-system, BlinkMacSystemFont, "segoe ui", roboto, oxygen, ubuntu, cantarell, "fira sans", "droid sans", "helvetica neue", Arial, sans-serif;
    font-size: 16px;
}
body {
    background-color: #fc7d1c;
}
.login {
    width: 400px;
    background-color: #ffffff;
    box-shadow: 0 0 9px 0 rgba(0, 0, 0, 0.3);
    margin: 100px auto;
}
.login h1 {
    text-align: center;
    color: #5b6574;
    font-size: 24px;
    padding: 20px 0 20px 0;
    border-bottom: 1px solid #dee0e4;
}

.login a {
    text-align: center;
    color: #5b6574;
    font-size: 24px;
    padding: 20px 0 20px 0;
    border-bottom: 1px solid #dee0e4;
}
.login form {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    padding-top: 20px;
}
.login form label {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 50px;
    height: 50px;
    background-color: #1984bc;
    color: #ffffff;
}
.login form input[type="password"], .login form input[type="text"] {
    width: 310px;
    height: 50px;
    border: 1px solid #dee0e4;
    margin-bottom: 20px;
    padding: 0 15px;
}
.login form input[type="submit"] {
    width: 100%;
    padding: 15px;
   margin-top: 20px;
    background-color: #1984bc;
    border: 0;
    cursor: pointer;
    font-weight: bold;
    color: #ffffff;
    transition: background-color 0.2s;
}
.login form input[type="submit"]:hover {
  background-color: #1984bc;
    transition: background-color 0.2s;
}

HTML Login Form

Creation of the login.html file where the form will be where the end user will enter their access credentials. This file is created on the root folder of the project, the following is the code that the Form carries:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,minimum-scale=1">
		<title>ConfiguroWeb</title>
        <!-- the form awesome library is used to add icons to our form -->
		<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
        <!-- include the stylesheet file -->
        <link href="/style.css" rel="stylesheet" type="text/css">
	</head>
	<body>
		<div class="login">
			<h1>Login  | <a  href="https://www.configuroweb.com/en/">ConfiguroWeb</a></h1>
			<form action="/en/auth/" method="post" data-trp-original-action="/auth">
				<label for="username">
					<!-- font awesome icon -->
					<i class="fas fa-user"></i>
				</label>
				<input type="text" name="username" placeholder="Usuario" id="username" required>
				<label for="password">
					<i class="fas fa-lock"></i>
				</label>
				<input type="password" name="password" placeholder="Contraseña" id="password" required>
				<input type="submit" value="Ingresar">
			<input type="hidden" name="trp-form-language" value="en"/></form>
		</div>
	</body>
</html>

Creating Login logic with Node.js Express and MySQL in the login.js file

const mysql = require('mysql');
const express = require('express');
const session = require('express-session');
const path = require('path');

const connection = mysql.createConnection({
	host     : 'localhost',
	user     : 'root',
	password : '',
	database : 'login-socket'
});

const app = express();

app.use(session({
	secret: 'secret',
	resave: true,
	saveUninitialized: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'static')));

// http://localhost:3000/
app.get('/', function(request, response) {
	// Render login template
	response.sendFile(path.join(__dirname + '/login.html'));
});

// http://localhost:3000/auth
app.post('/auth', function(request, response) {
	// Capture the input fields
	let username = request.body.username;
	let password = request.body.password;
	// Ensure the input fields exists and are not empty
	if (username && password) {
		// Execute SQL query that'll select the account from the database based on the specified username and password
		connection.query('SELECT * FROM accounts WHERE username = ? AND password = ?', [username, password], function(error, results, fields) {
			// If there is an issue with the query, output the error
			if (error) throw error;
			// If the account exists
			if (results.length > 0) {
				// Authenticate the user
				request.session.loggedin = true;
				request.session.username = username;
				// Redirect to home page
				response.redirect('/home');
			} else {
				response.send('Usuario y/o Contraseña Incorrecta');
			}			
			response.end();
		});
	} else {
		response.send('Por favor ingresa Usuario y Contraseña!');
		response.end();
	}
});

// http://localhost:3000/home
app.get('/home', function(request, response) {
	// If the user is loggedin
	if (request.session.loggedin) {
		// Output username
		response.send('Te has logueado satisfactoriamente:, ' + request.session.username + '!');
	} else {
		// Not logged in
		response.send('¡Inicia sesión para ver esta página!');
	}
	response.end();
});

app.listen(3000);

Creation of the database with the access user

The name of the database is login-socket, for the database creation process, you must access XAMPP and activate the Apache and MySQL service.

Then the following URL is accessed:

http://localhost/phpmyadmin/

The database is created with the name login-socket, click on the SQL section and insert the following code:

-- phpMyAdmin SQL Dump
-- version 5.1.1
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 09-05-2022 a las 17:18:44
-- Versión del servidor: 10.4.21-MariaDB
-- Versión de PHP: 8.0.11

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Base de datos: `login-socket`
--

-- --------------------------------------------------------

--
-- Estructura de tabla para la tabla `accounts`
--

CREATE TABLE `accounts` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Volcado de datos para la tabla `accounts`
--

INSERT INTO `accounts` (`id`, `username`, `password`, `email`) VALUES
(1, 'configuroweb', '1234abcd..', 'hola@configuroweb.com');

--
-- Índices para tablas volcadas
--

--
-- Indices de la tabla `accounts`
--
ALTER TABLE `accounts`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT de las tablas volcadas
--

--
-- AUTO_INCREMENT de la tabla `accounts`
--
ALTER TABLE `accounts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Activate nodejs server from console

At this point from the console, I paste the following script and it will enable the URL http://localhost:3000/ for application execution:

node login.js

If the system does not show you any error from the console, you will only have to access the following URL and you will be able to test the application:

http://localhost:3000/

The only access user is configuroweb and the password is 1234abcd... as usual.

Downloading the Login system in Nodejs

You can download the application in the following GitHub link

Login with Node.js Express and MySQL

Any questions I remain pending, if you require more PHP applications, in Python or JavaScript I recommend you subscribe to my content on Youtube and be on the lookout for any changes, that I make.

Leave a Reply

Your email address will not be published.