Skip to content
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
15 changes: 15 additions & 0 deletions clients/src/apis/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,18 @@ export const checkValid = async () => {
window.location.href = '/chats';
}
};
export const uploadProfilePicture = async (formData) => {
try {
const token = localStorage.getItem('userToken');
const response = await axios.post(`${url}/api/upload/upload-profile-pic`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${token}`
}
});
return response.data;
} catch (error) {
console.error('Error uploading profile picture:', error);
throw error;
}
};
126 changes: 84 additions & 42 deletions clients/src/components/Profile.jsx
Original file line number Diff line number Diff line change
@@ -1,71 +1,113 @@
import React, { useState } from 'react'
import { IoArrowBack } from "react-icons/io5"
import { useDispatch, useSelector } from 'react-redux'
import { setShowProfile } from '../redux/profileSlice'
import { IoMdLogOut } from "react-icons/io"
import InputEdit from './profile/InputEdit'
import { updateUser } from '../apis/auth'
import { toast } from 'react-toastify'
import { setUserNameAndBio } from '../redux/activeUserSlice'
import React, { useState, useEffect } from 'react';
import { IoArrowBack } from "react-icons/io5";
import { useDispatch, useSelector } from 'react-redux';
import { setShowProfile } from '../redux/profileSlice';
import { IoMdLogOut } from "react-icons/io";
import InputEdit from './profile/InputEdit';
import { updateUser, uploadProfilePicture } from '../apis/auth';
import { toast } from 'react-toastify';
import { setUserNameAndBio } from '../redux/activeUserSlice';

function Profile(props) {
const dispatch = useDispatch()
const { showProfile } = useSelector((state) => state.profile)
const activeUser = useSelector((state) => state.activeUser)
const dispatch = useDispatch();
const { showProfile } = useSelector((state) => state.profile);
const activeUser = useSelector((state) => state.activeUser);
const [formData, setFormData] = useState({
name: activeUser.name,
bio: activeUser.bio
})
name: activeUser.name || '',
bio: activeUser.bio || '',
});
const [profilePic, setProfilePic] = useState(activeUser.profilePic || '');

useEffect(() => {
setProfilePic(activeUser.profilePic || '');
}, [activeUser.profilePic]);

const logoutUser = () => {
toast.success("Logout Successfull!")
localStorage.removeItem("userToken")
window.location.href = "/login"
}
toast.success("Logout Successful!");
localStorage.removeItem("userToken");
window.location.href = "/login";
};

const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value })
}
const submit = async () => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};

dispatch(setUserNameAndBio(formData))
toast.success("Updated!")
await updateUser(activeUser.id, formData)
const handleProfilePicChange = (e) => {
const file = e.target.files[0];
if (file) {
setProfilePic(URL.createObjectURL(file));
handleProfilePicSubmit(file);
}
};

}
const handleProfilePicSubmit = async (file) => {
const formData = new FormData();
formData.append('profilePic', file);

return (
try {
const response = await uploadProfilePicture(formData);
if (response && response.filePath) {
toast.success("Profile Picture Updated!");
dispatch(setUserNameAndBio({ profilePic: response.filePath }));
} else {
toast.error("Error uploading profile picture.");
}
} catch (error) {
toast.error("Error uploading profile picture.");
console.error("Error uploading profile picture:", error);
}
};

const submit = async () => {
try {
await updateUser(activeUser.id, formData);
dispatch(setUserNameAndBio(formData));
toast.success("Profile Updated!");
} catch (error) {
toast.error("Error updating profile.");
console.error("Error updating profile:", error);
}
};

return (
<div style={{ transition: showProfile ? "0.3s ease-in-out" : "" }} className={props.className}>
<div className='absolute w-[100%]'>
<div className='absolute w-[100%]'>
<div className='bg-[#166e48] pt-12 pb-3'>
<button onClick={() => dispatch(setShowProfile(false))} className='flex items-center'>
<IoArrowBack style={{ color: "#fff", width: "30px", height: "20px" }} />
<h6 className='text-[16px] text-[#fff] font-semibold'>Profile</h6>
</button>
</div>
<div className=' pt-5'>
<div className='pt-5'>
<div className='flex items-center flex-col'>
<img className='w-[150px] h-[150px] rounded-[100%] -ml-5' src={activeUser?.profilePic} alt="" />
<input
type="file"
id="profilePicInput"
style={{ display: 'none' }}
onChange={handleProfilePicChange}
/>
<img
className='w-[150px] h-[150px] rounded-[100%] -ml-5 cursor-pointer'
src={profilePic || activeUser.profilePic || 'default_profile_pic_url'}
alt="Profile"
onClick={() => document.getElementById('profilePicInput').click()}
/>
</div>
<InputEdit type="name" handleChange={handleChange} input={formData.name} handleSubmit={submit} />

<div>

<div className='py-5 px-4'>
<p className='text-[10px] tracking-wide text-[#3b4a54] '>
This is not your username or pin. This name will be visible to your contacts
</p>
</div>

<div className='py-5 px-4'>
<p className='text-[10px] tracking-wide text-[#3b4a54]'>
This is not your username or pin. This name will be visible to your contacts.
</p>
</div>
<InputEdit type="bio" handleChange={handleChange} input={formData.bio} handleSubmit={submit} />
</div>

<div onClick={logoutUser} className='flex items-center justify-center mt-5 cursor-pointer shadow-2xl'>
<IoMdLogOut className='text-[#e44d4d] w-[27px] h-[23px]' />
<h6 className='text-[17px] text-[#e44d4d] font-semibold'>Logout</h6>
</div>
</div>
</div>
)
);
}

export default Profile
export default Profile;
65 changes: 65 additions & 0 deletions server/controllers/user.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import user from '../models/userModel.js';
import bcrypt from 'bcryptjs';
import multer from 'multer';
import path from 'path';
import jwt from 'jsonwebtoken';
import { OAuth2Client } from 'google-auth-library';
export const register = async (req, res) => {
const { firstname, lastname, email, password } = req.body;
Expand Down Expand Up @@ -125,3 +128,65 @@ export const updateInfo = async (req, res) => {
const updatedUser = await user.findByIdAndUpdate(id, { name, bio });
return updatedUser;
};

const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`);
},
});

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

export const uploadProfilePicMiddleware = upload.single('profilePic');

export const uploadProfilePicture = async (req, res) => {
try {
if (!req.file) {
return res.status(400).send('No file uploaded');
}
const filePath = `${req.protocol}://${req.get('host')}/uploads/${req.file.filename}`;
const updatedUser = await user.findByIdAndUpdate(req.rootUserId, { profilePic: filePath }, { new: true });
res.status(200).send({ message: 'Profile picture uploaded successfully', filePath });
} catch (error) {
console.error('Error uploading profile picture:', error);
res.status(500).send({ message: 'Error uploading profile picture', error });
}
};

export const Auth = async (req, res, next) => {
try {
const authHeader = req.headers.authorization;

if (!authHeader) {
return res.status(401).json({ error: 'No token provided' });
}

const token = authHeader.split(' ')[1];

if (!token) {
return res.status(401).json({ error: 'No token provided' });
}

if (token.length < 500) {
const verifiedUser = jwt.verify(token, process.env.SECRET);
const rootUser = await user.findOne({ _id: verifiedUser.id }).select('-password');
req.token = token;
req.rootUser = rootUser;
req.rootUserId = rootUser._id;
} else {
const data = jwt.decode(token);
req.rootUserEmail = data.email;
const googleUser = await user.findOne({ email: req.rootUserEmail }).select('-password');
req.rootUser = googleUser;
req.token = token;
req.rootUserId = googleUser._id;
}
next();
} catch (error) {
console.error('Auth Middleware Error:', error);
res.status(401).json({ error: 'Invalid Token' });
}
};
18 changes: 16 additions & 2 deletions server/index.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,39 @@
import express from 'express';
import { fileURLToPath } from 'url';
import dotenv from 'dotenv/config';
import mongoDBConnect from './mongoDB/connection.js';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import cors from 'cors';
import fs from 'fs';
import path from 'path';
import userRoutes from './routes/user.js';
import chatRoutes from './routes/chat.js';
import messageRoutes from './routes/message.js';
import uploadRoutes from './routes/uploadRoutes.js';
import * as Server from 'socket.io';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const corsConfig = {
origin: process.env.BASE_URL,
credentials: true,
};
const PORT=process.env.PORT || 8000


const UPLOADS_DIR = path.join(__dirname, 'uploads');

if (!fs.existsSync(UPLOADS_DIR)) {
fs.mkdirSync(UPLOADS_DIR);
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors(corsConfig));
app.use('/', userRoutes);
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use('/', userRoutes);
app.use('/api/upload', uploadRoutes);
app.use('/api/chat', chatRoutes);
app.use('/api/message', messageRoutes);
mongoose.set('strictQuery', false);
Expand Down
Loading