Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'request-ip' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
const server = http.createServer((request, response) => {
// gets the ip of the request
let ip = requestIp.getClientIp(request)
// this snippet closes the request to favicon.ico
if (request.url === '/favicon.ico') return response.end()
// here we add an attempt to the ip
lf.addAttempt(ip)
.then(() => {
// here we check if the client has reached the maximum number of attempts
// or if the client has an active timeout
return lf.checkClient(ip)
})
.then((client) => {
if (!client) {
response.writeHead(200, {'Content-Type': 'text/plain'})
response.end('Hello World\n')
} else {
response.writeHead(403, {'Content-Type': 'text/plain'})
http.createServer((request, response) => {
// gets the ip of the request
let ip = requestIp.getClientIp(request)
// this snippet closes the request to favicon.ico
if (request.url === '/favicon.ico') {
response.end()
console.log('favicon requested')
return
}
// here we add an attempt to the ip
lf.addAttempt(ip, (errAdd) => {
if (errAdd) return console.log(errAdd)
// here we check if the client has reached the maximum number of attempts
// or if the client has an active timeout
lf.checkClient(ip, (errCheck, client) => {
if (errCheck) return console.log(errCheck)
if (!client) {
module.exports = (req) => {
if ('development' === NODE_ENV) {
// ignore limits during development
return
}
const clientIp = requestIp.getClientIp(req)
seen[clientIp] = seen[clientIp] || 0
if (seen[clientIp] > 10) {
const err = new Error('Too many views per IP')
err.statusCode = 429
throw err
}
seen[clientIp]++
}
const ipMiddleware = (req, res, next) => {
let clientIp;
if (req.header('cf-connecting-ip')){
req.clientIp = req.header('cf-connecting-ip'); // I want to always give priority to this header
} else {
req.clientIp = requestIp.getClientIp(req); // if it's not there then fall back
}
next();
};
mongoose.set('useUnifiedTopology', true);
mongoose.connect('mongodb://'+keys.database.username+':' + keys.database.password + '@ds157298.mlab.com:57298/cat-facts', {
useNewUrlParser: true
});
app.set('socketio', io);
app.set('view engine', 'ejs');
app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(express.static(__dirname + '/public'));
app.use(requestIp.mw());
const mongoStore = new MongoStore({url: keys.database.url()});
const sessionMiddleware = session({
secret: keys.session.secret,
resave: true,
saveUninitialized: true,
store: mongoStore
});
app.use(sessionMiddleware);
app.use(passport.initialize());
app.use(passport.session()); // Persistent login sessions
// Define routes
app.use('/', require('./app/routes'));
module.exports = function(app, config) {
let env = config.env || 'dev';
app.locals.ENV = env;
app.locals.ENV_DEVELOPMENT = env == 'dev';
/**
* add middleware to add ip address to request.
*/
app.use(requestIp.mw());
/**
* Create and configure our templating engine
*/
require(config.root + '/app/nunjucks/nunjucks')(app, config);
// app.use(favicon(config.root + '/public/img/favicon.ico')); //TODO serve all the icons here. No need to log these. Also take care of apple-icons, touch icons. tile-iscons etc
/**
* Log all requests. Including statics.
*/
require(config.root + '/app/middleware/logging/logging.js').use(app);
app.use(i18n.init);
// Middleware to remove locale from url and set i18n.locale based on url. This allows one route to match different locales
// Set host and port
app.set('host', process.env.IP || '127.0.0.1');
app.set('port', process.env.PORT || 8080);
// Load Assets from Public folder
app.use(express.static(`${__dirname}/public`));
// Set view mode
app.set('view engine', 'ejs');
// Enable method override
app.use(methodOverride('_method'));
// Setup IP middleware
app.use(expressip().getIpInfoMiddleware);
app.use(requestIp.mw());
// Sets the view directory
app.set('views', `${__dirname}/views`);
// Morgan HTTP request logging
if (!process.env.NODE_ENV === 'development') {
app.use(logger('combined'));
} else {
app.use(logger('dev'));
}
// Setup Session config
// expiryDate for sessions:
// eslint-disable-next-line prefer-const
let sess = {
resave: false,
const [, token = null] = /^Bearer (.+)$/.exec(authorization) || [];
return {
db,
user: { token },
// WebSocket connections just send an auth token upon initial connection
// (authentication is handled in `subscriptions.onConnect` when calling
// `server.start`). Since they don't have a token attached permanently,
// we need to tell the auth middleware to allow these requests through.
authorized: !request && Boolean(connection),
};
},
});
// attach client IP info to request object in handlers
server.express.use(requestIp.mw());
// setup __proxy route for stripping problematic iframe headers
server.express.use('/__proxy', proxy);
// serve client application with server info injected
server.express.use('/web', client);
// listen on the provided PORT
server.start(
{
port: PORT,
playground: DISABLE_PLAYGROUND ? false : PLAYGROUND_URL,
subscriptions: {
onConnect: ({ token }) => {
if (!SANDBOX && token !== API_KEY) throw new Error('401: You must be logged in.');
},
const USE_DEV_TOOLS = Boolean(process.env.DEV_TOOLS);
const app = express();
app.use(helmet());
/* tc-accounts App was designed for browser environment, and its decodeToken()
* function (which we would like to use server-side as well) depends on global
* atob() method, which is present in browser, but not in NodeJS. This is the
* fix. */
global.atob = atob;
app.use(favicon(path.resolve(__dirname, '../assets/images/favicon.ico')));
app.use(bodyParser.json({ limit: '300kb' }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(requestIp.mw());
const checkAuthorizationHeader = (req, res, next) => {
if (req.headers.authorization !== `ApiKey ${config.SERVER_API_KEY}`) {
return res.status(403).end();
}
return next();
};
/* Log Entries service proxy. */
app.use('/community-app-assets/api/logger', checkAuthorizationHeader, (req, res) => {
logger.log(`${req.clientIp} > `, ...req.body.data);
res.end();
});
loggerMiddleware.token('ip', req => req.clientIp);
verify: addRawBody
})(req, res, err => {
if (err) {
console.log(err);
res.sendStatus(400);
return;
}
next();
});
});
function addRawBody(req, res, buf, encoding) {
req.rawBody = buf.toString();
}
app.use(requestIp.mw());
app.use("/static", express.static(path.join(__dirname, "../dashboard/build/static")));
app.use("/api", apiRouter.api);
app.use("/", express.static(path.join(__dirname, "../dashboard/build")));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, "../dashboard/build/index.html"));
});
require("./reminder").init();
app.listen(process.env.PORT, () => {
console.log("App listening on port " + process.env.PORT);
});
}