0% found this document useful (0 votes)
13 views7 pages

User Authentication System Setup Guide

Uploaded by

r180652
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views7 pages

User Authentication System Setup Guide

Uploaded by

r180652
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

User Authentication System

Overview:

This project implements a simple user authentication system where users can sign up, log in, and

access protected routes after logging in. It uses [Link] and [Link] to handle server-side logic,

SQL to store user credentials, and JavaScript for client-side validation and interactions.

Technologies:

- [Link]: Backend runtime environment.

- [Link]: Web framework for handling routes and middleware.

- SQL: To store and manage user data.

- JavaScript: For front-end interactions.

Steps:

1. Initialize the Project:

Set up a new [Link] project:

npm init -y

npm install express mysql body-parser bcryptjs jsonwebtoken

2. Set Up the Server ([Link]):

Create an [Link] file to manage user authentication:

const express = require('express');

const bodyParser = require('body-parser');

const bcrypt = require('bcryptjs');

const jwt = require('jsonwebtoken');


const mysql = require('mysql');

const app = express();

[Link]([Link]());

const secretKey = 'your_secret_key';

// Database connection

const db = [Link]({

host: 'localhost',

user: 'root',

password: '',

database: 'auth_db'

});

[Link]((err) => {

if (err) throw err;

[Link]('Connected to the database');

});

// Register new users

[Link]('/register', (req, res) => {

const { username, password } = [Link];

const hashedPassword = [Link](password, 10);

const sql = 'INSERT INTO users (username, password) VALUES (?, ?)';

[Link](sql, [username, hashedPassword], (err, result) => {


if (err) throw err;

[Link]('User registered successfully');

});

});

// Login users

[Link]('/login', (req, res) => {

const { username, password } = [Link];

const sql = 'SELECT * FROM users WHERE username = ?';

[Link](sql, [username], (err, result) => {

if (err) throw err;

if ([Link] === 0) return [Link](400).send('User not found');

const user = result[0];

const validPassword = [Link](password, [Link]);

if (!validPassword) return [Link](400).send('Invalid password');

const token = [Link]({ id: [Link] }, secretKey, { expiresIn: '1h' });

[Link]({ token });

});

});

// Protected route

[Link]('/dashboard', (req, res) => {

const token = [Link]['authorization'];

if (!token) return [Link](401).send('Access denied');


[Link](token, secretKey, (err, decoded) => {

if (err) return [Link](401).send('Invalid token');

[Link]('Welcome to the dashboard');

});

});

[Link](3000, () => {

[Link]('Server running on port 3000');

});

3. Set Up the SQL Database:

Create a database auth_db and a table users:

CREATE DATABASE auth_db;

USE auth_db;

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

username VARCHAR(255) NOT NULL,

password VARCHAR(255) NOT NULL

);

4. Frontend (HTML + JavaScript):

Basic [Link] for user registration and login:

<!DOCTYPE html>

<html>
<head>

<title>User Authentication</title>

</head>

<body>

<h1>User Authentication System</h1>

<h2>Register</h2>

<input type="text" id="registerUsername" placeholder="Username">

<input type="password" id="registerPassword" placeholder="Password">

<button onclick="register()">Register</button>

<h2>Login</h2>

<input type="text" id="loginUsername" placeholder="Username">

<input type="password" id="loginPassword" placeholder="Password">

<button onclick="login()">Login</button>

<h2>Dashboard</h2>

<button onclick="accessDashboard()">Access Dashboard</button>

<script>

async function register() {

const username = [Link]('registerUsername').value;

const password = [Link]('registerPassword').value;

const response = await fetch('/register', {

method: 'POST',

headers: { 'Content-Type': 'application/json' },


body: [Link]({ username, password })

});

const data = await [Link]();

alert(data);

async function login() {

const username = [Link]('loginUsername').value;

const password = [Link]('loginPassword').value;

const response = await fetch('/login', {

method: 'POST',

headers: { 'Content-Type': 'application/json' },

body: [Link]({ username, password })

});

const data = await [Link]();

[Link]('token', [Link]);

alert('Login successful');

async function accessDashboard() {

const token = [Link]('token');

const response = await fetch('/dashboard', {

headers: { 'Authorization': token }


});

const data = await [Link]();

alert(data);

</script>

</body>

</html>

5. Run the Project:

Start the [Link] server:

node [Link]

Open the browser and visit [Link] to interact with the user authentication system.

Common questions

Powered by AI

During user registration, the system collects a username and password, hashes the password using bcryptjs to ensure it is stored securely, and then inserts the hashed password and username into the SQL database. This process prevents storing plain text passwords, enhancing data security .

Bcryptjs is a suitable choice for password management as it provides a robust hashing mechanism designed to slow down potential brute-force attacks, thanks to its use of salting and iterative hashing. This mitigation against brute force and dictionary attacks makes it a strong option for securing passwords .

Session management is handled using JSON Web Tokens (JWT). Upon successful login, a JWT is generated and returned to the user. This token is stored client-side (e.g., in local storage) and must be included in the Authorization header for accessing protected routes, such as the dashboard. The system verifies the token on each request to ensure its validity, ensuring only authenticated users gain access .

Middleware in Express.js serves as functions that process requests between the server and the client. They are used here to parse JSON payloads in requests using body-parser, handle authentication processes, manage errors, and handle custom routing logic effectively, ensuring code modularity and reusability .

The system establishes a connection to the MySQL database using mysql.createConnection. Upon connection initiation, it checks for errors, throwing an exception if any occur. This step ensures feedback is provided immediately if the database connection fails, allowing for timely debugging and resolution .

Client-side JavaScript enhances user experience by managing dynamic interactions, such as collecting user credentials for registration and login, displaying feedback through interface alerts, and storing session tokens in local storage post-authentication. It facilitates asynchronous requests via fetch API, enhancing responsiveness and interaction flow .

The login process involves verifying the user-provided username and password against the stored credentials in the database. The system uses bcryptjs to compare the password input with the stored hashed password. Upon successful verification, a JSON Web Token (JWT) is generated and returned to the client, which can be used for authorized access to protected routes .

SQL is used for persistent storage of user credentials, ensuring they are organized efficiently for retrieval and modification. The database schema supports user management by providing functions such as INSERT for new user registration and SELECT for retrieving user data during login attempts. It also manages primary keys to uniquely identify user records .

The user authentication system utilizes Node.js as the backend runtime environment for running server-side code. Express.js is used as a web framework to manage routes and middleware operations. SQL is employed to store and manage user data securely, and JavaScript is used for client-side interactions and validations .

Storing JWTs in local storage exposes the application to potential attacks like Cross-Site Scripting (XSS), where malicious scripts could access the tokens. To mitigate this, developers could opt for HTTP-only cookies, which are not accessible via client-side scripts, or implement advanced measures like Content Security Policy (CSP) to reduce the likelihood of XSS attacks .

You might also like