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

Username implementation #157

Open
wants to merge 69 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
69 commits
Select commit Hold shift + click to select a range
c5b564b
created frontend route for /profile, placeholder page for profile
Jamiepod1 Nov 26, 2024
415dc63
removed console.log()
Jamiepod1 Nov 26, 2024
dc0cdc6
changed file names
Jamiepod1 Nov 26, 2024
0a270d8
Added component ProtectedRoute, prevents access without logging in. W…
Jamiepod1 Nov 26, 2024
3546b30
Merge pull request #1 from RussellColes/jamie
Jamiepod1 Nov 26, 2024
f75d82b
Added navbar, updated logoutbutton component.
pat-shannon Nov 26, 2024
bd02e54
Attempted package-lock fix
pat-shannon Nov 26, 2024
9b51ea9
remove package.json, package-lock.json
Jamiepod1 Nov 26, 2024
80bfac6
remove package.json, package-lock.json
Jamiepod1 Nov 26, 2024
abe0cf3
gitignore fix
pat-shannon Nov 26, 2024
ae3fd00
Merge pull request #3 from RussellColes/jamie
Jamiepod1 Nov 26, 2024
e61d3bc
Merge branch 'main' into patrick
RussellColes Nov 26, 2024
836ef6f
added 2 images and updated trello link in REA
RussellColes Nov 26, 2024
226d16f
Merge pull request #4 from RussellColes/patrick
Jamiepod1 Nov 27, 2024
3d8c1c2
Merge pull request #5 from RussellColes/Russell
RussellColes Nov 27, 2024
54c2f74
Added post and new post jsx files in components
Ali0k Nov 27, 2024
5dd8d65
Merge pull request #6 from RussellColes/Ali
pat-shannon Nov 27, 2024
412f4ff
sign up form additions
Fpike Nov 27, 2024
d42a78d
Merge pull request #7 from RussellColes/signup
Fpike Nov 27, 2024
ed2f4dd
sign up photo additions
Fpike Nov 27, 2024
0b056de
Added NewPost component, tests (incomplete)
pat-shannon Nov 27, 2024
b8a8cac
added working tests, NewPost component, updated FeedPage refresh logi…
Jamiepod1 Nov 28, 2024
aa383cc
Merge pull request #8 from RussellColes/1
Jamiepod1 Nov 28, 2024
445a6dd
fixed sign up page
Fpike Nov 28, 2024
5b2a180
Merge pull request #9 from RussellColes/image-upload
pat-shannon Nov 28, 2024
0c82373
made a get route
Ali0k Nov 28, 2024
cb08503
Merge pull request #10 from RussellColes/userRoute
Ali0k Nov 28, 2024
9420f95
comment out GET /profile route while function not defined, updated te…
Jamiepod1 Nov 28, 2024
bda2589
GET /users method for getting own user details, all tests pass, we ar…
Jamiepod1 Nov 28, 2024
148aac9
photo additions
Fpike Nov 28, 2024
47c1d4e
Merge pull request #12 from RussellColes/photo
RussellColes Nov 28, 2024
83024ee
Merge pull request #11 from RussellColes/get-user-details
pat-shannon Nov 28, 2024
edaab7b
Fixed cannot login?? moved tokenChecker validation to within users.js…
Jamiepod1 Nov 28, 2024
a9e9cd8
frontend photo upload additions
Fpike Nov 29, 2024
dba2e88
Merge pull request #13 from RussellColes/get-user-details
RussellColes Nov 29, 2024
71e8eb7
Merge pull request #14 from RussellColes/photo
RussellColes Nov 29, 2024
eb7495e
name displays on profile page, removed some comments
Jamiepod1 Nov 29, 2024
caf300b
Merge pull request #15 from RussellColes/profile-name
RussellColes Nov 29, 2024
b3569a1
Accidently added sort feed
Jamiepod1 Nov 29, 2024
c9ce717
photo display additions
Fpike Nov 29, 2024
d860a60
Merge pull request #16 from RussellColes/sort
RussellColes Nov 29, 2024
b85ea7a
Merge pull request #17 from RussellColes/photo
Fpike Nov 29, 2024
882fefb
Completed profile uploads! added mechanism to get photo after uploadi…
Jamiepod1 Nov 29, 2024
00ab8bd
Merge pull request #18 from RussellColes/profile-photo-complete
RussellColes Nov 30, 2024
6ac38c1
Started adding like functionality
pat-shannon Dec 2, 2024
30fce22
CHanged post schema, create post creates user_id
Jamiepod1 Dec 2, 2024
7fdec66
Merge pull request #19 from RussellColes/user-data-in-posts
RussellColes Dec 2, 2024
90baf60
changed comments
Jamiepod1 Dec 2, 2024
a18e06e
altered getAllPosts to add firstname lastname to response json
Jamiepod1 Dec 2, 2024
319909f
Merge pull request #20 from RussellColes/get-user-details-on-posts
Jamiepod1 Dec 2, 2024
5b5435c
Added photo url to getPosts so that front end can make a request to g…
Jamiepod1 Dec 2, 2024
93c2b85
Merge pull request #21 from RussellColes/post-shows-photos
RussellColes Dec 2, 2024
cc3e8d8
Finished like functionality - now displays
pat-shannon Dec 2, 2024
9ba04b5
prevents submitting an empty string and introduces character limit
Ali0k Dec 2, 2024
1965abb
added default photo
Jamiepod1 Dec 2, 2024
7df18cd
Merge branch 'main' into es
RussellColes Dec 2, 2024
4021e5f
Merge pull request #22 from RussellColes/es
Jamiepod1 Dec 2, 2024
6c307c1
Like button (nearly) works
pat-shannon Dec 2, 2024
3b5c389
default photo shows if you havent't uploaded a photo
Jamiepod1 Dec 2, 2024
c0773e3
Merge branch 'main' into temp
RussellColes Dec 2, 2024
0fb4a88
Merge pull request #23 from RussellColes/temp
Jamiepod1 Dec 2, 2024
dc4ed97
Merge pull request #24 from RussellColes/default-photo
RussellColes Dec 2, 2024
c7473c1
fixed posts
Jamiepod1 Dec 2, 2024
1b4e790
Merge pull request #25 from RussellColes/bug-fix-posts
Jamiepod1 Dec 2, 2024
05f4fbf
changed photo schema, can now change profile photo
Jamiepod1 Dec 2, 2024
3650eae
Merge pull request #26 from RussellColes/update-profile-photo
RussellColes Dec 2, 2024
dd04c1d
Added likes to createPost
pat-shannon Dec 2, 2024
60dc600
Merge pull request #27 from RussellColes/like-button-display
RussellColes Dec 2, 2024
297a25f
Username functionality added and some inital bits commented out for d…
RussellColes Dec 3, 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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
.DS_Store
.vscode
.vscode
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ the application works.

### Card wall

REPLACE THIS TEXT WITH A LINK TO YOUR CARD WALL
[LINK TO THE TRELLO BOARD WALL](https://trello.com/b/MbzzGYju/acebook-meta-sd-specialism)

### Quickstart

Expand Down
2 changes: 1 addition & 1 deletion api/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
node_modules
.env
.env
94 changes: 91 additions & 3 deletions api/app.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const multer = require('multer');
const path = require('path');

const usersRouter = require("./routes/users");
const postsRouter = require("./routes/posts");
const authenticationRouter = require("./routes/authentication");
const tokenChecker = require("./middleware/tokenChecker");
// const upload = require("./middleware/multerConfig");
const photoRouter = require("./routes/uploadPhoto");

// const upload = multer("api/uploads");

const app = express();

Expand All @@ -16,16 +22,24 @@ app.use(cors());

// Parse JSON request bodies, made available on `req.body`
app.use(bodyParser.json());
// app.use(express.bodyParser({limit: '50mb'}));
// app.use(express.json({ limit: '50mb' }));
// app.use(express.urlencoded({ limit: '50mb', extended: true}))

// const upload = multer({ storage: storage });

// API Routes
app.use("/users", usersRouter);
app.use("/posts", tokenChecker, postsRouter);
app.use("/tokens", authenticationRouter);
app.use("/photo", tokenChecker, photoRouter);
app.use("/uploads", express.static(path.join(__dirname, 'uploads')));
app.use("/checkusername", usersRouter);
// app.use("/get-photo", tokenChecker, photoRouter);


// 404 Handler
app.use((_req, res) => {
res.status(404).json({ err: "Error 404: Not Found" });
});


// Error handler
app.use((err, _req, res, _next) => {
Expand All @@ -37,4 +51,78 @@ app.use((err, _req, res, _next) => {
}
});

/////////////////
const mongoose = require('mongoose');
// const multer = require('multer');
const Photo = require('./models/photo');
// require("./models/photo");
// const Photo = mongoose.model(Photo);

app.get("/", async (req, res) => {
res.send("Success!");
});

// app.listen(3001, () => {
// console.log("Server started");
// })

// const storage = multer.diskStorage({
// destination: function (req, file, cb) {
// cb(null, '../frontend/src/photos/')
// },
// filename: function (req, file, cb) {
// const uniqueSuffix = Date.now();
// cb(null, uniqueSuffix + file.originalname);
// }
// })

// const upload = multer({ storage: storage })

// app.post("/upload-photo", upload.single("photo"), async (req, res) => {
// console.log(req.file)
// const photoName = req.file.filename;
// const photoPath = req.file.path;
// const dateNow = Date.now()
// const user_id = req.user_id

// try {
// await Photo.create({photoFileName: photoName, photoFilePath: photoPath, photoFileDate: dateNow, user_id: user_id})
// res.json({status:"ok"})
// } catch (error) {
// res.json({status:"error"})
// }

// });


// app.get("/get-photo", async(req, res) => {
// try {
// // Photo.find({ user_id: req.user_id }).then(data => {
// // res.send({status: "ok", data: data})
// // })
// res.json({ status: "ok"})
// } catch (error) {
// res.json({status:"error"})
// }
// })

function listRoutes() {
const routes = [];
app._router.stack.forEach((middleware) => {
if (middleware.route) {
const path = middleware.route.path;
console.log(middleware.route.methods)
console.log(path)
}
});
console.log(routes);
}

// Call to list the routes
listRoutes();

app.use((_req, res) => {
res.status(404).json({ err: "Error 404: Not Found" });
});

module.exports = app;
64 changes: 64 additions & 0 deletions api/controllers/photo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
const Photo = require("../models/photo");
const { generateToken } = require("../lib/token");
const fs = require('fs');
const path = require('path');


async function upload(req, res) {
console.log(req.file)
const photoName = req.file.filename;
const photoPath = req.file.path;
// const photoPath = "I broke your code";
// const dateNow = Date.now()
const user_id = req.user_id
const photos = await Photo.find({ user_id: user_id })
if (photos.length !== 0) {
const result = await Photo.findByIdAndDelete(photos[0]._id)
}

try {
await Photo.create({photoFileName: photoName, photoFilePath: photoPath, user_id: user_id})
res.json({status:"ok"})
} catch (error) {
res.json({status:"error"})
}

}


async function get(req, res) {
try {
const photo = await Photo.find({ user_id: req.user_id })
const newToken = generateToken(req.user_id);
// const photoPath = path.join(__dirname, photos[0].photoFilePath);
// console.log(photoPath)
// fs.readFile(photoPath, (err, data) => {
// if (err) {
// console.error("Error reading photo:", err);
// return res.status(500).json({ message: "Error reading photo" });
// }

// res.setHeader('Content-Type', 'image/png');
// res.status(200).send(data);
// });
let filePath
if (photo.length === 0) {
filePath = "uploads/default_photo.webp"
} else {
filePath = photo[0].photoFilePath
}
res.status(200).json({ filePath: filePath, token: newToken })

} catch (error) {
res.status(400);
}

}


const photoController = {
upload: upload,
get: get
};

module.exports = photoController;
109 changes: 107 additions & 2 deletions api/controllers/posts.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,128 @@
const Post = require("../models/post");
const { generateToken } = require("../lib/token");
const User = require("../models/user");

const mongoose = require("mongoose");
const Photo = require("../models/photo");

async function getAllPosts(req, res) {
const posts = await Post.find();
console.log("posts:", posts)


const postsWithUserDetails = await Promise.all(
posts.map(async (post) => {
console.log(post.user_id)
const user_id = post.user_id;


const user_data = await User.find({ _id: user_id });

const photo = await Photo.find({ user_id: user_id })
let filePath
if (photo.length === 0) {
filePath = "uploads/default_photo.webp"
} else {
filePath = photo[0].photoFilePath
}


const enrichedPost = {
...post._doc,
firstName: user_data[0].firstName,
lastName: user_data[0].lastName,
filePath: filePath
};
return enrichedPost;
})
);
const filteredPosts = postsWithUserDetails.sort((a, b) => b._id.getTimestamp() - a._id.getTimestamp());
const token = generateToken(req.user_id);
res.status(200).json({ posts: posts, token: token });
res.status(200).json({ posts: filteredPosts, token: token });
}

async function createPost(req, res) {
const post = new Post(req.body);

const newPostData = {
message: req.body.message,
user_id: new mongoose.Types.ObjectId(req.user_id),
likes: [],
likeCount: 0


}
const post = new Post(newPostData);
post.save();

const newToken = generateToken(req.user_id);
res.status(201).json({ message: "Post created", token: newToken });
}

// NEW:
async function likePost(req, res) {
// console.log(req);
try {
const postId = req.body.post_id;
// We need to call likePost with the postId
// const user_id = req.user_id;
const user_id = new mongoose.Types.ObjectId(req.user_id)
// include user's id (from token)
// console.log('Test post id' + postId);

console.log('my regular Post ID is '+ postId)
postObjectId = new mongoose.Types.ObjectId(postId)
console.log('my Object Post ID is '+ postObjectId)
const post = await Post.findById(postObjectId);

console.log('Test log')
console.log('This is my post: '+post);
if (!post) {
console.log('Not post');
return res.status(404).json({message: "Post not found"});
}
console.log('if statement passes successfully');
const hasLiked = post.likes.includes(user_id);
console.log(hasLiked);


if (hasLiked) {
post.likes = post.likes.filter(id => id.toString() !== user_id);
post.likeCount -= 1;
} else {
post.likes.push(user_id);
post.likeCount += 1;
}
console.log('Passes');

await post.save();
console.log('really?')
const newToken = generateToken(user_id);
console.log('broken?')
res.status(200).json({
message: hasLiked ? "Post Unliked" : "Post Liked",
likeCount: post.likeCount,
token: newToken
});
} catch (error) {
res.status(500).json({ message: "Error liking post", error: error.message});
}
}

const PostsController = {
getAllPosts: getAllPosts,
createPost: createPost,
likePost: likePost,
};

module.exports = PostsController;




//CODE FOR GETTING OWN POST
// async function getAllPosts(req, res) {
// const posts = await Post.find({ userId: req.user_id });
// const token = generateToken(req.user_id);
// // console.log(req.user_id)
// res.status(200).json({ posts: posts, token: token });
// }
35 changes: 34 additions & 1 deletion api/controllers/users.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
const User = require("../models/user");
const { generateToken } = require("../lib/token");
const Photo = require("../models/photo")

function create(req, res) {
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const username = req.body.username;
const email = req.body.email;
const password = req.body.password;

const user = new User({ email, password });
const user = new User({ firstName, lastName, username, email, password });
user
.save()
.then((user) => {
Expand All @@ -17,8 +22,36 @@ function create(req, res) {
});
}

async function getUserProfile(req, res) {
const user = await User.find({ _id: req.user_id });
const token = generateToken(req.user_id);

const returnUserData = {
firstName: user[0].firstName,
lastName: user[0].lastName,
}
res.status(200).json({ userData: returnUserData, token: token });
}

async function checkUsername(req, res) {
const {username} = req.query;

try {
const user = await User.findOne({username});
if (user) {
return res.status(200).json({ unique: false }); // Username exists
}
res.status(200).json({unique: true }); // Username is unique
} catch (error) {
console.error(error);
res.status(500).json({error: "Server error" });
}
}

const UsersController = {
create: create,
getUserProfile: getUserProfile,
checkUsername: checkUsername
};

module.exports = UsersController;
Loading