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

Project-Auth Lovisa, Axel, Alexandra #343

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
12 changes: 7 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
# 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.
In this project, we practised authentication and authorization for a unique user to be able to sign up or log in to an application with a password.

## 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?
We created a backend first and matched a frontend to it. We used Mongoose for backend and React Router for our frontend.

## 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.
Backend:
https://project-auth-irev.onrender.com/

Frontend:
https://clever-scone-066fd8.netlify.app/
29 changes: 29 additions & 0 deletions backend/models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import mongoose from "mongoose"
import bcrypt from "bcrypt"

//Schema - the blueprint
const { Schema, model } = mongoose

const userSchema = new Schema({
name: {
type: String,
},
email: {
type: String,
unique: true,
},
password: {
type: String,
required: true
},
accessToken: {
type: String,
default: () => bcrypt.genSaltSync()
}
});

//Model
const User = model("User", userSchema)

export default User

5 changes: 5 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,13 @@
"@babel/core": "^7.17.9",
"@babel/node": "^7.16.8",
"@babel/preset-env": "^7.16.11",
"bcrypt": "^5.1.1",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.17.3",
"express-list-endpoints": "^7.1.0",
"install": "^0.13.0",
"mongodb": "^6.6.2",
"mongoose": "^8.0.0",
"nodemon": "^3.0.1"
}
Expand Down
119 changes: 100 additions & 19 deletions backend/server.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,108 @@
import cors from "cors";
import express from "express";
import mongoose from "mongoose";
import cors from "cors"
import express from "express"
import mongoose from "mongoose"
import bcrypt from "bcrypt"
import User from "./models/User"
import dotenv from "dotenv"
import expressListEndpoints from "express-list-endpoints"

const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo";
mongoose.connect(mongoUrl);
mongoose.Promise = Promise;
//Dot env
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/project-auth"
mongoose.connect(mongoUrl)
mongoose.Promise = Promise

// Add middlewares to enable cors and json body parsing
app.use(cors());
app.use(express.json());
// Defines the port the app will run on.
const port = process.env.PORT || 8080
const app = express()

// Start defining your routes here
// Middlewares to enable cors and json body parsing
app.use(cors())
app.use(express.json())

//Middleware to authenticate user with accesstoken
const authenticateUser = async (req, res, next) => {
const user = await User.findOne({ accessToken: req.header("Authorization") })
if (user) {
req.user = user
next()
} else {
res
.status(401)
.json({
loggedOut: true,
message: "You have to log in to view this page",
})
}
}

// Route handler
app.get("/", (req, res) => {
res.send("Hello Technigo!");
});
const endpoints = expressListEndpoints(app)
res.json(endpoints)
})

//Sign up endpoint
app.post("/signup", async (req, res) => {
try {
const { name, email, password } = req.body
const user = new User({
name,
email,
password: bcrypt.hashSync(password, 10),
})
await user.save()
res.status(201).json({
id: user._id,
accessToken: user.accessToken,
success: true,
response: user,
message: "You are now signed up",
})
} catch (err) {
res.status(400).json({
message: "Could not create user",
response: err,
success: false,
})
}
})

app.get("/loggedin", authenticateUser)
app.get("/loggedin", (req, res) => {
res.json({
loggedin: "You are logged in and can view this secret message :)",
})
})

app.post("/signin", async (req, res) => {
try {
const user = await User.findOne({ email: req.body.email })

if (user && bcrypt.compareSync(req.body.password, user.password)) {
res.status(200).json({
success: true,
userId: user._id,
accessToken: user.accessToken,
message: "You are successfully logged in",
})
} else {
res.status(401).json({
success: false,
message: "Email or password is incorrect, please try again",
})
}
} catch (error) {
res.status(500).json({
success: false,
message: "Error signing in, please try again",
error: error.message,
})
}
})

// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
console.log(`Server running on http://localhost:${port}`)
})
3 changes: 3 additions & 0 deletions frontend/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,100;0,300;0,400;0,700;0,900;1,100;1,300;1,400;1,700;1,900&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React</title>
</head>
Expand Down
4 changes: 3 additions & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
"preview": "vite preview"
},
"dependencies": {
"lottie-react": "^2.4.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
"react-dom": "^18.2.0",
"react-router-dom": "^6.23.1"
},
"devDependencies": {
"@types/react": "^18.2.15",
Expand Down
Binary file added frontend/public/lock.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 9 additions & 2 deletions frontend/src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
import { BrowserRouter } from "react-router-dom"
import { AuthRoutes } from "./routes/AuthRoutes"

export const App = () => {
return <div>Find me in src/app.jsx!</div>;
};
return (
<BrowserRouter>
<AuthRoutes />
</BrowserRouter>
)
}
1 change: 1 addition & 0 deletions frontend/src/components/LoggedIn/Animation.json

Large diffs are not rendered by default.

36 changes: 36 additions & 0 deletions frontend/src/components/LoggedIn/LoggedIn.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
.loggedin-container {
display: flex;
flex-direction: column;
align-items: center;
}

h2 {
color: rgb(88, 63, 114);
font-family: "Lato";
font-size: 40px;
text-align: center;
margin-top: 40px;
}

.signout-button {
height: 40px;
width: 200px;
padding: 10px 10px 10px 16px;
margin-bottom: 40px;
font-size: 16px;
border-radius: 20px;
border: none;
background-color: rgb(53, 60, 90);
color: white;
font-family: "Lato";
font-weight: 600;
cursor: pointer;
}

.signout-button:hover {
background-color: rgb(94, 106, 158);
}

.signout-button:active {
background-color: rgb(88, 63, 114);
}
44 changes: 44 additions & 0 deletions frontend/src/components/LoggedIn/LoggedIn.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { useEffect, useState } from "react"
import { useNavigate } from "react-router-dom"
import Lottie from "lottie-react"
import animationData from "../LoggedIn/Animation.json"
import "./LoggedIn.css"

export const LoggedIn = () => {
//State to see if user is logged in or not based on authentication
const [isLoggedIn, setIsLoggedIn] = useState(false)
const navigate = useNavigate()

useEffect(() => {
const accessToken = localStorage.getItem("accessToken")

if (accessToken) {
setIsLoggedIn(true) //If there is an accesstoken, isLoggedIn is set to true
} else {
navigate("/signin") //If there is no accesstoken, navigate to signin
}
}, [navigate])

//Function to handle signout
const handleSignOut = () => {
localStorage.removeItem("accessToken") //Remove saved accessToken
setIsLoggedIn(false)
navigate("/signup")
}

return (
<div className="loggedin-container">
{isLoggedIn ? (
<>
<h2>You have successfully logged in!</h2>
<Lottie animationData={animationData} />
<button onClick={handleSignOut} className="signout-button">
Sign Out
</button>
</>
) : (
<p>You are not logged in</p>
)}
</div>
)
}
87 changes: 87 additions & 0 deletions frontend/src/components/SignInForm.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { useState } from "react";
import { useNavigate } from "react-router-dom";

export const SignInForm = () => {
// State to manage user input
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");

const navigate = useNavigate();

// Handle sign in

const handleSignIn = async (event) => {
event.preventDefault();

// POST request to autheticate the user
try {
const response = await fetch(
"https://project-auth-irev.onrender.com/signin",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, password }),
}
);

//If authetication ok, call onLogin and redirect to logged in page
if (response.ok) {
const data = await response.json();

localStorage.setItem("accessToken", data.accessToken);
navigate("/loggedin");
} else {
// If login fails, update error state
const errorData = await response.json();
setError(`Login failed: ${errorData.error}`);

if (
response.status === 401 &&
errorData.error === "Invalid email or password, please try again"
) {
//Error message if user writes wrong email or password
setError("Invalid email or password, please try again");
} else {
// Display general error message
setError(`Login failed: ${errorData.error}`);
}
}
} catch (error) {
// If unexpected error
setError(`Error during login: ${error.message}`);
}
};

return (
<>
<form>
<h3>Sign in here:</h3>

<label>
<input
type="email"
value={email}
placeholder="Enter your email here"
onChange={(event) => setEmail(event.target.value)}
/>
</label>

<label>
<input
type="password"
value={password}
placeholder="Enter your password here"
onChange={(event) => setPassword(event.target.value)}
/>
</label>
<button type="submit" onClick={handleSignIn}>
SIGN IN
</button>
{error && <p>{error}</p>}
</form>
</>
);
};
Loading