Handling user login and registration using nodejs and mysql | by Saurabh Mhatre | CodeClassifiers | Medium

#1.10. .env

Create a file named “.env” in the “backend” folder, then type the following code:

ACCESS_TOKEN_SECRET = jsfgfjguwrg8783wgbjs849h2fu3cnsvh8wyr8fhwfvi2g225
REFRESH_TOKEN_SECRET = 825y8i3hnfjmsbv7gwajbl7fobqrjfvbs7gbfj2q3bgh8f42

You are free to set values in ACCESS_TOKEN_SECRET and REFRESH_TOKEN_SECRET above.

To make sure the application runs properly, run the application by typing the following command in the terminal:

nodemon index

If it goes well, it will look like the following image:

Up here you have successfully created a “backend”.

#1.2. create a database

To be able to use MySQL, you need to install XAMPP, WAMP, MAMP, or similar software.

In this tutorial, I use XAMPP.

#1.3. application structure

To make the application more structured neatly, we will apply the MVC pattern (Model-View-Controllers).

Create “config”, “controllers”, “middleware”, “models”, and “routes” folders in the “backend” folder.

#1.4. connect to database

Open the “Database.js” file in the “config” folder, then type the following code:

import { Sequelize } from "sequelize";

const db = new Sequelize('auth_db', 'root', '', {
    host: "localhost",
    dialect: "mysql"
});

export default db;

#1.7. middleware

Open the “VerifyToken.js” file located in the “middleware” folder, then type the following code:

import jwt from "jsonwebtoken";

export const verifyToken = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];
    if(token == null) return res.sendStatus(401);
    jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
        if(err) return res.sendStatus(403);
        req.email = decoded.email;
        next();
    })
}

#1.8. routes

Open the “index.js” file in the “routes” folder, then type the following code:

#1.9. entry point

Open the “index.js” file located in the “backend” folder, then type the following code:

#2.5. dashboard

Open the “Dashboard.js” file located in the “frontend/src” folder, then type the following code:

#2.6. navbar

Open the “Navbar.js” file located in the “frontend/src” folder, then type the following code:

#2.7. app.js

Open the “App.js” file in the “frontend” folder, then change it to the following:

import { BrowserRouter, Route, Switch } from "react-router-dom";
import Dashboard from "./components/Dashboard";
import Login from "./components/Login";
import Navbar from "./components/Navbar";
import Register from "./components/Register";

function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/">
          <Login/>
        </Route>
        <Route path="/register">
          <Register/>
        </Route>
        <Route path="/dashboard">
          <Navbar/>
          <Dashboard/>
        </Route>
      </Switch>
    </BrowserRouter>
  );
}

export default App;

#2.8. index.js

Open the “index.js” file in the “frontend” folder, then change it to the following:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import "bulma/css/bulma.css";
import axios from "axios";

axios.defaults.withCredentials = true;

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

(b) connect your nodejs app to your mysql db

Create a dbServer.js file as follow,

(c) create a .env file and hide your db credentials in there

Create a .env file as follows

Install NodeJS

1. Go to

Angular – making protected page

Remember the interceptor and auth-guard services that we created previously. Let’s use these to create a protected page and also use the JWT that we received during the register/login to request for protected data.

Article update

This article has been updated as of 5th of March 2022. I noticed some of the code are old and broken and has been receiving a lots of comments to fix it. I apologize for the delay to correct it and I hope this would make your day better. Cheers mate!

Without further ado, let’s get started!

Awesome!! you are now connected to your mysql db!!!

Note: that we use mysql.createPool(), instead of mysql.createConnection(), since we want our application to be PRODUCTION grade.

Configure auth key

jsonwebtoken functions such as verify() or sign() use algorithm that needs a secret key (as String) to encode and decode token.

In the app/config folder, create auth.config.js file with following code:

module.exports = {
  secret: "bezkoder-secret-key"
};

You can create your own secret String.

Create node.js express login app

First, we create a folder for our project:

$ mkdir node-js-express-login-example
$ cd node-js-express-login-example

Then we initialize the Node.js App with a package.json file:

npm init
name: (node-js-express-login-example) 
version: (1.0.0) 
description: Node.js Express Login and Registration example
entry point: (index.js) server.js
test command: 
git repository: 
keywords: node.js, express, login, registration, rest api, jwt, authentication, authorization, mysql
author: bezkoder
license: (ISC)
Is this ok? (yes) yes

Creating angular services

Now, before we construct the HTML for our login and register page. We are going to create 4 services.

ng g service services/auth
ng g service services/api
ng g service services/interceptor-service
ng g service services/auth-guard

Open your api.service.ts file and paste the following code.

Further reading

Fullstack CRUD Application:- Vue.js Node.js Express MySQL example- Angular 8 Node.js Express MySQL example- Angular 10 Node.js Express MySQL example- Angular 11 Node.js Express MySQL example- Angular 12 Node.

Deployment:- Deploying/Hosting Node.js app on Heroku with MySQL database- Dockerize Node.js Express and MySQL example – Docker Compose

Install expressjs

1. Go to

Install mysql

1. Go to

Node.js express login example architecture

You can have an overview of our Node.js Express App with the diagram below:

Overview of node.js express login example

We will build a Node.js Express application in that:

These are APIs that we need to provide:

Project structure

This is directory structure for our Node.js Express Login and Registration application:

– config

  • configure MySQL database & Sequelize
  • configure Auth Key

– routes

– middlewares

– controllers

– models for Sequelize Models

– server.js: import and initialize necessary modules and routes, listen for connections.

Source code

You can find the complete source code for this tutorial on Github.

Step 1: install node express js setup

The following command install express js setup:

express --view=ejs myApp

After open myApp setup with any text editor. And use the following command to enter your myApp app directories, So open your cmd and run the following command:

cd loginSystem

Your node express js app structure looks like:

Next, you need to install some required pacakges, so open again your cmd and run the following commands:

 npm install    
 npm install express-flash --save
 npm install express-session --save
 npm install express-validator --save
 npm install method-override --save
 npm install mysql --save

Step 2: connect node express js app with db

Before connecting DB to your application, create table into your database by using the following SQL query:

CREATE DATABASE IF NOT EXISTS `nodelogin` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `nodelogin`;

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(100) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO `users` (`id`, `name`, `password`, `email`) VALUES (1, 'test', 'test', '[email protected]');

ALTER TABLE `users` ADD PRIMARY KEY (`id`);
ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;

Next, you need to create one folder named lib and create a new file name db.js inside lib folder.

Note that, This file is used to connect your node express js app to MySQL db.

Step 3: import packages and routes in app.js

In this step, you need to include all packages in app.js file whose installed above and also initialize the session in this file.

So go to app.js file and update the following code:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressValidator = require('express-validator');
var flash = require('express-flash');
var session = require('express-session');
var bodyParser = require('body-parser');


var mysql = require('mysql');
var connection  = require('./lib/db');


var indexRouter = require('./routes/index');
var authRouter = require('./routes/auth');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({ 
    secret: '123456cat',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 }
}))

app.use(flash());
app.use(expressValidator());

app.use('/', indexRouter);
app.use('/auth', authRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// port must be set to 3000 because incoming http requests are routed from port 80 to port 8080
app.listen(3000, function () {
    console.log('Node app is running on port 3000');
});
module.exports = app;

Step 4: create route

In this step, you need to create one route file name auth.js inside the routes folder.

Then update the following routes into your routes/auth.js file:

var express = require('express');
var router = express.Router();
var connection  = require('../lib/db');
//display login page
router.get('/', function(req, res, next){    
res.render('auth/login', {
title: 'Login',
email: '',
password: ''      
})
})
//display login page
router.get('/login', function(req, res, next){    
res.render('auth/login', {
title: 'Login',
email: '',
password: ''     
})
})
//authenticate user
router.post('/authentication', function(req, res, next) {
var email = req.body.email;
var password = req.body.password;
connection.query('SELECT * FROM accounts WHERE email = ? AND password = ?', [email, password], function(err, rows, fields) {
if(err) throw err
// if user not found
if (rows.length <= 0) {
req.flash('error', 'Please correct enter email and Password!')
res.redirect('/login')
}
else { // if user found
// render to views/user/edit.ejs template file
req.session.loggedin = true;
req.session.name = name;
res.redirect('/home');
}            
})
})
//display login page
router.get('/register', function(req, res, next){    
res.render('auth/register', {
title: 'Registration Page',
name: '',
email: '',
password: ''     
})
})
// user registration
router.post('/post-register', function(req, res, next){    
req.assert('name', 'Name is required').notEmpty()           //Validate name
req.assert('password', 'Password is required').notEmpty()   //Validate password
req.assert('email', 'A valid email is required').isEmail()  //Validate email
var errors = req.validationErrors()
if( !errors ) {   //No errors were found.  Passed Validation!
var user = {
name: req.sanitize('name').escape().trim(),
email: req.sanitize('email').escape().trim(),
password: req.sanitize('password').escape().trim()
}
connection.query('INSERT INTO users SET ?', user, function(err, result) {
//if(err) throw err
if (err) {
req.flash('error', err)
res.render('auth/register', {
title: 'Registration Page',
name: '',
password: '',
email: ''                    
})
} else {                
req.flash('success', 'You have successfully signup!');
res.redirect('/login');
}
})
}
else {   //Display errors to user
var error_msg = ''
errors.forEach(function(error) {
error_msg  = error.msg   '<br>'
})                
req.flash('error', error_msg)        
/**
* Using req.body.name 
* because req.param('name') is deprecated
*/ 
res.render('auth/register', { 
title: 'Registration Page',
name: req.body.name,
email: req.body.email,
password: ''
})
}
})
//display home page
router.get('/home', function(req, res, next) {
if (req.session.loggedin) {
res.render('auth/home', {
title:"Dashboard",
name: req.session.name,     
});
} else {
req.flash('success', 'Please login first!');
res.redirect('/login');
}
});
// Logout user
router.get('/logout', function (req, res) {
req.session.destroy();
req.flash('success', 'Login Again Here');
res.redirect('/login');
});
module.exports = router;

Technology

  • Express 4.17.1
  • bcryptjs 2.4.3
  • cookie-session 1.4.0
  • jsonwebtoken 8.5.1
  • Sequelize 6.11.0
  • MySQL

Testing out!

Handling user login and registration using nodejs and mysql | by Saurabh Mhatre | CodeClassifiers | Medium
profile page

Make sure you are logged in and manually input the url localhost:4200/profile. If you are not logged in, it will redirect you back to the login page.

Let’s create a package.json to install all our dependencies.

you can use npm init to create your own package.json specifying all your dependencies or you can use below given package.json file.

#1.1. install dependency

Create a folder on your computer, here I name it “jwt-auth”.

You are free to make it anywhere, either in C, D, or on the Desktop.

Then open the “jwt-auth” folder using the code editor, here I use Visual Studio Code.

I also suggest you to use Visual Studio Code.

You can download Visual Studio Code at the following link, then install it on your computer:

Conclusion

Congratulation!

Today we’ve learned so many interesting things about Node.js Express Login and Registration example with JWT – JSONWebToken by building Rest Apis for Authentication and Authorization.Despite we wrote a lot of code, I hope you will understand the overall architecture of the application, and apply it in your project at ease.

You should continue to know how to implement Refresh Token:JWT Refresh Token implementation in Node.js example

If you need a working front-end for this back-end, you can find Client App in the post:(just modify using Local Storage to Cookies)- Vue- Angular 8 / Angular 10 / Angular 11 / Angular 12 / Angular 13- React / React Hooks / React Redux

Angular frontend authmodule

Open your command line and go to your app folder in your Angular app. Run the following commands to create an Auth Module.

ng g module auth/auth

Now, you have another module called AuthModule, make sure to import this module in your app.module.ts

@NgModule({
  declarations: [
    AppComponent,    
    
  ],
  imports: [
    BrowserModule,
    AppRoutingModule.
    AuthModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

After that, create a couple of components in our Auth folder.

ng g component auth/components/login
ng g component auth/components/register

This will create two components and will be imported in the AuthModule. Check if you have this correctly.

@NgModule({
  declarations: [
    LoginComponent, 
    RegisterComponent 
  ],
  imports: [
    CommonModule
  ],
  exports : [
    LoginComponent, 
    RegisterComponent 
  ]
})
export class AuthModule { }

Open you app-routing.module and replace the Routes with the following.

const routes: Routes = [
  {path: 'login', component: LoginComponent},
  {path: 'register', component: RegisterComponent},
];

End of article…

There we have it. A Login and Registration System using Angular, Express and MySQL. I sincerely hope that this article would help you in some way or another.

Cheers!

Initialize sequelize

Now create app/models/index.js with content like this:

(a) create a new folder and initialize your nodejs app

$ mkdir db-practice1
$ cd db-practice1
$ npm init --y
//next we will install some node packages$ npm i express mysql
$ npm i nodemon dotenv --save-dev
//We installed "express" and "mysql", and "nodemon" and "dotenv" as devDependencies

Updating frontend angular for protected page

ng g component main/profile

Run & test with results

Run Node.js application with command: node server.js

Tables that we define in models package will be automatically generated in MySQL Database.If you check the database, you can see things like this:

Похожее:  Авторизация через соцсети и регистрация на сайте — Хабр Q&A

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *