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 Node.js and Express.js to handle server-side logic,
SQL to store user credentials, and JavaScript for client-side validation and interactions.
Technologies:
- Node.js: Backend runtime environment.
- Express.js: 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 Node.js project:
npm init -y
npm install express mysql body-parser bcryptjs jsonwebtoken
2. Set Up the Server (Express.js):
Create an auth.js 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();
app.use(bodyParser.json());
const secretKey = 'your_secret_key';
// Database connection
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'auth_db'
});
db.connect((err) => {
if (err) throw err;
console.log('Connected to the database');
});
// Register new users
app.post('/register', (req, res) => {
const { username, password } = req.body;
const hashedPassword = bcrypt.hashSync(password, 10);
const sql = 'INSERT INTO users (username, password) VALUES (?, ?)';
db.query(sql, [username, hashedPassword], (err, result) => {
if (err) throw err;
res.send('User registered successfully');
});
});
// Login users
app.post('/login', (req, res) => {
const { username, password } = req.body;
const sql = 'SELECT * FROM users WHERE username = ?';
db.query(sql, [username], (err, result) => {
if (err) throw err;
if (result.length === 0) return res.status(400).send('User not found');
const user = result[0];
const validPassword = bcrypt.compareSync(password, user.password);
if (!validPassword) return res.status(400).send('Invalid password');
const token = jwt.sign({ id: user.id }, secretKey, { expiresIn: '1h' });
res.send({ token });
});
});
// Protected route
app.get('/dashboard', (req, res) => {
const token = req.headers['authorization'];
if (!token) return res.status(401).send('Access denied');
jwt.verify(token, secretKey, (err, decoded) => {
if (err) return res.status(401).send('Invalid token');
res.send('Welcome to the dashboard');
});
});
app.listen(3000, () => {
console.log('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 index.html 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 = document.getElementById('registerUsername').value;
const password = document.getElementById('registerPassword').value;
const response = await fetch('/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const data = await response.text();
alert(data);
async function login() {
const username = document.getElementById('loginUsername').value;
const password = document.getElementById('loginPassword').value;
const response = await fetch('/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const data = await response.json();
localStorage.setItem('token', data.token);
alert('Login successful');
async function accessDashboard() {
const token = localStorage.getItem('token');
const response = await fetch('/dashboard', {
headers: { 'Authorization': token }
});
const data = await response.text();
alert(data);
</script>
</body>
</html>
5. Run the Project:
Start the Node.js server:
node auth.js
Open the browser and visit http://localhost:3000 to interact with the user authentication system.