initial commit, authentication
This commit is contained in:
232
.gitignore
vendored
Normal file
232
.gitignore
vendored
Normal file
@@ -0,0 +1,232 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# Snowpack dependency directory (https://snowpack.dev/)
|
||||
web_modules/
|
||||
|
||||
# TypeScript cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Microbundle cache
|
||||
.rpt2_cache/
|
||||
.rts2_cache_cjs/
|
||||
.rts2_cache_es/
|
||||
.rts2_cache_umd/
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variables file
|
||||
.env
|
||||
.env.test
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
.parcel-cache
|
||||
|
||||
# Next.js build output
|
||||
.next
|
||||
out
|
||||
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
dist
|
||||
|
||||
# Gatsby files
|
||||
.cache/
|
||||
# Comment in the public line in if your project uses Gatsby and not Next.js
|
||||
# https://nextjs.org/blog/next-9-1#public-directory-support
|
||||
# public
|
||||
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
# DynamoDB Local files
|
||||
.dynamodb/
|
||||
|
||||
# TernJS port file
|
||||
.tern-port
|
||||
|
||||
# Stores VSCode versions used for testing VSCode extensions
|
||||
.vscode-test
|
||||
|
||||
# yarn v2
|
||||
.yarn/cache
|
||||
.yarn/unplugged
|
||||
.yarn/build-state.yml
|
||||
.yarn/install-state.gz
|
||||
.pnp.*
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# Snowpack dependency directory (https://snowpack.dev/)
|
||||
web_modules/
|
||||
|
||||
# TypeScript cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Microbundle cache
|
||||
.rpt2_cache/
|
||||
.rts2_cache_cjs/
|
||||
.rts2_cache_es/
|
||||
.rts2_cache_umd/
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variables file
|
||||
.env
|
||||
.env.test
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
.parcel-cache
|
||||
|
||||
# Next.js build output
|
||||
.next
|
||||
out
|
||||
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
dist
|
||||
|
||||
# Gatsby files
|
||||
.cache/
|
||||
# Comment in the public line in if your project uses Gatsby and not Next.js
|
||||
# https://nextjs.org/blog/next-9-1#public-directory-support
|
||||
# public
|
||||
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
# DynamoDB Local files
|
||||
.dynamodb/
|
||||
|
||||
# TernJS port file
|
||||
.tern-port
|
||||
|
||||
# Stores VSCode versions used for testing VSCode extensions
|
||||
.vscode-test
|
||||
|
||||
# yarn v2
|
||||
.yarn/cache
|
||||
.yarn/unplugged
|
||||
.yarn/build-state.yml
|
||||
.yarn/install-state.gz
|
||||
.pnp.*
|
||||
136
index.js
Normal file
136
index.js
Normal file
@@ -0,0 +1,136 @@
|
||||
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');
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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);
|
||||
if (session_id && user_sid) {
|
||||
const userInfo = await DB.checkSessionOnDB(session_id, user_sid);
|
||||
req.userInfo = userInfo;
|
||||
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});
|
||||
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;
|
||||
if(!username || !password || !email) return res.json({status: "fail"})
|
||||
const hashedPassword = await bcrypt.hash(password, 10);
|
||||
const success = await DB.newUser({
|
||||
username: username,
|
||||
email: email,
|
||||
password: hashedPassword
|
||||
});
|
||||
if(success){
|
||||
return login(req, res);
|
||||
}
|
||||
res.redirect('/signup');
|
||||
}
|
||||
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
|
||||
};
|
||||
|
||||
// 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);
|
||||
return res.json({
|
||||
status: "ok",
|
||||
user_sid: user._id,
|
||||
session_id: doc.insertedId
|
||||
});
|
||||
}
|
||||
app.route('/login').get(async (req, res) => {
|
||||
return await login(req, res);
|
||||
}).post(async (req, res) => {
|
||||
return await login(req, res);
|
||||
});
|
||||
|
||||
// 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);
|
||||
});
|
||||
|
||||
// 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;
|
||||
});
|
||||
|
||||
54
mongoDB.js
Normal file
54
mongoDB.js
Normal file
@@ -0,0 +1,54 @@
|
||||
const mongo = require('mongodb');
|
||||
const MongoClient = mongo.MongoClient;
|
||||
const DBName = "EMI_SOCIAL";
|
||||
const mongoUrl = process.env.MONGO_URL
|
||||
|
||||
|
||||
const getDB = new Promise((resolve, reject) => {
|
||||
const DB = {ObjectID: mongo.ObjectID};
|
||||
MongoClient.connect(mongoUrl, function(err, db) {
|
||||
if (err) return reject(err);
|
||||
|
||||
DB.db = db;
|
||||
console.log("Connected to DB!");
|
||||
DB.usersCol = db.db(DBName).collection("users");
|
||||
DB.tokensCol = db.db(DBName).collection("AmArr5EHx7sn3Gr");
|
||||
|
||||
DB.checkSessionOnDB = async (session_id, user_sid)=>{
|
||||
const temp_id = new mongo.ObjectID(session_id);
|
||||
//We can add cache, like a temporary Redis entry, to avoid calling the DB on each call
|
||||
const doc = await DB.tokensCol.findOne({"_id":temp_id});
|
||||
if(doc && doc.uid == user_sid){
|
||||
const userMongoId = new mongo.ObjectID(user_sid);
|
||||
const userInfo = await DB.usersCol.findOne({"_id": userMongoId}, {fields: {password: 0}});
|
||||
return userInfo;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
DB.getUser = (username)=>{
|
||||
return DB.usersCol.findOne({ username: username });
|
||||
}
|
||||
|
||||
DB.newUser = (userInformation)=>{
|
||||
console.log("NewUser", userInformation);
|
||||
return DB.usersCol.insertOne(userInformation).catch((err)=>{
|
||||
console.log(err);
|
||||
return false;
|
||||
});
|
||||
};
|
||||
|
||||
DB.newSession = (user_id)=>{
|
||||
return DB.tokensCol.insertOne({uid: user_id});
|
||||
}
|
||||
|
||||
DB.removeSession = (session_id)=>{
|
||||
const temp_id = new mongo.ObjectID(session_id);
|
||||
return DB.tokensCol.deleteOne({"_id":temp_id});
|
||||
}
|
||||
|
||||
resolve(DB);
|
||||
});
|
||||
});
|
||||
|
||||
exports.getDB = getDB;
|
||||
2023
package-lock.json
generated
Normal file
2023
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
19
package.json
Normal file
19
package.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "emi_backend",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"bcrypt": "^5.0.0",
|
||||
"body-parser": "^1.19.0",
|
||||
"cookie-parser": "^1.4.5",
|
||||
"dotenv": "^8.2.0",
|
||||
"express": "^4.17.1",
|
||||
"mongodb": "^3.6.3"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user