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 #346

Open
wants to merge 36 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
6e18d4f
Delete netlify.toml
AntonellaMorittu May 22, 2024
774efcc
Creating the backend
Paulajungaker May 23, 2024
f8e4b53
Adding netlify file
Paulajungaker May 23, 2024
11e3f91
Creating config file for axios
Paulajungaker May 23, 2024
eb3de0b
Setting up routes and creating navbar
Paulajungaker May 23, 2024
700c5ea
First styling of navbar
Paulajungaker May 23, 2024
f2cd33e
Creating homepage
Paulajungaker May 23, 2024
0886f20
First styling of homepage
Paulajungaker May 23, 2024
5233d74
Changing some styling
Paulajungaker May 23, 2024
53e5133
Making responsive
Paulajungaker May 23, 2024
4e36f26
Creating the Register component
Paulajungaker May 23, 2024
55f8c5d
Creating login component and styling login and register
Paulajungaker May 24, 2024
ee656f0
Creating protected component
Paulajungaker May 24, 2024
d2c37a2
Adding .env file
Paulajungaker May 26, 2024
8df362b
API working
Paulajungaker May 26, 2024
9a381b1
Adding new backend link
Paulajungaker May 26, 2024
f9b925f
Getting API to work for registration
Paulajungaker May 26, 2024
135021f
Working on getting the login to work
Paulajungaker May 26, 2024
69194c0
Trying to get login to work by debugging
Paulajungaker May 27, 2024
46a731b
Trying to solve issues
Paulajungaker May 27, 2024
126e8e7
Redoing backend and testing with postman. Successfull
Paulajungaker May 27, 2024
bad04a0
Login and register is working
Paulajungaker May 27, 2024
48bc4ec
Making able to see protected content and logout
Paulajungaker May 27, 2024
0a1411c
Styling the protected page
Paulajungaker May 27, 2024
aac8108
Changing to deployed backend api
Paulajungaker May 27, 2024
0fc937d
Small changes in paths
Paulajungaker May 27, 2024
6a05786
Changing route
Paulajungaker May 27, 2024
fcb7b43
Small changes
Paulajungaker May 27, 2024
d37ade6
Changing to deployed API
Paulajungaker May 27, 2024
20e9be3
Removing unnecessary components
Paulajungaker May 27, 2024
dd56dba
Testing
Paulajungaker May 27, 2024
80125c0
Updating to store token
Paulajungaker May 27, 2024
d052b22
Correcting spelling error
Paulajungaker May 28, 2024
9544c72
Getting registering to store token
Paulajungaker May 28, 2024
df9ab2f
Updating README
Paulajungaker May 28, 2024
95c2b50
Final styling changes
Paulajungaker May 28, 2024
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
Prev Previous commit
Next Next commit
Working on getting the login to work
  • Loading branch information
Paulajungaker committed May 26, 2024
commit 135021f9c02f2224ffed0d435f974fdcc22238fe
2 changes: 2 additions & 0 deletions backend/models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ userSchema.pre("save", async function (next) {
});

userSchema.methods.matchPassword = async function (enteredPassword) {
console.log("Entered password:", enteredPassword);
console.log("Stored password:", this.password);
return await bcrypt.compare(enteredPassword, this.password);
};

Expand Down
18 changes: 18 additions & 0 deletions backend/routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,25 @@ const router = express.Router();
router.post("/register", async (req, res) => {
const { username, password } = req.body;
try {
// Check if the user already exists
const userExists = await User.findOne({ username });
if (userExists) {
return res.status(400).json({ message: "User already exists" });
}

// Hash the password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

// Create new user
const user = await User.create({ username, password: hashedPassword });

// Generate JWT token
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
expiresIn: "1h",
});

// Store token in user document
user.accessToken = token;
await user.save();

Expand All @@ -33,24 +38,33 @@ router.post("/register", async (req, res) => {

router.post("/login", async (req, res) => {
const { username, password } = req.body;
console.log("Attempting login with:", username, password);

try {
// Find user by username
const user = await User.findOne({ username });
if (!user) {
console.log("User not found");
return res.status(400).json({ message: "Invalid credentials" });
}

// Check if password matches
const isMatch = await user.matchPassword(password);
if (!isMatch) {
console.log("Password does not match");
return res.status(400).json({ message: "Invalid credentials" });
}

// Generate JWT token
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
expiresIn: "1h",
});

// Store token in user document
user.accessToken = token;
await user.save();

console.log("Login successfull");
res.json({ token });
} catch (error) {
console.error("Login error:", error);
Expand All @@ -65,13 +79,17 @@ router.get("/protected", async (req, res) => {
}

try {
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);

// Find user by decoded token ID
const user = await User.findById(decoded.id);
if (!user) {
return res.status(401).json({ message: "Token is not valid" });
}
res.json({ message: "This is protected content" });
} catch (error) {
console.error("Protected route error:", error);
res.status(401).json({ message: "Token is not valid " });
}
});
Expand Down
5 changes: 4 additions & 1 deletion frontend/src/components/Navbar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { Link } from "react-router-dom";
import "../styling/Navbar.css";

const Navbar = () => {
// const location = useLocation();
const token = localStorage.getItem("token");

return (
<nav className="navbar">
<div className="navContainer">
Expand All @@ -27,7 +30,7 @@ const Navbar = () => {
</li>

{/* Contidional rendering based on authentication status */}
{localStorage.getItem("token") ? (
{token ? (
<li className="navItem">
<Link to="/logout" className="navLink">
Logout
Expand Down
1 change: 1 addition & 0 deletions frontend/src/components/auth/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const Login = () => {
const handleSubmit = async (e) => {
e.preventDefault();
try {
console.log("Trying to log in with:", username, password);
const response = await axios.post("/auth/login", {
username,
password,
Expand Down
15 changes: 14 additions & 1 deletion frontend/src/components/auth/Logout.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import { useNavigate } from "react-router-dom";

const Logout = () => {
return;
const navigate = useNavigate();

const handleLogout = () => {
localStorage.removeItem("token");
navigate("/login");
};

return (
<div>
<button onClick={handleLogout}>Logout</button>
</div>
);
};

export default Logout;
2 changes: 2 additions & 0 deletions frontend/src/components/protected/Protected.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import Logout from "../auth/Logout";
import axios from "../../api/config";

const Protected = () => {
Expand Down Expand Up @@ -33,6 +34,7 @@ const Protected = () => {
<div className="protectedContainer">
<h1 className="protectedTitle">Protected Content</h1>
<p>{message}</p>
<Logout />
</div>
);
};
Expand Down