0% found this document useful (0 votes)
3 views

Code-report

The document contains a series of JavaScript modules for a MongoDB application, defining database connections and models for users, chats, followers, blogs, and comments. It also includes an API for user authentication, email verification, and real-time socket communication for messaging. Additionally, utility functions for sending OTPs and managing JWT tokens are provided to enhance security and user management.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Code-report

The document contains a series of JavaScript modules for a MongoDB application, defining database connections and models for users, chats, followers, blogs, and comments. It also includes an API for user authentication, email verification, and real-time socket communication for messaging. Additionally, utility functions for sending OTPs and managing JWT tokens are provided to enhance security and user management.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

// Coder-Channel/mongo/dbConnect.

js
import mongoose from "mongoose";
mongoose.set('strictPopulate', false); // Disable strict populate globally

export default function dbConnect() {


if(mongoose.connection.readyState >= 1) {
return ;
}

mongoose.connect(process.env.MONGO_URL);
}

// Coder-Channel/mongo/UserModel.js
import mongoose from "mongoose";
import dbConnect from "./dbConnect";

dbConnect();
const userSchema = new mongoose.Schema({ //data model
name:{
type:String,
required:[true , 'Please enter user name'],
},
email:{
type:String,
unique:[true , "This email is already registered!"],
required:[true , "Please enter your email"]
},
password:{
type:String,
required:[true , 'Please enter your password'],
},
gender:{
type:String,
required:[true , "Please enter your gender"],
enum: {
values:[
"male",
"female",
"others"
],
message:"Please select correct gender",
}
},
university:{
type:String,
},
course:{
type:String,
},
verify:{
type:Boolean,
default:false,
},
imgUrl:{
type:String,
default:"/img/profileImg.jpg",
},
linkedIn: {
type:String,
default:"",
},
instagram: {
type:String,
default:"",
},
github: {
type:String,
default:"",
},
createdAt: {
type:Date,
default:Date.now,
}
});

export default mongoose.models.Users || mongoose.model("Users" , userSchema); // constructor

// Coder-Channel/mongo/ChatModel.js
import mongoose from "mongoose";
import dbConnect from './dbConnect'

dbConnect();
const chatSchema = new mongoose.Schema({
senderId:{
type:mongoose.Schema.Types.ObjectId,
required:[true , "sender-id is missing."],
ref:"Users",
},
receiverId:{
type:mongoose.Schema.Types.ObjectId,
required:[true , "sender-id is missing."],
ref:"Users",
},
message:{
type:String,
required:[true , "chat-message is missing."],
},
createdAt: {
type:Date,
default:Date.now,
}
});

export const Chat = mongoose.models.Chats || mongoose.model("Chats" , chatSchema);

// Coder-Channel/mongo/FollowersModel.js
import mongoose from "mongoose";
import dbConnect from "./dbConnect";

dbConnect();
const followerSchema = new mongoose.Schema({
followedById:{
type:mongoose.Schema.Types.ObjectId,
required:[true , 'Please enter follower-id'],
ref:"Users",
},
followedToId:{
type:mongoose.Schema.Types.ObjectId,
required:[true , "Please enter the user-id"],
ref:"Users",
},
});

export default mongoose.models.Follower || mongoose.model("Follower" , followerSchema);

// Coder-Channel/mongo/BlogModel.js
import mongoose from "mongoose";
import dbConnect from "./dbConnect";

dbConnect();
const blogSchema = new mongoose.Schema({
writerId:{
type:mongoose.Schema.Types.ObjectId,
required:[true , "Writer id is missing"],
ref:"Users",
},
blog:{
type:String,
required:[true , "There is no blog found!"],
},
image:{
type:String,
},
likes: {
type:Number,
default:0,
},
time:{
type:Date,
default:Date.now,
}
})

export default mongoose.models.Blogs || mongoose.model("Blogs" , blogSchema);

// Coder-Channel/mongo/CommentModel.js
import mongoose from "mongoose";
import dbConnect from "./dbConnect";

dbConnect();
const commentSchema = new mongoose.Schema({
comment:{
type:String,
required:true,
},
commentToId:{
type:mongoose.Schema.Types.ObjectId,
required:true,
ref:"Blogs",
},
commentById:{
type:mongoose.Schema.Types.ObjectId,
required:true,
ref:"Users",
},
commentedAt: {
type:Date,
default:Date.now,
}
})

export const Comment = mongoose.models.Comments || mongoose.model("Comments" , commentSchema);

// Coder-Channel/src/pages/api/socket.js
import { Server } from "socket.io";
let map = new Map();
let existingUsers = new Set();

export default async function SocketHandler(req, res) {


if (!res.socket.server.io) {
const io = new Server(res.socket.server, {
path: "/api/socket_io",
addTrailingSlash: false,
});
res.socket.server.io = io;

io.on("connection", (socket) => {


socket.on('new-user', async ({ name, _id }) => {
socket.join(_id);
existingUsers.add(_id);
map.set(socket.id, _id);
const room = io.sockets.adapter.rooms.get(_id);
if (room.size === 1) {
socket.broadcast.emit('newUserInGroup', name);
socket.broadcast.emit("online-status", { _id, status: true })
}
socket.emit("existingOnline", Array.from(existingUsers));
});

socket.on('loadOnlineUsers', _id => {


socket.emit("existingOnline", Array.from(existingUsers));
});

socket.on('sendPersonalMessage', data => {


socket.to(data.receiverId).emit('receivePersonalMessage', data);
});

socket.on('sendPersonalMessage', data => {


socket.to(data.receiverId).emit('receivePersonalMessage', data);
});

socket.on('logout', async (_id) => {


socket.to(_id).emit('refresh');
});

socket.on('disconnect', async () => {


const _id = map.get(socket.id);
const room = io.sockets.adapter.rooms.get(_id);
if (!room || room.size === 0) {
existingUsers.delete(_id);
socket.broadcast.emit("online-status", { _id, status: false });
// socket.broadcast.emit('userLeftGroup', { _id });
}
map.delete(socket.id);
});
});
}
res.end();
}

// Coder-Channel/src/app/api/users/route.js
import cron from 'node-cron';
import cryptoJS from 'crypto-js'
import Users from "/mongo/UserModel";
import { NextResponse } from "next/server";
import { sendOTP } from '@/utilities/sendOTP';
import { verifyOPT } from '@/utilities/verifyOTP';
import { setJWTUser } from '@/utilities/getJWTUser';
import { sendVerificationEmail } from '@/utilities/sendVerificationMailToUser';

export async function GET() {


try {
let users = await Users.find({ verify: true });
return NextResponse.json({ users, success: true });
} catch (err) {
return NextResponse.json({ success: false });
}
}

export async function POST(req) {


try {
let { name, email, password, gender } = await req.json();
password = cryptoJS.AES.encrypt(password, email).toString(); // Encrypt a password
const user = new Users({ name , email , gender, password });
await user.save();
const origin = `http://${req.headers.get('x-forwarded-host') || req.headers.get('host') || '13.201.44.241/'}`;
await sendVerificationEmail(email, user._id, origin);
return NextResponse.json({ message: "Verification Link sent successfully to your Email...! It will be valid only for 10 minutes, If you fails to verify within the tim
} catch (error) {
// console.error(error);
return NextResponse.json({ error: 'Error during file upload: ' + error.message }, { status: 500 });
}
}

export async function PUT(req) {


try {
let data = await req.json();
let { email, password, OTP } = data;

if (!email || !password) {
return NextResponse.json({ message: "bad request! Missing credentials.", success: false });
}

let User = (await Users.findOne({ email })).toObject();


let bytes = cryptoJS.AES.decrypt(User.password, email);
let pass = bytes.toString(cryptoJS.enc.Utf8);

if (!User || password !== pass) {


return NextResponse.json({ message: "wrong credentials, Try again...!", success: false });
} else if (!User.verify) {
return NextResponse.json({ message: "email verification required...!", success: false });
}

if (!OTP) {
sendOTP({ email });
return NextResponse.json({ message: "OTP is sent to your email", success: true });
}
const otpVerified = verifyOPT({ email, OTP });
if (!otpVerified) {
return NextResponse.json({ message: "wrong OTP, Try again...!", success: false });
}

delete User.password;
setJWTUser(User);

return NextResponse.json({ User, success: true, message: `You credentials are right and you have Logged-in...!` })
} catch (error) {
// console.log(error.message);
return NextResponse.json({ message: "bad request, Try again...!", success: false });
}
}

cron.schedule('*/10 * * * *', async () => {


try {
const now = new Date();
await Users.deleteMany({
verify: false,
createdAt: { $lt: new Date(now - 10 * 60 * 1000) }
});
// console.log('Deleting unverified users registered more than 10 minutes ago');
} catch (error) {
console.error('Error deleting unverified users:', error.message);
}
});

// Coder-Channel/src/utilities/sendOTP.js
import speakeasy from "speakeasy"
import nodemailer from "nodemailer"

export const sendOTP = async({ email }) => {


const OTP = createOTP(email)
await sendOTP2MAIL(email , OTP);
}

const createOTP = (secret) => {


const OTP = speakeasy.totp({
secret,
encoding:"base32",
step:300, // OTP is valid for 5 minutes(300 secs)
digits:6,
algorithm:"sha1",
})
return OTP;
}

const transporter = nodemailer.createTransport({


service: "gmail",
auth: {
user: process.env.USER_EMAIL,
pass: process.env.E_PASS,
},
});

export async function sendOTP2MAIL(email, OTP) {


const mailOptions = {
from: process.env.USER_EMAIL,
to: email,
subject: "Email Verification",
text: `Your Login OTP.`,
html: `<p>Hi,</p>
<p>Please don't share your OTP to anyone</p>
<h2> ${OTP} </h2>
`
};
return transporter.sendMail(mailOptions);
}

// Coder-Channel/src/utilities/verifyOTP.js
import { totp } from "speakeasy";

export const verifyOPT = ({ email , OTP }) => {


const verified = totp.verify({
secret: email,
encoding: 'base32',
token: OTP,
step: 300, // Must match the step used during generation
window: 1, // Allow 1 step before and after
digits: 6,
algorithm: 'sha1',
});
return verified;
}

// Coder-Channel/src/utilities/getJWTUser.js
import { cookies } from "next/headers";
import { CODER_CHANNEL_TOCKEN, TOCKEN_MAX_AGE } from "./constants";
import { sign, verify } from "jsonwebtoken";

export const getJWTUser = () => {


try {
const tocken = cookies().get(CODER_CHANNEL_TOCKEN)?.value;
const secret = process.env.JWT_SECRET_KEY || "";
const { User } = verify(tocken, secret);
return User;
} catch (error) {
return null;
}
}

export const setJWTUser = (User) => {


const secret = process.env.JWT_SECRET_KEY || "";
const tocken = sign({ User }, secret, { expiresIn: TOCKEN_MAX_AGE });
cookies().set({
name: CODER_CHANNEL_TOCKEN,
value: tocken,
// secure: process.env.NODE_ENV === 'production' && window.location.protocol === 'https:',
httpOnly: true,
// sameSite: "strict",
maxAge: TOCKEN_MAX_AGE,
path: "/"
});
}

You might also like