232 lines
8.3 KiB
JavaScript
232 lines
8.3 KiB
JavaScript
require('dotenv').config();
|
|
const express = require('express');
|
|
const path = require('path');
|
|
const app = express();
|
|
const port = process.env.PORT || 3000;
|
|
const bodyParser = require('body-parser');
|
|
const cookieParser = require('cookie-parser');
|
|
const cors = require('cors');
|
|
const Notifications = require("./notifications");
|
|
|
|
var corsOptions = {
|
|
origin: ['http://localhost:8080', "https://social.emmint.com"],
|
|
credentials: true };
|
|
app.use(cors(corsOptions));
|
|
app.use(bodyParser.json());
|
|
app.use(bodyParser.urlencoded({ extended: true }));
|
|
app.use(cookieParser());
|
|
|
|
const bcrypt = require('bcrypt');
|
|
const crypto = require('crypto');
|
|
const DB = require("./mongoDB.js");
|
|
|
|
// Utilities
|
|
const getSessionId = function(req){
|
|
const session_id = req.cookies.session_id || req.query.session_id || req.body.session_id;
|
|
return session_id;
|
|
}
|
|
const getUserId = function(req){
|
|
const user_sid = req.cookies.user_sid || req.query.user_sid || req.body.user_sid;
|
|
return user_sid;
|
|
}
|
|
const getProfileId = function(req){
|
|
const profile_id = req.cookies.profile_id || req.query.profile_id || req.body.profile_id;
|
|
return profile_id;
|
|
}
|
|
|
|
// Definitions
|
|
const Post = require("./def/post.js")
|
|
const Profile = require("./def/profile.js");
|
|
const profileRoute = require('./routes/profile.js');
|
|
const postRoute = require('./routes/post.js');
|
|
const paymentsRoute = require('./routes/payments.js');
|
|
|
|
|
|
DB.getDB.then((DB)=>{
|
|
|
|
// middleware function to check for logged-in users
|
|
const sessionChecker = async (req, res, next) => {
|
|
const session_id = getSessionId(req);
|
|
const user_sid = getUserId(req);
|
|
const profile_id = getProfileId(req);
|
|
if (session_id && user_sid) {
|
|
const userInfo = await DB.checkSessionOnDB(session_id, user_sid);
|
|
req.userInfo = userInfo;
|
|
req.profileInfo = {_id: profile_id}
|
|
if(!userInfo) return res.redirect('/login');
|
|
next();
|
|
} else {
|
|
return res.redirect('/login');
|
|
}
|
|
};
|
|
|
|
// route for Home-Page
|
|
app.get('/', sessionChecker, async (req, res) => {
|
|
if(req.userInfo) return res.json({
|
|
status: "ok",
|
|
userInfo: req.userInfo,
|
|
profileInfo:req.profileInfo
|
|
});
|
|
res.json({status: "ok"});
|
|
});
|
|
|
|
// route for user signup
|
|
const signup = async function(req, res){
|
|
const username = req.query.username || req.body.username;
|
|
const password = req.query.password || req.body.password;
|
|
const email = req.query.email || req.body.email;
|
|
const profile = req.query.profile || req.body.profile;
|
|
if(!username || !password || !email) return res.json({status: "fail"});
|
|
//Check if the new user has an invitation
|
|
if(!await DB.getInvitation(email)) return res.json({status: "Not invitation found!"});
|
|
//const hashedPassword = await bcrypt.hash(password, 10);
|
|
const hashedPassword = await bcrypt.hash(password, 10);
|
|
const response = await DB.newUser({
|
|
username: username.toLowerCase(),
|
|
email: email.toLowerCase(),
|
|
password: hashedPassword
|
|
});
|
|
if(!response.toLowerCase){
|
|
let user = {
|
|
userid: response.insertedId,
|
|
profile: profile,
|
|
}
|
|
const userObj = new Profile(user);
|
|
await DB.newProfile(userObj);
|
|
return await login(req, res);
|
|
}
|
|
return res.json({status: response})
|
|
}
|
|
app.route('/signup').get(async (req, res) => {
|
|
return await signup(req, res);
|
|
}).post(async (req, res) => {
|
|
return await signup(req, res);
|
|
});
|
|
|
|
const cookiesOptions = {
|
|
maxAge: 1000 * 60 * 60 * 24 * 30, // would expire after 30 days
|
|
httpOnly: true, // The cookie only accessible by the web server
|
|
//signed: true // Indicates if the cookie should be signed
|
|
sameSite: 'none', // This and secure are required for properly
|
|
secure: true, // manage cockies in cros-domain
|
|
};
|
|
|
|
// route for user Login
|
|
const login = async function(req, res){
|
|
const session_id = getSessionId(req);
|
|
const user_sid = getUserId(req);
|
|
if (session_id && user_sid) {
|
|
const userInfo = await DB.checkSessionOnDB(session_id, user_sid);
|
|
if(userInfo) return res.redirect('/');
|
|
}
|
|
const username = req.body.username || req.query.username;
|
|
const password = req.body.password || req.query.password || "";
|
|
const user = await DB.getUser(username);
|
|
if (!user) return res.json({status: "user not founded"});
|
|
const samePass = await bcrypt.compare(password, user.password);
|
|
if(!samePass) return res.json({status: "incorrect password"});
|
|
const doc = await DB.newSession(user._id);
|
|
res.cookie('user_sid', user._id, cookiesOptions);
|
|
res.cookie('session_id', doc.insertedId, cookiesOptions);
|
|
//Chooses the most recent update profile
|
|
const latestProfile = await DB.latestProfile(user._id);
|
|
res.cookie('profile_id', latestProfile._id, cookiesOptions);
|
|
return res.json({
|
|
status: "ok",
|
|
user_sid: user._id,
|
|
session_id: doc.insertedId,
|
|
profile_id: latestProfile._id
|
|
});
|
|
}
|
|
app.route('/login').get(async (req, res) => {
|
|
return await login(req, res);
|
|
}).post(async (req, res) => {
|
|
return await login(req, res);
|
|
});
|
|
|
|
function generatePassword() {
|
|
var length = 8,
|
|
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
|
|
retVal = "";
|
|
for (var i = 0, n = charset.length; i < length; ++i) {
|
|
retVal += charset.charAt(Math.floor(Math.random() * n));
|
|
}
|
|
return retVal;
|
|
}
|
|
|
|
app.route('/resetPassword').post(async (req, res) => {
|
|
const session_id = getSessionId(req);
|
|
const user_sid = getUserId(req);
|
|
if (session_id && user_sid) {
|
|
const userInfo = await DB.checkSessionOnDB(session_id, user_sid);
|
|
if(userInfo) return res.redirect('/');
|
|
}
|
|
const username = req.body.username;
|
|
const user = await DB.getUser(username);
|
|
if (!user) return res.json({status: "user not founded"});
|
|
const password = generatePassword();
|
|
const hashedPassword = await bcrypt.hash(password, 10);
|
|
DB.resetUserPassword(username, hashedPassword);
|
|
//We need to limit this to every 2 hours or something like this.
|
|
Notifications.sendEmail(username, "Your new credentials",
|
|
`
|
|
<p> Hello,</p>
|
|
<p> This is your new password: ${password}</p>
|
|
<p><a href="https://social.emmint.com/">Log in</a></p>
|
|
<p>Blessings</p>
|
|
<p>Emmanuel International Ministries</p>
|
|
`)
|
|
return res.json({
|
|
status: "ok",
|
|
details: 'Check your email for new password'
|
|
});
|
|
});
|
|
|
|
app.post('/changeProfile', sessionChecker, async (req, res) => {
|
|
const user_sid = getUserId(req);
|
|
let profile = await DB.getProfile(req.body.profileid);
|
|
if(!profile || profile.userid != user_sid) return res.json({
|
|
status: "profile does not belong to the logged user",
|
|
});
|
|
res.cookie('profile_id', profile._id, cookiesOptions);
|
|
return res.json({
|
|
status: "ok",
|
|
...profile
|
|
});
|
|
});
|
|
|
|
// route for user logout
|
|
const logout = function(req, res){
|
|
const session_id = getSessionId(req);
|
|
const user_sid = getUserId(req);
|
|
if (session_id && user_sid) {
|
|
res.clearCookie('session_id');
|
|
res.clearCookie('user_sid');
|
|
//remove from DB
|
|
DB.removeSession(session_id);
|
|
res.redirect('/');
|
|
} else {
|
|
res.redirect('/login');
|
|
}
|
|
}
|
|
app.get('/logout', (req, res) => {
|
|
return logout(req, res);
|
|
});
|
|
|
|
app.use('/user', sessionChecker, profileRoute);
|
|
app.use('/post', sessionChecker, postRoute);
|
|
app.use('/payments', sessionChecker, paymentsRoute);
|
|
|
|
// route for handling 404 requests(unavailable routes)
|
|
app.use(function (req, res, next) {
|
|
res.status(404).send("Sorry can't find that!")
|
|
});
|
|
|
|
app.listen(port, () => {
|
|
console.log(`Example app listening at http://localhost:${port}`);
|
|
});
|
|
}).catch((err)=>{
|
|
throw err;
|
|
});
|
|
|