Skip to content

Commit

Permalink
Merge pull request #14 from Abhrajitdas02/react-mongo
Browse files Browse the repository at this point in the history
feat: added signout to `templates/FullStack/React(Frontend)+Nodejs(Backend)`
  • Loading branch information
Abhishek-Mallick authored Aug 26, 2024
2 parents 41ef89d + fc180c0 commit 915dcdd
Show file tree
Hide file tree
Showing 5 changed files with 180 additions and 15 deletions.
101 changes: 101 additions & 0 deletions templates/FullStack/React(Frontend)+Nodejs(Backend)/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# FullStack Template: React + Node.js

This repository provides a simple FullStack template for building modern web applications using React for the frontend and Node.js for the backend. It includes essential features such as user authentication, session management, and a responsive user interface.

## Features

- **User Authentication**: Supports user registration and login with session management.
- **Frontend**: Built with React, offering a dynamic and responsive user interface.
- **Backend**: Powered by Node.js with Express, providing a robust RESTful API.
- **API Integration**: Seamless communication between the frontend and backend through API calls.
- **Session Management**: Utilizes Express sessions to manage user states.
- **Responsive Design**: Ensures the application is accessible on various devices.

## Technologies Used

### Frontend

- **React**: A JavaScript library for building user interfaces.
- **Bootstrap**: For responsive and mobile-first UI design.
- **React Router**: Handles navigation and routing in the application.

### Backend

- **Node.js**: A JavaScript runtime built on Chrome's V8 JavaScript engine.
- **Express**: A minimal and flexible Node.js web application framework.
- **MongoDB**: A NoSQL database known for its flexibility and scalability.
- **Mongoose**: An elegant MongoDB object modeling for Node.js.

## Installation
1. **Populate the .env.example file**:

```bash
MONGO_URL
JWT_SECRET
```

2. **Install the required dependencies**:

```bash
npm install
```

3. **Ensure MongoDB is running**:
- Make sure your MongoDB server is running locally or accessible remotely.

4. **Run the application**:

```bash
npm run dev
both client and server
```

5. **Access the application**:

Visit `http://localhost:5173/` in your web browser.

## Routes and Functionalities

- **`/register` [GET, POST]**:
- **GET**: Renders the registration page where new users can sign up.
- **POST**: Handles the form submission for user registration. If the username is already taken, it flashes an error message. Otherwise, it creates a new user and redirects to the login page with a success message.

- **`/signin` [POST]**:
- **GET**: Renders the login page where users can log in with their credentials.
- **POST**: Handles the login form submission. If the credentials are correct, it logs the user in by storing their user ID in the session and redirects to the dashboard. If the credentials are incorrect, it flashes an error message.

- **`/signup` [POST]**:
- Displays the dashboard page if the user is logged in. If not, it redirects to the login page.

- **`/logout` [POST]**:
- Logs the user out by clearing their session and redirects them to the home page.

- **`/` [GET]**:
- Renders the homepage of the application.

## Flash Messages

The application uses flash messages to communicate the following events to the user:

- **Signup**:
- **Success**: "Signup successful. Please signin."
- **Error**: "Username already exists. Please choose a different one."

- **Signin**:
- **Error**: "Invalid username or password. Please try again."

These messages are displayed on the frontend in the registration and login pages.

## Database

The application uses MongoDB for storing user information. The `users` collection in the MongoDB database contains the following fields for each user:

- **_id**: ObjectId, the unique identifier for each document (user).
- **username**: String, unique, cannot be null.
- **emailid**: String, unique, cannot be null.
- **password**: String, hashed, cannot be null.

---

Made using [Universal-Box](https://github.com/Abhishek-Mallick/universal-box)

Original file line number Diff line number Diff line change
@@ -1,31 +1,83 @@
import React from 'react';
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import logo from '../public/logo.webp'; // Ensure this path is correct

function Header() {
const [isSignedIn, setIsSignedIn] = useState(false);
const navigate = useNavigate();

// Check sign-in status on component mount
useEffect(() => {
const signedInStatus = localStorage.getItem('isSignedIn');
if (signedInStatus === 'true') {
setIsSignedIn(true);
}
}, []);

const handleSignOut = async () => {
try {
const res = await fetch('http://localhost:3000/api/user/signout', {
method: 'POST',
});

if (!res.ok) {
const errorData = await res.json();
console.log('Error:', errorData.message);
return;
}

const data = await res.json();
console.log('Sign out successful:', data.message);
setIsSignedIn(false);
localStorage.removeItem('isSignedIn');
navigate('/signin'); // Redirect to sign-in page
} catch (error) {
console.error('Sign out error:', error.message);
}
};

const handleSignIn = () => {
// Simulate a sign-in process
setIsSignedIn(true);
localStorage.setItem('isSignedIn', 'true');
};

return (
<nav className="bg-gradient-to-r from-gray-800 to-black p-4 shadow-lg">
<div className="container mx-auto flex items-center justify-between">
<a href="/" className="flex items-center space-x-3">
<div className="flex items-center space-x-3">
<img
src={logo} // Use the imported logo here
alt="Logo"
className="w-12 h-12 object-cover rounded-full" // Adjust size as needed
/>
<span className="text-white text-2xl font-bold">Universal-Box</span>
</a>
</div>
<div className="flex items-center space-x-6">
<a
href="/signin"
className="text-white hover:text-gray-300 transition duration-200"
>
Sign In
</a>
<img
src="https://via.placeholder.com/40"
alt="User DP"
className="w-10 h-10 rounded-full border-2 border-white shadow-md"
/>
{isSignedIn ? (
<>
<button
onClick={handleSignOut}
className="text-white hover:text-gray-300 transition duration-200"
>
Sign Out
</button>
<img
src="https://via.placeholder.com/40"
alt="User DP"
className="w-10 h-10 rounded-full border-2 border-white shadow-md"
/>
</>
) : (
<a
href="/signin"
className="text-white hover:text-gray-300 transition duration-200"
onClick={handleSignIn}
>
Sign In
</a>
)}
</div>
</div>
</nav>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
MONGO_URL
JWT_SECRET
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
export const test = (req, res) => {
res.json({ message: 'API is working!'});
};

export const signout = (req, res, next) => {
try {
res.clearCookie('access_token').status(200).json('USer has been signed out!!');

} catch (error) {
next(error);
}
};
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import express from "express";
import { test } from "../controllers/user.controller.js";
import { signout, test } from "../controllers/user.controller.js";

const router = express.Router();

router.get("/test", test);
router.post("/signout", signout);


export default router;

0 comments on commit 915dcdd

Please sign in to comment.