Best JavaScript code snippet using playwright-internal
index.js
Source:index.js
1/*!2 * proxy-addr3 * Copyright(c) 2014-2016 Douglas Christopher Wilson4 * MIT Licensed5 */6'use strict'7/**8 * Module exports.9 * @public10 */11module.exports = proxyaddr12module.exports.all = alladdrs13module.exports.compile = compile14/**15 * Module dependencies.16 * @private17 */18var forwarded = require('forwarded')19var ipaddr = require('ipaddr.js')20/**21 * Variables.22 * @private23 */24var DIGIT_REGEXP = /^[0-9]+$/25var isip = ipaddr.isValid26var parseip = ipaddr.parse27/**28 * Pre-defined IP ranges.29 * @private30 */31var IP_RANGES = {32 linklocal: ['169.254.0.0/16', 'fe80::/10'],33 loopback: ['127.0.0.1/8', '::1/128'],34 uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7']35}36/**37 * Get all addresses in the request, optionally stopping38 * at the first untrusted.39 *40 * @param {Object} request41 * @param {Function|Array|String} [trust]42 * @public43 */44function alladdrs (req, trust) {45 // get addresses46 var addrs = forwarded(req)47 if (!trust) {48 // Return all addresses49 return addrs50 }51 if (typeof trust !== 'function') {52 trust = compile(trust)53 }54 for (var i = 0; i < addrs.length - 1; i++) {55 if (trust(addrs[i], i)) continue56 addrs.length = i + 157 }58 return addrs59}60/**61 * Compile argument into trust function.62 *63 * @param {Array|String} val64 * @private65 */66function compile (val) {67 if (!val) {68 throw new TypeError('argument is required')69 }70 var trust71 if (typeof val === 'string') {72 trust = [val]73 } else if (Array.isArray(val)) {74 trust = val.slice()75 } else {76 throw new TypeError('unsupported trust argument')77 }78 for (var i = 0; i < trust.length; i++) {79 val = trust[i]80 if (!IP_RANGES.hasOwnProperty(val)) {81 continue82 }83 // Splice in pre-defined range84 val = IP_RANGES[val]85 trust.splice.apply(trust, [i, 1].concat(val))86 i += val.length - 187 }88 return compileTrust(compileRangeSubnets(trust))89}90/**91 * Compile `arr` elements into range subnets.92 *93 * @param {Array} arr94 * @private95 */96function compileRangeSubnets (arr) {97 var rangeSubnets = new Array(arr.length)98 for (var i = 0; i < arr.length; i++) {99 rangeSubnets[i] = parseipNotation(arr[i])100 }101 return rangeSubnets102}103/**104 * Compile range subnet array into trust function.105 *106 * @param {Array} rangeSubnets107 * @private108 */109function compileTrust (rangeSubnets) {110 // Return optimized function based on length111 var len = rangeSubnets.length112 return len === 0113 ? trustNone114 : len === 1115 ? trustSingle(rangeSubnets[0])116 : trustMulti(rangeSubnets)117}118/**119 * Parse IP notation string into range subnet.120 *121 * @param {String} note122 * @private123 */124function parseipNotation (note) {125 var pos = note.lastIndexOf('/')126 var str = pos !== -1127 ? note.substring(0, pos)128 : note129 if (!isip(str)) {130 throw new TypeError('invalid IP address: ' + str)131 }132 var ip = parseip(str)133 if (pos === -1 && ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) {134 // Store as IPv4135 ip = ip.toIPv4Address()136 }137 var max = ip.kind() === 'ipv6'138 ? 128139 : 32140 var range = pos !== -1141 ? note.substring(pos + 1, note.length)142 : null143 if (range === null) {144 range = max145 } else if (DIGIT_REGEXP.test(range)) {146 range = parseInt(range, 10)147 } else if (ip.kind() === 'ipv4' && isip(range)) {148 range = parseNetmask(range)149 } else {150 range = null151 }152 if (range <= 0 || range > max) {153 throw new TypeError('invalid range on address: ' + note)154 }155 return [ip, range]156}157/**158 * Parse netmask string into CIDR range.159 *160 * @param {String} netmask161 * @private162 */163function parseNetmask (netmask) {164 var ip = parseip(netmask)165 var kind = ip.kind()166 return kind === 'ipv4'167 ? ip.prefixLengthFromSubnetMask()168 : null169}170/**171 * Determine address of proxied request.172 *173 * @param {Object} request174 * @param {Function|Array|String} trust175 * @public176 */177function proxyaddr (req, trust) {178 if (!req) {179 throw new TypeError('req argument is required')180 }181 if (!trust) {182 throw new TypeError('trust argument is required')183 }184 var addrs = alladdrs(req, trust)185 var addr = addrs[addrs.length - 1]186 return addr187}188/**189 * Static trust function to trust nothing.190 *191 * @private192 */193function trustNone () {194 return false195}196/**197 * Compile trust function for multiple subnets.198 *199 * @param {Array} subnets200 * @private201 */202function trustMulti (subnets) {203 return function trust (addr) {204 if (!isip(addr)) return false205 var ip = parseip(addr)206 var ipconv207 var kind = ip.kind()208 for (var i = 0; i < subnets.length; i++) {209 var subnet = subnets[i]210 var subnetip = subnet[0]211 var subnetkind = subnetip.kind()212 var subnetrange = subnet[1]213 var trusted = ip214 if (kind !== subnetkind) {215 if (subnetkind === 'ipv4' && !ip.isIPv4MappedAddress()) {216 // Incompatible IP addresses217 continue218 }219 if (!ipconv) {220 // Convert IP to match subnet IP kind221 ipconv = subnetkind === 'ipv4'222 ? ip.toIPv4Address()223 : ip.toIPv4MappedAddress()224 }225 trusted = ipconv226 }227 if (trusted.match(subnetip, subnetrange)) {228 return true229 }230 }231 return false232 }233}234/**235 * Compile trust function for single subnet.236 *237 * @param {Object} subnet238 * @private239 */240function trustSingle (subnet) {241 var subnetip = subnet[0]242 var subnetkind = subnetip.kind()243 var subnetisipv4 = subnetkind === 'ipv4'244 var subnetrange = subnet[1]245 return function trust (addr) {246 if (!isip(addr)) return false247 var ip = parseip(addr)248 var kind = ip.kind()249 if (kind !== subnetkind) {250 if (subnetisipv4 && !ip.isIPv4MappedAddress()) {251 // Incompatible IP addresses252 return false253 }254 // Convert IP to match subnet IP kind255 ip = subnetisipv4256 ? ip.toIPv4Address()257 : ip.toIPv4MappedAddress()258 }259 return ip.match(subnetip, subnetrange)260 }...
department.js
Source:department.js
1const winston = require('winston');2const jwt = require('jsonwebtoken');3const { insertDepartment } = require('../services/department');4const { removeDepartment } = require('../services/department');5const { getallDepartment } = require('../services/department');6const { updateDepartment } = require('../services/department');7const { getDepartmentCount } = require('../services/department');8const parseIp = require('../middleware/parseIp');9const logger = winston.createLogger({10 transports: [11 new winston.transports.File({12 level: 'info',13 filename: 'logs/department.log',14 json: true,15 format: winston.format.combine(winston.format.timestamp(),16 winston.format.json()),17 }),18 ],19});20//Add Department---------21const DepartmentRegister = async (req, res) => {22 logger.info(`received Department request with details ${req.body.department_id}`);23 const DepartmentDetails = {24 department_name: req.body.department_name,25 roles: req.body.roles,26 };27 const secret = '!@#DWe$%^gge&&**';28 const token = jwt.sign({ sub: req.body.department_id }, secret, {29 expiresIn: 86400, // expires in 24 hours30 });31 const addDepartment = await insertDepartment(DepartmentDetails);32 if (addDepartment.command === 'INSERT') {33 logger.info(`Department Details added successfully`);34 return res.status(201)35 .json({36 statusCode: 200,37 message: 'Sucess!',38 details: [addDepartment.rows,39 {40 token: token,41 ipAddress: parseIp(req)42 },]43 });44 }45 return res.status(400)46 .json({47 statusCode: 400,48 message: addDepartment.detail,49 ipAddress: parseIp(req)50 });51};52//deleteDepartmentDetails------------------------53const deleteDepartmentDetails = async (req, res) => {54 const DepartmentDetails = {55 department_id: req.body.department_id,56 };57 const deletedepartment = await removeDepartment(DepartmentDetails);58 if (deletedepartment.command === 'DELETE') {59 return res.status(201)60 .json({61 statusCode: 200,62 message: 'Sucess!',63 details: deletedepartment.rows,64 ipAddress: parseIp(req)65 });66 }67 return res.status(400)68 .json({69 statusCode: 400,70 message: deletedepartment.detail,71 ipAddress: parseIp(req)72 });73};74// getallDepartmentdetails----------------------------------75const getallDepartmentdetails = async (req, res) => {76 const getDepartment = await getallDepartment();77 if (getDepartment.command === 'SELECT') {78 return res.status(201)79 .json({80 statusCode: 200,81 message: 'Sucess!',82 details: getDepartment.rows,83 ipAddress: parseIp(req)84 });85 }86 return res.status(400)87 .json({88 statusCode: 400,89 message: getDepartment.detail,90 ipAddress: parseIp(req)91 });92};93//updateDepartmentDetails-------------------94const updateDepartmentDetails = async (req, res) => {95 const DepartmentDetails = {96 department_id: req.body.department_id,97 department_name: req.body.department_name,98 roles: req.body.roles,99 };100 const updatedepartment = await updateDepartment(DepartmentDetails);101 if (updatedepartment.command === 'UPDATE') {102 return res.status(201)103 .json({104 statusCode: 200,105 message: 'Sucess!',106 details: updatedepartment.rows,107 ipAddress: parseIp(req)108 });109 }110 return res.status(400)111 .json({112 statusCode: 400,113 message: updatedepartment.detail,114 ipAddress: parseIp(req)115 });116};117//Total count of Department 118const getCountDepartmentDetails = async (req, res) => {119 const getCountdepartment = await getDepartmentCount();120 if (getCountdepartment.command === 'SELECT') {121 return res.status(201)122 .json({123 statusCode: 200,124 message: 'Sucess!',125 departmentCount: getCountdepartment.rows,126 ipAddress: parseIp(req)127 });128 }129 return res.status(400)130 .json({131 statusCode: 400,132 message: getCountdepartment.detail,133 ipAddress: parseIp(req)134 });135};...
menuUser.js
Source:menuUser.js
1const winston = require('winston');2const jwt = require('jsonwebtoken');3const { insertUser } = require('../services/menuUser');4const { removeUser } = require('../services/menuUser');5const { getallUser } = require('../services/menuUser');6const { updateUser } = require('../services/menuUser');7const { getUserCount } = require('../services/menuUser');8const parseIp = require('../middleware/parseIp');9const logger = winston.createLogger({10 transports: [11 new winston.transports.File({12 level: 'info',13 filename: 'logs/menuUser.log',14 json: true,15 format: winston.format.combine(winston.format.timestamp(),16 winston.format.json()),17 }),18 ],19});20//Add MenuUser---------21const MenuUserRegister = async (req, res) => {22 logger.info(`received Department request with details ${req.body.menuuser_id}`);23 const menuUserDetails = {24 user_name: req.body.user_name,25 department_name: req.body.department_name,26 email_id: req.body.email_id,27 address: req.body.address,28 };29 const secret = '!@#DWe$%^gge&&**';30 const token = jwt.sign({ sub: req.body.menuuser_id }, secret, {31 expiresIn: 86400, // expires in 24 hours32 });33 const addUser = await insertUser(menuUserDetails);34 if (addUser.command === 'INSERT') {35 logger.info(`User Details added successfully`);36 return res.status(201)37 .json({38 statusCode: 200,39 message: 'Sucess!',40 details: [addUser.rows,41 {42 token: token,43 ipAddress: parseIp(req)44 },]45 });46 }47 return res.status(400)48 .json({49 statusCode: 400,50 message: addUser.detail,51 ipAddress: parseIp(req)52 });53};54//deleteUserDetails------------------------55const deleteUserDetails = async (req, res) => {56 const menuUserDetails = {57 menuuser_id: req.body.menuuser_id,58 };59 const deleteuser = await removeUser(menuUserDetails);60 if (deleteuser.command === 'DELETE') {61 return res.status(201)62 .json({63 statusCode: 200,64 message: 'Sucess!',65 details: deleteuser.rows,66 ipAddress: parseIp(req)67 });68 }69 return res.status(400)70 .json({71 statusCode: 400,72 message: deleteuser.detail,73 ipAddress: parseIp(req)74 });75};76// getallUser----------------------------------77const getallUserdetails = async (req, res) => {78 const getUser = await getallUser();79 if (getUser.command === 'SELECT') {80 return res.status(201)81 .json({82 statusCode: 200,83 message: 'Sucess!',84 details: getUser.rows,85 ipAddress: parseIp(req)86 });87 }88 return res.status(400)89 .json({90 statusCode: 400,91 message: getUser.detail,92 ipAddress: parseIp(req)93 });94};95//updateUserDetails-------------------96const updateUserDetails = async (req, res) => {97 const menuUserDetails = {98 menuuser_id: req.body.menuuser_id,99 user_name: req.body.user_name,100 department_name: req.body.department_name,101 email_id: req.body.email_id,102 address: req.body.address,103 };104 const updateuser = await updateUser(menuUserDetails);105 if (updateuser.command === 'UPDATE') {106 return res.status(201)107 .json({108 statusCode: 200,109 message: 'Sucess!',110 details: updateuser.rows,111 ipAddress: parseIp(req)112 });113 }114 return res.status(400)115 .json({116 statusCode: 400,117 message: updateuser.detail,118 ipAddress: parseIp(req)119 });120};121//Total count of User 122const getCounUserDetails = async (req, res) => {123 const getCountuser = await getUserCount();124 if (getCountuser.command === 'SELECT') {125 return res.status(201)126 .json({127 statusCode: 200,128 message: 'Sucess!',129 userCount: getCountuser.rows,130 ipAddress: parseIp(req)131 });132 }133 return res.status(400)134 .json({135 statusCode: 400,136 message: getCountuser.detail,137 ipAddress: parseIp(req)138 });139};...
ip_utils_test.js
Source:ip_utils_test.js
1'use strict';2const { parseIp, isIpInRange, isLocalIp } = require('../background-scripts/ip_utils');3const assert = require('chai').assert;4describe('ip_utils.js', () => {5 describe('parseIp', () => {6 it('rejects an empty string', () => {7 assert(parseIp('') === -1);8 });9 it('rejects a string consisting entirely of dots', () => {10 assert(parseIp('.') === -1);11 assert(parseIp('..') === -1);12 assert(parseIp('...') === -1);13 assert(parseIp('....') === -1);14 });15 it('rejects a string consisting only of digits', () => {16 assert(parseIp('1') === -1);17 });18 it('rejects a string not consisting of four parts separated by dots', () => {19 assert(parseIp('1.1') === -1);20 assert(parseIp('1.1.1') === -1);21 assert(parseIp('1.1.1.1.1') === -1);22 });23 it('rejects a well-formed IP address followed by one or multiple trailing dots', () => {24 assert(parseIp('1.1.1.1.') === -1);25 assert(parseIp('1.1.1.1..') === -1);26 assert(parseIp('1.1.1.1...') === -1);27 });28 it('rejects an IP address-like string with omitted parts', () => {29 assert(parseIp('.1.1.1') === -1);30 assert(parseIp('1..1.1') === -1);31 assert(parseIp('1.1..1') === -1);32 assert(parseIp('1.1.1.') === -1);33 });34 it('rejects an IP address-like string with invalid parts', () => {35 assert(parseIp('192.168.1.256') === -1);36 assert(parseIp('192.168.256.1') === -1);37 assert(parseIp('192.256.1.1') === -1);38 assert(parseIp('256.168.1.1') === -1);39 assert(parseIp('256.168.1.-1') === -1);40 });41 it('correctly parses well-formed IP addresses', () => {42 assert(parseIp('192.168.0.1') === 0xc0a80001);43 assert(parseIp('127.0.0.1') === 0x7f000001);44 assert(parseIp('1.1.1.1') === 0x01010101);45 assert(parseIp('8.8.8.8') === 0x08080808);46 });47 });48 describe('isIpInRange', () => {49 it('correctly detects if IP is in range', () => {50 assert(isIpInRange(0xabadcafe, [0x00000000, 0x00000000]));51 assert(isIpInRange(0x7f000001, [0x7f000000, 0xff000000]));52 assert(isIpInRange(0xc0a80001, [0xc0a80000, 0xffff0000]));53 assert(isIpInRange(0xc0a80101, [0xc0a80100, 0xffffff00]));54 assert(isIpInRange(0xdeadbeef, [0xdeadbeef, 0xffffffff]));55 });56 it('correctly detects if IP is outside of range', () => {57 assert(!isIpInRange(0xaaaaaaaa, [0xdeadbeef, 0xffffffff]));58 assert(!isIpInRange(0xaaaaaaaa, [0x7f000000, 0xff000000]));59 assert(!isIpInRange(0xaaaaaaaa, [0xc0a80000, 0xffff0000]));60 });61 });62 describe('isLocalIp', () => {63 it('correctly detects if IP is a private network or loopback address', () => {64 assert(isLocalIp(0x00000000));65 assert(isLocalIp(0x7fabcdef));66 assert(isLocalIp(0x0aabcdef));67 assert(isLocalIp(0xc0a8abcd));68 assert(isLocalIp(0xac1abcde));69 });70 it('correctly detects if IP is not a private network or loopback address', () => {71 assert(!isLocalIp(0x00abcdef));72 assert(!isLocalIp(0x01010101));73 assert(!isLocalIp(0x01000001));74 assert(!isLocalIp(0x08080808));75 assert(!isLocalIp(0x08080404));76 });77 });...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!