backend/routes/user.js
2023-07-27 23:36:07 -04:00

155 lines
4.8 KiB
JavaScript

const express = require('express');
const router = express.Router();
const User = require('../models/User');
const jwt = require('jsonwebtoken');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const fs = require('fs');
const AWS = require('aws-sdk');
AWS.config.update({
accessKeyId: "178dce4e3eb2f06893ddc54b13712b52",
secretAccessKey: "c271b6b5edca93fc341165f6f803cf81617bb238586db07ba959739185020092",
region: "us-east-1" //
});
const s3 = new AWS.S3({
endpoint: 'https://084fb3347d23f6194c7b68aabe0073c8.r2.cloudflarestorage.com/', // Use custom endpoint
s3ForcePathStyle: true // Needed when using a custom endpoint
});
// Verify the JWT in the Authorization header
function authenticate(req, res, next) {
const token = req.header('Authorization');
if (!token) return res.sendStatus(401);
jwt.verify(token, 'SECRET_KEY', (err, decoded) => {
if (err) return res.sendStatus(401);
req.userId = decoded.userId;
next();
});
}
router.post('/follow/:id', authenticate, async (req, res) => {
const { id } = req.params;
const { userId } = req; // Changed from req.user to req
// First, find the user
const user = await User.findById(userId);
// Check if the user is already following the person
if (user.following.includes(id)) {
return res.status(400).json({ error: 'You are already following this user' });
}
if (id === userId) {
return res.status(304).json({ error: 'You cannot follow yourself' });
}
// If not, add the user to the following list
user.following.push(id);
await user.save();
console.log(user.following.length)
console.log(user.following)
// if (socketId) req.app.io.to(socketId).emit('follow', { userId: req.userId, switId: req.params.id }); // Emit the 'like' event to the user who posted the swit
res.status(200).json({ message: 'Followed user', "count": user.following.length });
});
router.post('/unfollow/:id', authenticate, async (req, res) => {
const { id } = req.params;
const user = await User.findById(id);
if (!user) return res.sendStatus(404);
const me = await User.findById(req.userId);
// Use the $pull operator to remove user._id from me.following
await User.findByIdAndUpdate(req.userId, {
$pull: { following: user._id }
});
console.log(user.following.length)
console.log(user.following)
res.status(200).json({ message: 'Unfollowed user', "count": user.following.length });
});
router.get('/search', authenticate, async (req, res) => {
const query = req.query.q;
const users = await User.find({ username: { $regex: query, $options: 'i' } }).select('-password -__v');
console.log(users)
res.json(users);
});
router.get('/data/:id', authenticate, async (req, res) => {
const { id } = req.params;
const user = await User.findById(id).select('-password -__v').populate('following');
if (!user) return res.sendStatus(404);
res.json(user);
});
router.put('/data/:id/edit', authenticate, async (req, res) => {
const { username, profilePicture, bio, pronouns, email, name } = req.body;
const userId = req.userId;
const user = await User.findById(userId);
if (!user) return res.sendStatus(404);
if (username !== undefined) user.username = username;
if (profilePicture !== undefined) user.profilePicture = profilePicture;
if (bio !== undefined) user.bio = bio;
if (pronouns !== undefined) user.pronouns = pronouns;
if (email !== undefined) user.email = email;
if (name !== undefined) user.name = name;
await user.save();
res.status(200).json({ message: 'Profile updated successfully' });
});
router.get('/followers/:id', authenticate, async (req, res) => {
const { id } = req.params;
const user = await User.findById(id);
if (!user) return res.sendStatus(404);
const followers = await User.find({ following: id });
res.json(followers);
});
router.post('/profilePicture', authenticate, upload.single('profilePicture'), async (req, res) => {
const user = await User.findById(req.userId);
const uploadParams = {
Bucket: 'swifter',
Key: "cdn/pfp/" + req.file.filename, // you might want to add a directory prefix or a unique identifier
Body: fs.createReadStream(req.file.path), // create a read stream from the uploaded file
ACL: 'public-read', // so the file is publicly readable
ContentType: req.file.mimetype,
};
console.log(uploadParams)
s3.upload(uploadParams, async function(err, data) {
if (err) {
console.log("Error", err);
} if (data) {
console.log("Upload Success: ", data);
user.profilePicture = "https://swifter.jiafeiproducts.xyz/" + data.Key;
console.warn("user: ", user)
await user.save();
console.log('saved')
res.sendStatus(200);
console.log('sent')
}
});
});
module.exports = router;