Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auth project Vittoria #340

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Procfile

This file was deleted.

24 changes: 19 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,27 @@
# Project Auth API

Replace this readme with your own information about your project.

Start by briefly describing the assignment in a sentence or two. Keep it short and to the point.
This project is a user authentication system built with React, Express.js, MongoDB, bcrypt, and crypto. The application provides secure user registration, login, and access to protected routes.

## The problem

Describe how you approached to problem, and what tools and techniques you used to solve it. How did you plan? What technologies did you use? If you had more time, what would be next?
.React: For building the frontend.
.Express.js: For handling backend routing and API logic.
.MongoDB: For storing user data.
.bcrypt: For hashing passwords before storing them in the database.
.crypto: For generating secure access tokens.

If more time were available, the next steps would include implementing user roles, adding more comprehensive validation and error handling.

## API Endpoints

GET
./: Basic root route for testing, returns a welcome message.
./secrets: Access a protected route, requires a valid access token.

POST
./users: Register a new user.
./sessions: Log in an existing user.

## View it live

Every project should be deployed somewhere. Be sure to include the link to the deployed project so that the viewer can click around and see what it's all about.
You can view the live project [here](https://doggyadopt.netlify.app/)
3 changes: 2 additions & 1 deletion backend/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules
package-lock.json
package-lock.json
.env
19 changes: 12 additions & 7 deletions backend/package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "project-auth-backend",
"name": "project-auth-backendproject-auth",
"version": "1.0.0",
"description": "Starter project to get up and running with express quickly",
"scripts": {
Expand All @@ -9,12 +9,17 @@
"author": "",
"license": "ISC",
"dependencies": {
"@babel/core": "^7.17.9",
"@babel/node": "^7.16.8",
"@babel/preset-env": "^7.16.11",
"@babel/core": "^7.24.5",
"@babel/node": "^7.23.9",
"@babel/preset-env": "^7.24.5",
"bcrypt-nodejs": "^0.0.3",
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"express": "^4.17.3",
"mongoose": "^8.0.0",
"nodemon": "^3.0.1"
"dotenv": "^16.4.5",
"express": "^4.19.2",
"express-list-endpoints": "^7.1.0",
"mongodb": "^6.6.2",
"mongoose": "^8.3.5",
"nodemon": "^3.1.0"
}
}
127 changes: 108 additions & 19 deletions backend/server.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,116 @@
import express from "express";
import cors from "cors";
import mongoose from "mongoose";
import express from "express"
import cors from "cors"
import mongoose from "mongoose"
import dotenv from "dotenv"
import crypto from "crypto"
import bcrypt from "bcryptjs"

const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo";
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.Promise = Promise;
dotenv.config()

// Defines the port the app will run on. Defaults to 8080, but can be overridden
// when starting the server. Example command to overwrite PORT env variable value:
// PORT=9000 npm start
const port = process.env.PORT || 8080;
const app = express();
const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/Authorization"
mongoose.connect(mongoUrl)
mongoose.Promise = Promise

// Add middlewares to enable cors and json body parsing
app.use(cors());
app.use(express.json());
const User = mongoose.model("User", {
name: {
type: String,
unique: true,
},
email: {
type: String,
unique: true,
},
password: {
type: String,
required: true,
},
accessToken: {
type: String,
default: () => crypto.randomBytes(128).toString("hex"),
},
})
const authenticateUser = async (req, res, next) => {
const user = await User.findOne({
accessToken: req.header("Authorization"),
}).exec()
if (!accessToken) {
return res
.status(401)
.json({ error: "Unauthorized. Access token missing." })
}
if (user) {
req.user = user
next()
} else {
res.status(401).json({ loggedOut: true })
}
}

const port = process.env.PORT || 8080
const app = express()

app.use(cors())
app.use(express.json())

// Enable CORS middleware
app.use(
cors({
origin: true,
methods: ["GET", "POST"],
allowedHeaders: ["Content-Type", "Authorization"],
})
)

// Start defining your routes here
app.get("/", (req, res) => {
res.send("Hello Technigo!");
});
app.get("/", (req, res) => {})
app.post("/users", async (req, res) => {
try {
const { name, email, password } = req.body
const existingUser = await User.findOne({ name }).exec()
if (existingUser) {
return res.status(409).json({ message: "Username already taken" })
}
const user = new User({ name, email, password: bcrypt.hashSync(password) })
user.save()
res.status(201).json({ id: user._id, accessToken: user.accessToken })
} catch (err) {
res.status(400).json({ message: "Could not save user", errors: err.errors })
}
})
app.get("/secrets", authenticateUser)
app.get("/secrets", (req, res) => {
res.send(" This is the secret page to show after logging or registration.")
})
app.post("/sessions", async (req, res) => {
const user = await User.findOne({ email: req.body.email }).exec()
if (user && bcrypt.compareSync(req.body.password, user.password)) {
res.json({ userId: user._id, accessToken: user.accessToken })
} else {
res.json({ notFound: true })
}
})
// app.post("/logout", async (req, res) => {
// try {
// const accessToken = req.header("Authorization")

// // Find the user by the access token and update the accessToken field to invalidate it
// const user = await User.findOneAndUpdate(
// { accessToken },
// { accessToken: null }
// ).exec()

// if (user) {
// res.status(200).json({ message: "Logout successful" })
// } else {
// res.status(401).json({ message: "Unauthorized" })
// }
// } catch (error) {
// console.error("Error logging out:", error)
// res.status(500).json({ message: "Internal server error" })
// }
// })

// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
console.log(`Server running on http://localhost:${port}`)
})
6 changes: 3 additions & 3 deletions frontend/index.html
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<!doctype html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<link rel="icon" type="image/svg+xml" href="/paw-print.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React</title>
<title>DoggyAdopt</title>
</head>
<body>
<div id="root"></div>
Expand Down
6 changes: 4 additions & 2 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.23.1",
"styled-components": "^6.1.11"
},
"devDependencies": {
"@types/react": "^18.2.15",
Expand Down
Binary file added frontend/public/dog.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added frontend/public/dog2.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added frontend/public/dog3.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added frontend/public/dog4.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 10 additions & 0 deletions frontend/public/logo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
150 changes: 150 additions & 0 deletions frontend/public/paw-print.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading