init commit
This commit is contained in:
112
server/middlewares/TRON.js
Executable file
112
server/middlewares/TRON.js
Executable file
@@ -0,0 +1,112 @@
|
||||
"use strict";
|
||||
exports.__esModule = true;
|
||||
exports.TRONTransferFrom = exports.validateByTXId = void 0;
|
||||
var tronWeb = require("tronweb");
|
||||
var currencies_1 = require("../db/currencies");
|
||||
var user_1 = require("../db/user");
|
||||
var _ = require("lodash");
|
||||
// export function TRONTransferTo(userId, systemAccount, userAccount, privateKey, amount){
|
||||
// User.findOne({ _id : userId })
|
||||
// .then((user) => {
|
||||
// if(user && user._id.toString() === userId.toString()){
|
||||
// const HttpProvider = tronWeb.providers.HttpProvider;
|
||||
// const fullNode = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
// const solidityNode = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
// const eventServer = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
// const tw = new tronWeb(fullNode,solidityNode,eventServer,privateKey);
|
||||
// const am = amount * 1000000
|
||||
// tw.trx.getAccount(userAccount.toString()).then((usrAcc) =>{
|
||||
// if(usrAcc){
|
||||
// tw.trx.sendTransaction(systemAccount, am)
|
||||
// }else{
|
||||
// const error = "user Tron Account not fount"
|
||||
// console.log("Error in TRONTransferTo : ", error)
|
||||
// }
|
||||
// })
|
||||
// .catch((err) => console.log(err))
|
||||
// }else{
|
||||
// const error = 'user not fount'
|
||||
// console.log('Error in TRONTransferTo : ', error)
|
||||
// }
|
||||
// })
|
||||
// .catch((err) => console.log('Error in TRONTransferTo : ', err))
|
||||
// }
|
||||
function validateByTXId(userId, hash) {
|
||||
var systemPrivateKey = '4a8f251556d19ab6625c0cc012a3c534bf978e6a099d0bb8f42d6539579a10c5';
|
||||
user_1.User.findOne({ _id: userId })
|
||||
.then(function (user) {
|
||||
if (user && user._id.toString() === userId.toString()) {
|
||||
var HttpProvider = tronWeb.providers.HttpProvider;
|
||||
var fullNode = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
var solidityNode = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
var eventServer = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
var TronWeb = new tronWeb(fullNode, solidityNode, eventServer, systemPrivateKey);
|
||||
console.log("here : ", TronWeb);
|
||||
TronWeb.trx.getTransaction(hash.toString())
|
||||
.then(function (transaction) {
|
||||
return transaction;
|
||||
})["catch"](function (err) { throw (err); });
|
||||
}
|
||||
else {
|
||||
var error = 'user not fount';
|
||||
console.log('Error in TRONTransferTo : ', error);
|
||||
throw (error);
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.validateByTXId = validateByTXId;
|
||||
function TRONTransferFrom(userId, destAccount, am) {
|
||||
var systemPrivateKey = '4a8f251556d19ab6625c0cc012a3c534bf978e6a099d0bb8f42d6539579a10c5';
|
||||
var tronId = undefined;
|
||||
var amount = am * 1000000;
|
||||
currencies_1.Currencies.findOne({ name: "TRON" })
|
||||
.then(function (curTRONObj) {
|
||||
tronId = curTRONObj._id;
|
||||
user_1.User.findOne({ _id: userId })
|
||||
.then(function (user) {
|
||||
if (user && user._id.toString() === userId.toString()) {
|
||||
var userTronWal_1 = _.find(user.wallet, function (e) { return e.currency.toString() === tronId.toString(); });
|
||||
if (userTronWal_1.value >= am) {
|
||||
var HttpProvider = tronWeb.providers.HttpProvider;
|
||||
var fullNode = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
var solidityNode = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
var eventServer = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
var TronWeb = new tronWeb(fullNode, solidityNode, eventServer, systemPrivateKey);
|
||||
TronWeb.trx.sendTransaction(destAccount, amount)
|
||||
.then(function (transaction) {
|
||||
if (transaction.result) {
|
||||
userTronWal_1.value = userTronWal_1.value - am;
|
||||
user.save();
|
||||
console.log("Transaction to destination account done. ");
|
||||
}
|
||||
else {
|
||||
var error = "Transaciton Failed";
|
||||
console.log(error);
|
||||
throw (error);
|
||||
}
|
||||
})["catch"](function (err) {
|
||||
console.log("Error : ", err);
|
||||
throw (err);
|
||||
});
|
||||
}
|
||||
else {
|
||||
var error = "user does not have enough TRON currency in his/her wallet";
|
||||
console.log(error);
|
||||
throw (error);
|
||||
}
|
||||
}
|
||||
else {
|
||||
var error = 'user not fount';
|
||||
console.log('Error in TRONTransferTo : ', error);
|
||||
throw (error);
|
||||
}
|
||||
})["catch"](function (err) {
|
||||
console.log('Error in TRONTransferTo : ', err);
|
||||
throw (err);
|
||||
});
|
||||
})["catch"](function (err) {
|
||||
console.log(err);
|
||||
throw (err);
|
||||
});
|
||||
}
|
||||
exports.TRONTransferFrom = TRONTransferFrom;
|
||||
132
server/middlewares/TRON.ts
Executable file
132
server/middlewares/TRON.ts
Executable file
@@ -0,0 +1,132 @@
|
||||
import * as tronWeb from 'tronweb'
|
||||
import { Currencies } from '../db/currencies';
|
||||
import { User } from '../db/user'
|
||||
import * as _ from 'lodash'
|
||||
|
||||
// export function TRONTransferTo(userId, systemAccount, userAccount, privateKey, amount){
|
||||
|
||||
// User.findOne({ _id : userId })
|
||||
// .then((user) => {
|
||||
|
||||
// if(user && user._id.toString() === userId.toString()){
|
||||
// const HttpProvider = tronWeb.providers.HttpProvider;
|
||||
// const fullNode = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
// const solidityNode = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
// const eventServer = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
// const tw = new tronWeb(fullNode,solidityNode,eventServer,privateKey);
|
||||
// const am = amount * 1000000
|
||||
// tw.trx.getAccount(userAccount.toString()).then((usrAcc) =>{
|
||||
// if(usrAcc){
|
||||
// tw.trx.sendTransaction(systemAccount, am)
|
||||
|
||||
// }else{
|
||||
// const error = "user Tron Account not fount"
|
||||
// console.log("Error in TRONTransferTo : ", error)
|
||||
// }
|
||||
|
||||
// })
|
||||
// .catch((err) => console.log(err))
|
||||
|
||||
|
||||
// }else{
|
||||
// const error = 'user not fount'
|
||||
// console.log('Error in TRONTransferTo : ', error)
|
||||
// }
|
||||
|
||||
// })
|
||||
// .catch((err) => console.log('Error in TRONTransferTo : ', err))
|
||||
|
||||
// }
|
||||
|
||||
export function validateByTXId(userId, hash){
|
||||
const systemPrivateKey = '4a8f251556d19ab6625c0cc012a3c534bf978e6a099d0bb8f42d6539579a10c5'
|
||||
User.findOne({ _id : userId })
|
||||
.then((user) => {
|
||||
if(user && user._id.toString() === userId.toString()){
|
||||
|
||||
const HttpProvider = tronWeb.providers.HttpProvider;
|
||||
const fullNode = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
const solidityNode = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
const eventServer = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
const TronWeb = new tronWeb(fullNode,solidityNode,eventServer,systemPrivateKey);
|
||||
console.log("here : ", TronWeb)
|
||||
TronWeb.trx.getTransaction(hash.toString())
|
||||
.then((transaction) => {
|
||||
return transaction
|
||||
})
|
||||
.catch((err) => {throw(err)})
|
||||
|
||||
}else{
|
||||
const error = 'user not fount'
|
||||
console.log('Error in TRONTransferTo : ', error)
|
||||
throw(error)
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
|
||||
export function TRONTransferFrom(userId, destAccount, am){
|
||||
const systemPrivateKey = '4a8f251556d19ab6625c0cc012a3c534bf978e6a099d0bb8f42d6539579a10c5'
|
||||
let tronId = undefined
|
||||
const amount = am * 1000000
|
||||
|
||||
Currencies.findOne({name : "TRON"})
|
||||
.then((curTRONObj) => {
|
||||
tronId = curTRONObj._id
|
||||
User.findOne({ _id : userId })
|
||||
.then((user) => {
|
||||
if(user && user._id.toString() === userId.toString()){
|
||||
|
||||
let userTronWal = _.find(user.wallet, (e) => e.currency.toString() === tronId.toString())
|
||||
if(userTronWal.value >= am){
|
||||
|
||||
const HttpProvider = tronWeb.providers.HttpProvider;
|
||||
const fullNode = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
const solidityNode = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
const eventServer = new HttpProvider("https://api.shasta.trongrid.io");
|
||||
const TronWeb = new tronWeb(fullNode,solidityNode,eventServer,systemPrivateKey);
|
||||
TronWeb.trx.sendTransaction(destAccount, amount)
|
||||
.then((transaction) => {
|
||||
|
||||
if(transaction.result){
|
||||
|
||||
userTronWal.value = userTronWal.value - am
|
||||
user.save()
|
||||
console.log("Transaction to destination account done. ")
|
||||
|
||||
}else{
|
||||
const error = "Transaciton Failed"
|
||||
console.log(error)
|
||||
throw(error)
|
||||
}
|
||||
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log("Error : ", err)
|
||||
throw(err)
|
||||
})
|
||||
|
||||
}else{
|
||||
const error = "user does not have enough TRON currency in his/her wallet"
|
||||
console.log(error)
|
||||
throw(error)
|
||||
}
|
||||
|
||||
}else{
|
||||
const error = 'user not fount'
|
||||
console.log('Error in TRONTransferTo : ', error)
|
||||
throw(error)
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log('Error in TRONTransferTo : ', err)
|
||||
throw(err)
|
||||
})
|
||||
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(err)
|
||||
throw(err)
|
||||
})
|
||||
}
|
||||
24
server/middlewares/auth.js
Executable file
24
server/middlewares/auth.js
Executable file
@@ -0,0 +1,24 @@
|
||||
"use strict";
|
||||
exports.__esModule = true;
|
||||
exports.isAdmin = exports.isAuthorized = void 0;
|
||||
var myError_1 = require("../api/myError");
|
||||
function isAuthorized(req, res, next) {
|
||||
if (!req.session.userId) {
|
||||
var error = new myError_1["default"]('unauthorized cookie', 401, 1, 'خطا رخ داد!', 'لطفا برای ادامه لاگین کنید!');
|
||||
next(error);
|
||||
}
|
||||
else {
|
||||
next();
|
||||
}
|
||||
}
|
||||
exports.isAuthorized = isAuthorized;
|
||||
function isAdmin(req, res, next) {
|
||||
if (!req.session.adminId) {
|
||||
var error = new myError_1["default"]('unauthorized', 401, 3, 'خطا رخ داد!', 'شما اجازه دسترسی ندارید!');
|
||||
next(error);
|
||||
}
|
||||
else {
|
||||
next();
|
||||
}
|
||||
}
|
||||
exports.isAdmin = isAdmin;
|
||||
31
server/middlewares/auth.ts
Executable file
31
server/middlewares/auth.ts
Executable file
@@ -0,0 +1,31 @@
|
||||
import myError from '../api/myError'
|
||||
|
||||
export function isAuthorized (req, res, next) {
|
||||
if (!req.session.userId) {
|
||||
const error = new myError(
|
||||
'unauthorized cookie',
|
||||
401,
|
||||
1,
|
||||
'خطا رخ داد!',
|
||||
'لطفا برای ادامه لاگین کنید!'
|
||||
)
|
||||
next(error)
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
}
|
||||
|
||||
export function isAdmin (req, res, next) {
|
||||
if (!req.session.adminId) {
|
||||
const error = new myError(
|
||||
'unauthorized',
|
||||
401,
|
||||
3,
|
||||
'خطا رخ داد!',
|
||||
'شما اجازه دسترسی ندارید!'
|
||||
)
|
||||
next(error)
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
}
|
||||
33
server/middlewares/errorHandler.js
Executable file
33
server/middlewares/errorHandler.js
Executable file
@@ -0,0 +1,33 @@
|
||||
"use strict";
|
||||
exports.__esModule = true;
|
||||
var logger_1 = require("../api/logger");
|
||||
exports["default"] = (function (err, req, res, next) {
|
||||
if (err.statusCode) {
|
||||
logger_1.logger.warn(err.statusCode + ' - ' + err.messageEnglish);
|
||||
}
|
||||
else {
|
||||
logger_1.logger.warn(err);
|
||||
}
|
||||
if (!err.statusCode) {
|
||||
logger_1.logger.error(err.stack);
|
||||
res.status(500).json({
|
||||
actionName: 'Intrnal Error',
|
||||
metaData: {
|
||||
title: 'خطا در سرور',
|
||||
message: 'لطفا لحظاتی بعد دوباره اقدام کنید.',
|
||||
messageEnglish: 'something bad happened!'
|
||||
}
|
||||
});
|
||||
}
|
||||
else {
|
||||
res.status(err.statusCode).send({
|
||||
actionName: 'Error',
|
||||
metaData: {
|
||||
title: err.title,
|
||||
clientErrorCode: err.clientCode,
|
||||
message: err.clientMessage,
|
||||
messageEnglish: err.messageEnglish
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
29
server/middlewares/errorHandler.ts
Executable file
29
server/middlewares/errorHandler.ts
Executable file
@@ -0,0 +1,29 @@
|
||||
import { logger } from '../api/logger'
|
||||
export default (err, req, res, next) => {
|
||||
if(err.statusCode) {
|
||||
logger.warn(err.statusCode + ' - ' + err.messageEnglish)
|
||||
} else {
|
||||
logger.warn(err)
|
||||
}
|
||||
if (!err.statusCode) {
|
||||
logger.error(err.stack)
|
||||
res.status(500).json({
|
||||
actionName: 'Intrnal Error',
|
||||
metaData: {
|
||||
title: 'خطا در سرور',
|
||||
message: 'لطفا لحظاتی بعد دوباره اقدام کنید.',
|
||||
messageEnglish: 'something bad happened!'
|
||||
}
|
||||
})
|
||||
} else {
|
||||
res.status(err.statusCode).send({
|
||||
actionName: 'Error',
|
||||
metaData: {
|
||||
title: err.title,
|
||||
clientErrorCode: err.clientCode,
|
||||
message: err.clientMessage,
|
||||
messageEnglish: err.messageEnglish
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
4
server/middlewares/offers.ts
Executable file
4
server/middlewares/offers.ts
Executable file
@@ -0,0 +1,4 @@
|
||||
|
||||
// export const evaluateOffer = (offerArray)=>{
|
||||
|
||||
// }
|
||||
126
server/middlewares/preventBruteForce.js
Executable file
126
server/middlewares/preventBruteForce.js
Executable file
@@ -0,0 +1,126 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __generator = (this && this.__generator) || function (thisArg, body) {
|
||||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
|
||||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
||||
function verb(n) { return function (v) { return step([n, v]); }; }
|
||||
function step(op) {
|
||||
if (f) throw new TypeError("Generator is already executing.");
|
||||
while (_) try {
|
||||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
||||
if (y = 0, t) op = [op[0] & 2, t.value];
|
||||
switch (op[0]) {
|
||||
case 0: case 1: t = op; break;
|
||||
case 4: _.label++; return { value: op[1], done: false };
|
||||
case 5: _.label++; y = op[1]; op = [0]; continue;
|
||||
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
||||
default:
|
||||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
||||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
||||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
||||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
||||
if (t[2]) _.ops.pop();
|
||||
_.trys.pop(); continue;
|
||||
}
|
||||
op = body.call(thisArg, _);
|
||||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
||||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
||||
}
|
||||
};
|
||||
exports.__esModule = true;
|
||||
exports.preventBruteForce = exports.rateLimiterMiddleware = exports.globalRedisClient = void 0;
|
||||
var myError_1 = require("../api/myError");
|
||||
var rateLimiteFlexible = require("rate-limiter-flexible");
|
||||
var redis = require("redis");
|
||||
exports.globalRedisClient = redis.createClient({
|
||||
port: process.env.REDIS_PORT,
|
||||
host: process.env.REDIS_HOST,
|
||||
enable_offline_queue: false
|
||||
});
|
||||
exports.globalRedisClient.on('connect', function (err) {
|
||||
console.log('Redis-server is connected');
|
||||
});
|
||||
exports.globalRedisClient.on('error', function (err) {
|
||||
console.log('Error ' + err);
|
||||
});
|
||||
var RateLimiterRedis = rateLimiteFlexible.RateLimiterRedis;
|
||||
var maxWrongAttemptsByIPperDay = 100;
|
||||
var maxConsecutiveFailsByUsernameAndIP = 5;
|
||||
var rateLimiterRedis = new RateLimiterRedis({
|
||||
storeClient: exports.globalRedisClient,
|
||||
points: maxWrongAttemptsByIPperDay,
|
||||
duration: 1000,
|
||||
blockDuration: 60 * 60 // Per second
|
||||
});
|
||||
exports.rateLimiterMiddleware = function (req, res, next) {
|
||||
rateLimiterRedis.consume(req.ip)
|
||||
.then(function () {
|
||||
next();
|
||||
})["catch"](function (err) {
|
||||
err.statusCode = 429;
|
||||
err.clientCode = 11;
|
||||
err.clientMessage = 'درخواست بیش از حد انجام داده اید! بعد از یک ساعت دیگر دوباره اقدام بفرمایید!';
|
||||
err.messageEnglish = 'Too Many Requests';
|
||||
next(err);
|
||||
});
|
||||
};
|
||||
var limiterSlowBruteByIP = new RateLimiterRedis({
|
||||
storeClient: exports.globalRedisClient,
|
||||
keyPrefix: 'login_fail_ip_per_day',
|
||||
points: maxWrongAttemptsByIPperDay,
|
||||
duration: 60 * 60 * 24,
|
||||
blockDuration: 60 * 60 * 24 // Block for 1 day, if 100 wrong attempts per day
|
||||
});
|
||||
var limiterConsecutiveFailsByUsernameAndIP = new RateLimiterRedis({
|
||||
storeClient: exports.globalRedisClient,
|
||||
keyPrefix: 'login_fail_consecutive_username_and_ip',
|
||||
points: maxConsecutiveFailsByUsernameAndIP,
|
||||
duration: 60 * 60,
|
||||
blockDuration: 60 * 60 // Block for 1 hour
|
||||
});
|
||||
var getUsernameIPkey = function (username, ip) { return username + "_" + ip; };
|
||||
function preventBruteForce(req, res, next) {
|
||||
return __awaiter(this, void 0, void 0, function () {
|
||||
var ipAddr, usernameIPkey, _a, resUsernameAndIP, resSlowByIP, retrySecs, error;
|
||||
return __generator(this, function (_b) {
|
||||
switch (_b.label) {
|
||||
case 0:
|
||||
ipAddr = req.ip;
|
||||
usernameIPkey = getUsernameIPkey(req.body.email, ipAddr);
|
||||
return [4 /*yield*/, Promise.all([
|
||||
limiterConsecutiveFailsByUsernameAndIP.get(usernameIPkey),
|
||||
limiterSlowBruteByIP.get(ipAddr)
|
||||
])];
|
||||
case 1:
|
||||
_a = _b.sent(), resUsernameAndIP = _a[0], resSlowByIP = _a[1];
|
||||
retrySecs = 0;
|
||||
// Check if IP or Username + IP is already blocked
|
||||
if (resSlowByIP !== null && resSlowByIP.consumedPoints > maxWrongAttemptsByIPperDay) {
|
||||
retrySecs = Math.round(resSlowByIP.msBeforeNext / 1000) || 1;
|
||||
}
|
||||
else if (resUsernameAndIP !== null && resUsernameAndIP.consumedPoints > maxConsecutiveFailsByUsernameAndIP) {
|
||||
retrySecs = Math.round(resUsernameAndIP.msBeforeNext / 1000) || 1;
|
||||
}
|
||||
if (retrySecs > 0) {
|
||||
error = new myError_1["default"]("Too many requests for user " + req.body.email + " with ip " + ipAddr, 1, 429, 'درخواست بیش از حد انجام داده اید! بعد از یک ساعت دیگر دوباره اقدام بفرمایید!', 'خطا رخ داد');
|
||||
next(error);
|
||||
}
|
||||
else {
|
||||
limiterConsecutiveFailsByUsernameAndIP.consume(usernameIPkey);
|
||||
limiterSlowBruteByIP.consume(ipAddr);
|
||||
next();
|
||||
}
|
||||
return [2 /*return*/];
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
exports.preventBruteForce = preventBruteForce;
|
||||
91
server/middlewares/preventBruteForce.ts
Executable file
91
server/middlewares/preventBruteForce.ts
Executable file
@@ -0,0 +1,91 @@
|
||||
import myError from '../api/myError'
|
||||
import * as rateLimiteFlexible from 'rate-limiter-flexible'
|
||||
import * as redis from 'redis'
|
||||
|
||||
export const globalRedisClient = redis.createClient({
|
||||
port: process.env.REDIS_PORT,
|
||||
host: process.env.REDIS_HOST,
|
||||
enable_offline_queue: false
|
||||
})
|
||||
globalRedisClient.on('connect', function (err) {
|
||||
console.log('Redis-server is connected')
|
||||
})
|
||||
globalRedisClient.on('error', function (err) {
|
||||
console.log('Error ' + err)
|
||||
})
|
||||
|
||||
const RateLimiterRedis = rateLimiteFlexible.RateLimiterRedis
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
const maxWrongAttemptsByIPperDay = 100
|
||||
const maxConsecutiveFailsByUsernameAndIP = 5
|
||||
|
||||
const rateLimiterRedis = new RateLimiterRedis({
|
||||
storeClient: globalRedisClient,
|
||||
points: maxWrongAttemptsByIPperDay, // Number of points
|
||||
duration: 1000, // Per second,
|
||||
blockDuration: 60 * 60 // Per second
|
||||
})
|
||||
|
||||
export const rateLimiterMiddleware = (req, res, next) => {
|
||||
rateLimiterRedis.consume(req.ip)
|
||||
.then(() => {
|
||||
next()
|
||||
})
|
||||
.catch(err => {
|
||||
err.statusCode = 429
|
||||
err.clientCode = 11
|
||||
err.clientMessage = 'درخواست بیش از حد انجام داده اید! بعد از یک ساعت دیگر دوباره اقدام بفرمایید!'
|
||||
err.messageEnglish = 'Too Many Requests'
|
||||
next(err)
|
||||
})
|
||||
}
|
||||
|
||||
const limiterSlowBruteByIP = new RateLimiterRedis({
|
||||
storeClient: globalRedisClient,
|
||||
keyPrefix: 'login_fail_ip_per_day',
|
||||
points: maxWrongAttemptsByIPperDay,
|
||||
duration: 60 * 60 * 24,
|
||||
blockDuration: 60 * 60 * 24 // Block for 1 day, if 100 wrong attempts per day
|
||||
})
|
||||
|
||||
const limiterConsecutiveFailsByUsernameAndIP = new RateLimiterRedis({
|
||||
storeClient: globalRedisClient,
|
||||
keyPrefix: 'login_fail_consecutive_username_and_ip',
|
||||
points: maxConsecutiveFailsByUsernameAndIP,
|
||||
duration: 60 * 60, // Store number for 90 days since first fail
|
||||
blockDuration: 60 * 60 // Block for 1 hour
|
||||
})
|
||||
|
||||
const getUsernameIPkey = (username, ip) => `${username}_${ip}`
|
||||
|
||||
export async function preventBruteForce (req, res, next) {
|
||||
const ipAddr = req.ip
|
||||
const usernameIPkey = getUsernameIPkey(req.body.email, ipAddr)
|
||||
|
||||
const [resUsernameAndIP, resSlowByIP] = await Promise.all([
|
||||
limiterConsecutiveFailsByUsernameAndIP.get(usernameIPkey),
|
||||
limiterSlowBruteByIP.get(ipAddr)
|
||||
])
|
||||
let retrySecs = 0
|
||||
|
||||
// Check if IP or Username + IP is already blocked
|
||||
if (resSlowByIP !== null && resSlowByIP.consumedPoints > maxWrongAttemptsByIPperDay) {
|
||||
retrySecs = Math.round(resSlowByIP.msBeforeNext / 1000) || 1
|
||||
} else if (resUsernameAndIP !== null && resUsernameAndIP.consumedPoints > maxConsecutiveFailsByUsernameAndIP) {
|
||||
retrySecs = Math.round(resUsernameAndIP.msBeforeNext / 1000) || 1
|
||||
}
|
||||
|
||||
if (retrySecs > 0) {
|
||||
const error = new myError(`Too many requests for user ${req.body.email} with ip ${ipAddr}`, 1, 429, 'درخواست بیش از حد انجام داده اید! بعد از یک ساعت دیگر دوباره اقدام بفرمایید!', 'خطا رخ داد')
|
||||
next(error)
|
||||
} else {
|
||||
limiterConsecutiveFailsByUsernameAndIP.consume(usernameIPkey)
|
||||
limiterSlowBruteByIP.consume(ipAddr)
|
||||
next()
|
||||
}
|
||||
}
|
||||
|
||||
7
server/middlewares/response.js
Executable file
7
server/middlewares/response.js
Executable file
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
exports.__esModule = true;
|
||||
function successRes(res, message, data, metaData, statusCode) {
|
||||
if (statusCode === void 0) { statusCode = 200; }
|
||||
return res.status(statusCode).json({ success: true, message: message, data: data, metaData: metaData });
|
||||
}
|
||||
exports["default"] = successRes;
|
||||
5
server/middlewares/response.ts
Executable file
5
server/middlewares/response.ts
Executable file
@@ -0,0 +1,5 @@
|
||||
export default function successRes (res, message?: string, data?, metaData?, statusCode = 200) {
|
||||
return res.status(statusCode).json({ success: true, message: message, data: data, metaData: metaData })
|
||||
}
|
||||
|
||||
|
||||
63
server/middlewares/tryCatch.js
Executable file
63
server/middlewares/tryCatch.js
Executable file
@@ -0,0 +1,63 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __generator = (this && this.__generator) || function (thisArg, body) {
|
||||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
|
||||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
||||
function verb(n) { return function (v) { return step([n, v]); }; }
|
||||
function step(op) {
|
||||
if (f) throw new TypeError("Generator is already executing.");
|
||||
while (_) try {
|
||||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
||||
if (y = 0, t) op = [op[0] & 2, t.value];
|
||||
switch (op[0]) {
|
||||
case 0: case 1: t = op; break;
|
||||
case 4: _.label++; return { value: op[1], done: false };
|
||||
case 5: _.label++; y = op[1]; op = [0]; continue;
|
||||
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
||||
default:
|
||||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
||||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
||||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
||||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
||||
if (t[2]) _.ops.pop();
|
||||
_.trys.pop(); continue;
|
||||
}
|
||||
op = body.call(thisArg, _);
|
||||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
||||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
||||
}
|
||||
};
|
||||
exports.__esModule = true;
|
||||
function tryCatch(cb) {
|
||||
var _this = this;
|
||||
return function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
|
||||
var err_1;
|
||||
return __generator(this, function (_a) {
|
||||
switch (_a.label) {
|
||||
case 0:
|
||||
_a.trys.push([0, 2, , 3]);
|
||||
return [4 /*yield*/, cb(req, res, next)
|
||||
// next()
|
||||
];
|
||||
case 1:
|
||||
_a.sent();
|
||||
return [3 /*break*/, 3];
|
||||
case 2:
|
||||
err_1 = _a.sent();
|
||||
console.log(err_1);
|
||||
next(err_1);
|
||||
return [3 /*break*/, 3];
|
||||
case 3: return [2 /*return*/];
|
||||
}
|
||||
});
|
||||
}); };
|
||||
}
|
||||
exports["default"] = tryCatch;
|
||||
12
server/middlewares/tryCatch.ts
Executable file
12
server/middlewares/tryCatch.ts
Executable file
@@ -0,0 +1,12 @@
|
||||
export default function tryCatch (cb) {
|
||||
return async (req, res, next) => {
|
||||
try {
|
||||
await cb(req, res, next)
|
||||
// next()
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
next(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
63
server/middlewares/tryCtach.js
Executable file
63
server/middlewares/tryCtach.js
Executable file
@@ -0,0 +1,63 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __generator = (this && this.__generator) || function (thisArg, body) {
|
||||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
|
||||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
||||
function verb(n) { return function (v) { return step([n, v]); }; }
|
||||
function step(op) {
|
||||
if (f) throw new TypeError("Generator is already executing.");
|
||||
while (_) try {
|
||||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
||||
if (y = 0, t) op = [op[0] & 2, t.value];
|
||||
switch (op[0]) {
|
||||
case 0: case 1: t = op; break;
|
||||
case 4: _.label++; return { value: op[1], done: false };
|
||||
case 5: _.label++; y = op[1]; op = [0]; continue;
|
||||
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
||||
default:
|
||||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
||||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
||||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
||||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
||||
if (t[2]) _.ops.pop();
|
||||
_.trys.pop(); continue;
|
||||
}
|
||||
op = body.call(thisArg, _);
|
||||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
||||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
||||
}
|
||||
};
|
||||
exports.__esModule = true;
|
||||
function tryCatch(cb) {
|
||||
var _this = this;
|
||||
return function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
|
||||
var err_1;
|
||||
return __generator(this, function (_a) {
|
||||
switch (_a.label) {
|
||||
case 0:
|
||||
_a.trys.push([0, 2, , 3]);
|
||||
return [4 /*yield*/, cb(req, res, next)
|
||||
// next()
|
||||
];
|
||||
case 1:
|
||||
_a.sent();
|
||||
return [3 /*break*/, 3];
|
||||
case 2:
|
||||
err_1 = _a.sent();
|
||||
console.log(err_1);
|
||||
next(err_1);
|
||||
return [3 /*break*/, 3];
|
||||
case 3: return [2 /*return*/];
|
||||
}
|
||||
});
|
||||
}); };
|
||||
}
|
||||
exports["default"] = tryCatch;
|
||||
60
server/middlewares/upload.js
Executable file
60
server/middlewares/upload.js
Executable file
@@ -0,0 +1,60 @@
|
||||
"use strict";
|
||||
exports.__esModule = true;
|
||||
exports.uploadEdit = exports.uploadTemp = exports.editStorage = void 0;
|
||||
var multer = require("multer");
|
||||
var path = require("path");
|
||||
var mongodb = require("mongodb");
|
||||
var ObjectId = mongodb.ObjectId;
|
||||
var TempStorage = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
cb(null, 'images/temp');
|
||||
},
|
||||
filename: function (req, file, cb) {
|
||||
var name = new ObjectId();
|
||||
var ext = path.extname(file.originalname);
|
||||
cb(null, name + ext);
|
||||
}
|
||||
});
|
||||
exports.editStorage = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
cb(null, 'images/temp');
|
||||
},
|
||||
filename: function (req, file, cb) {
|
||||
// const name = uuid4()
|
||||
// const ext = path.extname(file.originalname)
|
||||
cb(null, file.originalname);
|
||||
}
|
||||
});
|
||||
exports.uploadTemp = multer({
|
||||
storage: TempStorage,
|
||||
limits: {
|
||||
fileSize: 1024 * 1024,
|
||||
files: 1,
|
||||
fields: 0
|
||||
},
|
||||
fileFilter: function (req, file, callback) {
|
||||
var ext = path.extname(file.originalname);
|
||||
if (ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg') {
|
||||
return callback(new Error('Only images are allowed'));
|
||||
}
|
||||
callback(null, true);
|
||||
}
|
||||
}).single('image');
|
||||
exports.uploadEdit = multer({
|
||||
storage: exports.editStorage,
|
||||
fileFilter: function (req, file, callback) {
|
||||
var ext = path.extname(file.originalname);
|
||||
if (ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg') {
|
||||
return callback(new Error('Only images are allowed'));
|
||||
}
|
||||
callback(null, true);
|
||||
},
|
||||
limits: {
|
||||
fileSize: 1024 * 1024,
|
||||
files: 10,
|
||||
fields: 2
|
||||
}
|
||||
}).fields([
|
||||
{ name: 'images[]', maxCount: 5 },
|
||||
{ name: 'image', maxCount: 1 }
|
||||
]);
|
||||
64
server/middlewares/upload.ts
Executable file
64
server/middlewares/upload.ts
Executable file
@@ -0,0 +1,64 @@
|
||||
|
||||
import * as multer from 'multer'
|
||||
import * as uuid4 from 'uuid4'
|
||||
import * as path from 'path'
|
||||
import * as mongodb from 'mongodb'
|
||||
const ObjectId = mongodb.ObjectId
|
||||
|
||||
var TempStorage = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
cb(null, 'images/temp')
|
||||
},
|
||||
filename: function (req, file, cb) {
|
||||
const name = new ObjectId()
|
||||
const ext = path.extname(file.originalname)
|
||||
cb(null, name + ext)
|
||||
}
|
||||
})
|
||||
|
||||
export const editStorage = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
cb(null, 'images/temp')
|
||||
},
|
||||
filename: function (req, file, cb) {
|
||||
// const name = uuid4()
|
||||
// const ext = path.extname(file.originalname)
|
||||
cb(null, file.originalname)
|
||||
}
|
||||
})
|
||||
|
||||
export const uploadTemp = multer({
|
||||
storage: TempStorage,
|
||||
limits: {
|
||||
fileSize: 1024 * 1024,
|
||||
files: 1,
|
||||
fields: 0
|
||||
},
|
||||
fileFilter: function (req, file, callback) {
|
||||
var ext = path.extname(file.originalname)
|
||||
if (ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg') {
|
||||
return callback(new Error('Only images are allowed'))
|
||||
}
|
||||
callback(null, true)
|
||||
}
|
||||
}).single('image')
|
||||
|
||||
export const uploadEdit = multer({
|
||||
storage: editStorage,
|
||||
fileFilter: function (req, file, callback) {
|
||||
var ext = path.extname(file.originalname)
|
||||
if (ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg') {
|
||||
return callback(new Error('Only images are allowed'))
|
||||
}
|
||||
callback(null, true)
|
||||
},
|
||||
limits: {
|
||||
fileSize: 1024 * 1024,
|
||||
files: 10,
|
||||
fields: 2
|
||||
}
|
||||
}).fields([
|
||||
{ name: 'images[]', maxCount: 5 },
|
||||
{ name: 'image', maxCount: 1 }
|
||||
])
|
||||
|
||||
1874
server/middlewares/validation.js
Executable file
1874
server/middlewares/validation.js
Executable file
File diff suppressed because it is too large
Load Diff
1872
server/middlewares/validation.ts
Executable file
1872
server/middlewares/validation.ts
Executable file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user