socket.on('login', function (user) { pseudo = ent.encode(user.pseudo); password= ent.encode(user.password); var dbPassword = ""; console.log("New login"); // check login and password in database db.each("SELECT * FROM users WHERE login = '******' LIMIT 1", function(err, row) { console.log("db login : "******"db pass : "******"enter : "+password); console.log("dppass : "******"") { socket.set('pseudo', pseudo); users.push({pseudo:pseudo,password:password}); socket.broadcast.emit('pseudo', pseudo); } else { socket.emit('redirect'); // wrong password or login redirect with error } } }); });
exports.sendmessage = function(req, res) { var data = { remoteip: req.connection.remoteAddress, challenge: req.body.recaptcha_challenge_field, response: req.body.recaptcha_response_field }; var messageData = { username: ent.encode(req.body.username), email: ent.encode(req.body.email), message: ent.encode(req.body.message) }; // console.log(messageData); var recaptcha = new Recaptcha(PUBLIC_KEY, PRIVATE_KEY, data); recaptcha.verify(function(success, error_code) { if (success) { req.flash('success', 'Thank you! your message has been recorded'); sendmail(messageData); res.redirect('/'); } else { req.flash('error', 'Sorry, your message could not be recorded. Please try again'); console.log(error_code); res.redirect('/'); } }); };
socket.on('room',function(data){ var peopleInRoom = {}; var room = ent.encode(data.room); // Join room socket.join(room); // Set the room of the current client people[socket.id].room = room; // Check if room id defined if (rooms[room] === undefined){ // If not define it and set it's userStory to undefined rooms[room] = {"name" : room, "currentUserStory" : undefined, "cardsRevealed" : false, "lastMessages" : []}; } // Check if client already has a name if (data.name !== undefined){ data.name = ent.encode(data.name.trim()); if(data.name != ''){ people[socket.id].name = data.name; } } // Display last messages sent rooms[room].lastMessages.forEach(function(data){ if(data.author == people[socket.id].name){ socket.emit('message', {msg: data.msg, author : null, me : true, server : true}); }else{ socket.emit('message', {msg: data.msg, author: data.author, me : false, server : true}); } }); // Show for each room who is online in it io.sockets.clients(room).forEach(function (socket) { peopleInRoom[socket.id] = people[socket.id]; }); // Send the list of participants to newly connected socket socket.emit('participants', {people: peopleInRoom, id: socket.id}); // Send the current User Story if one is already here if (rooms[room].currentUserStory != undefined) { socket.emit('newUserStory', rooms[room].currentUserStory); } // Then broadcast the array in order to list all participants in main.js socket.broadcast.to(room).emit('participants', {people: peopleInRoom, connect: people[socket.id].name}); });
socket.on('nouveau_client', function(pseudo) { pseudo = ent.encode(pseudo); socket.set('pseudo', pseudo); var player = { pseudo: pseudo, order: game.players.length, stats: { dna: 20, spores: 5, prod: 1, attack: 1, def: 1, conso: { spores: 5, laps: 5, count: 1 }, demography: 1 }, score: 0, associations: [], hasToken: false, lose: false }; game.players.push(player); io.sockets.emit('nouveau_client', {players:game.players, maxPlayers: game.playersMax} ); //socket.broadcast.emit('nouveau_client', game.players ); if (!game.started && game.players.length <= game.playersMax && game.players.length > 1) { io.sockets.emit('canStartGame', true ); } });
var args = Array.prototype.concat.apply([], Array.prototype.slice.call(arguments)).map(function(val, index) { if (typeof val === "string" && index !== 0) { return ent.encode(val); } else { return val; } });
.spread(function (template, messageCount, editCount, activeDays, firstMessage, randomMessage, emoticonCounts, hangmanStats, fightStats) { firstMessage = firstMessage[0]; randomMessage = randomMessage[0]; var dateFormat = 'dddd MMMM Do, YYYY'; var dateTimeFormat = 'dddd MMMM Do, YYYY @ h:mm:ssa'; var averageCountPerDay = 0; if (messageCount && activeDays.length) { averageCountPerDay = messageCount / activeDays.length; } var data = { user: roomMember.user.nick, messageCount: messageCount, averageMessageCountPerDay: ~~averageCountPerDay, editCount: editCount, startDate: moment(roomMember.user.createdAt).format(dateFormat), totalDays: moment().diff(roomMember.user.createdAt, 'days'), activeDays: activeDays.length, firstMessage: firstMessage ? '"' + ent.decode(firstMessage.text) + '" (' + moment(firstMessage.createdAt).format(dateTimeFormat) + ')' : '', emotes: ent.decode(_.pluck(emoticonCounts, 'emoticon').join(' ')), randomMessage: randomMessage ? '"' + ent.decode(randomMessage.text) + '" (' + moment(randomMessage.createdAt).format(dateTimeFormat) + ')' : '', hangmanGuessCount: hangmanStats.count, hangmanGuessAccuracy: hangmanStats.guessAccuracy ? hangmanStats.guessAccuracy + '%' : 'N/A', hangmanPrivateWinLoss: (hangmanStats.privateWins ? hangmanStats.privateWins : 0) + ' - ' + (hangmanStats.privateLosses ? hangmanStats.privateLosses : 0), hangmanPublicWinLoss: hangmanStats.publicWins + ' - ' + hangmanStats.publicLosses, fightWinPercentage: fightStats.fightWinPercentage, fightRoundWinPercentage: fightStats.fightRoundWinPercentage, fightVictim1: fightStats.topVictims && fightStats.topVictims[0] ? fightStats.topVictims[0].userNick + " " + fightStats.topVictims[0].beatings : '', fightVictim2: fightStats.topVictims && fightStats.topVictims[1] ? fightStats.topVictims[1].userNick + " " + fightStats.topVictims[1].beatings : '', fightVictim3: fightStats.topVictims && fightStats.topVictims[2] ? fightStats.topVictims[2].userNick + " " + fightStats.topVictims[2].beatings : '', fightVictim4: fightStats.topVictims && fightStats.topVictims[3] ? fightStats.topVictims[3].userNick + " " + fightStats.topVictims[3].beatings : '', fightVictim5: fightStats.topVictims && fightStats.topVictims[4] ? fightStats.topVictims[4].userNick + " " + fightStats.topVictims[4].beatings : '' }; if (activeDays) { var mostActive = makeActiveModel(activeDays); var activeDaysSorted = _(activeDays) .sortByAll([ function (day) { return day._id.year; }, function (day) { return day._id.dayOfYear; } ]) .reverse() .value(); var lastActive = makeActiveModel(activeDaysSorted); data.activeDate = mostActive.day.format(dateFormat) + ' (' + mostActive.object.count + ' messages)'; data.lastActiveDate = lastActive.day.format(dateFormat) + ' (' + lastActive.object.count + ' messages)'; } return ent.encode(_.template(template)(data)); });
socket.on('message', function (_message, _room) { console.log(_room+', message :'+_message); insertMess(socket.username, _message, _room, getDate()); _message = ent.encode(_message); io.sockets.in(_room).emit('message', {username:socket.username, picture:socket.picture,room:_room, message:{message:_message, date:getDate()}}); //socket.broadcast.emit('message', {username:socket.username, picture:socket.picture,room:_room, message:{message:_message, date:getDate()}}); });
socket.on('desktop-post-message', function(data){ var message = ent.encode(data.message); console.log('>desktop ',desktops[socket.id].name, ' posted : ',message); io.of('/desktop').emit('desktop-add-message', { message : "<b>"+desktops[socket.id].name+"</b> "+message }); });
router.post('/user/traitementEdition', function(req, res, next){ var collection = db.get().collection('users'); collection.updateOne({pseudo: ent.encode(req.body.pseudoUserManaged)}, {$set: {droits: req.body.droitsUserManaged}}, function(err, result){ collection.findOne({pseudo: ent.encode(req.body.pseudoUserManaged)}, function(err, result){ if(err){ var decodeUser = { pseudo: ent.decode(result.pseudo), mail: ent.decode(result.mail), droits: result.droits, dateCreation: result.dateCreation, derniereConnection: result.derniereConnection }; res.render('admin/listeUsers.jade', {title: 'Gestion des utilisateurs', message: 'Quelque chose s\'est mal passé!', user: req.session.user, userManaged: decodeUser}); } else { var decodeUser = { pseudo: ent.decode(result.pseudo), mail: ent.decode(result.mail), droits: result.droits, dateCreation: result.dateCreation, derniereConnection: result.derniereConnection }; res.render('users/profil.jade', {title: 'Gestion: ' + result.pseudo, message: 'Modification réussie!', user: req.session.user, userManaged: decodeUser, moment: moment}); }; }); }); });
socket.on('nouveau_client', function(pseudo) { app.socket.users.push({'id':socket.id, 'pseudo': pseudo}); pseudo = ent.encode(pseudo); socket.pseudo = pseudo; app.socket.io.emit('nouveau_client', {'pseudo':pseudo, 'users':app.socket.users}); // this.emit('nouveau_client', {'pseudo':pseudo, 'users':app.socket.users}); });
reset.generateToken(48, function(tokenID) { var time = reset.generateTime(); reset.insertIntoResetDB(email, resetDB, time, tokenID); var uri = opts.uri + '?tokenID=' + tokenID; transport.sendMail({ sender : opts.from || 'nodepasswordreset@localhost', to : email, subject : opts.subject || 'Password Reset Request', text : opts.text || "", html : opts.html || [ 'Click this link to reset your password:\r\n', '<br>', '<a href="' + encodeURI(uri) + '">', ent.encode(uri), '</a>', '' ].join('\r\n') }, function (error, success) { if (error) { if (cb.error) cb.error(error); } else { if(cb.success) cb.success(success) } }); })
Object.keys(contents).forEach(function(lang){ // encode '%' characters otherwise postgres will break (because the format function will be used) contents[lang] = Ent.encode(contents[lang], { special: {"%": true} }); console.log("contents[lang]: ", contents[lang]) });
var self = function (email, cb) { var session = reset.generate(); if (!session) return; var uri = session.uri = opts.uri + '?' + session.id; transport.sendMail({ sender : opts.from || 'nodepasswordreset@localhost', to : email, subject : opts.subject || 'Password reset request', text : opts.text || "", html : opts.html || [ 'Click this link to reset your password:\r\n', '<br>', '<a href="' + encodeURI(uri) + '">', ent.encode(uri), '</a>', '' ].join('\r\n') }, function (error, success) { if (error) { if (cb.error) cb.error(error); delete reset.sessions[session.id]; } else { if(cb.success) cb.success(success) } }); return session; };
var PatternsToSVG = function(patternData) { this.patternData = patternData; this.outputStrings = { svg : [], svgSamples : [] }; // iterate over all patterns, and convert them to css for(var g = 0; g < this.patternData.groupCount; g++) { var group = this.patternData.groups[g]; this.patternData.groups[g].svg = []; this.patternData.groups[g].svgSamples = []; for(var i = 0; i < this.patternData.groups[g].patterns.length; i++) { var data = this.patternData.groups[g].patterns[i]; // svg class this.patternData.groups[g].svg[i] = templates.pattern.svg(data); // sample usage divs data.encodedSVG = ent.encode(this.patternData.groups[g].svg[i]); this.patternData.groups[g].svgSamples[i] = templates.components.rect(data); } } };
socket.on('nouveau_client', function(pseudo) { alert(__dirname); pseudo = ent.encode(pseudo); socket.set('pseudo', pseudo); socket.broadcast.emit('nouveau_client', pseudo); });
socket.get('pseudo', function (error, pseudo) { message = ent.encode(message); if(message.toLowerCase() == currentQuestion.reponse.toLowerCase()) { console.log('Good response : '+currentQuestion.reponse); var currentPoints = 0; var id = 0; db.each("SELECT * FROM users WHERE login = '******' LIMIT 1", function(err, row) { console.log("db points : "+row.points); id = row.id; currentPoints = row.points + pointsToWin; }, function(err, rows) { if(rows != 0) { // first to have the good response have 5 points, second 3, third 2 and others 1 if(pointsToWin > 1) { if(pointsToWin == 5) { pointsToWin--; } pointsToWin--; } // update points for the user db.run("UPDATE users SET points = '"+currentPoints+"' WHERE id = ?", id); } } ); io.sockets.emit('good_response', pseudo); } else { socket.broadcast.emit('message', {pseudo: pseudo, message: message}); } });
brucedown(_input ,function (err, _output) { if (err) return done(err) input = ent.encode(_input) output = _output done() })
var writeRow = function (file, i) { try { var decoded = decodeURI( req.url.replace(/\/$/, '') + '/' + file[0] ); } catch (err) { failed = true; res.statusCode = 400; return res.end(err + '\n') } html += '<tr><td><code>(' + perms(file[1]) + ')</code> <a href="' + ent.encode(decoded) + '">' + ent.encode(file[0]) + '</a></td></tr>\n'; }
socket.on("newMsg", function(data){ data.message = ent.encode(data.message); if(data.type == 0) io.to("General").emit("incomingMsg", data); else if(data.type==1) io.to("teamA").emit("incomingMsg", data); else if(data.type==2) io.to("teamB").emit("incomingMsg", data); else if(data.type==3) io.to("teamC").emit("incomingMsg", data); else if(data.team==4) io.to("teamD").emit("incomingMsg", data); });
socket.on('newUserStory', function(data){ // If the user story is blank, set it to 'User story' if(data.userStory == ''){ data.userStory = 'User story'; } rooms[data.room].currentUserStory = ent.encode(data.userStory.trim()); io.sockets.in(data.room).emit('newUserStory', rooms[data.room].currentUserStory); });
socket.on('message', function (message) { message = ent.encode(message); var reg = new RegExp("((http://)|(https://)[a-zA-Z0-9/.]+)+","gi"); var linkifed = message.replace(reg, "<a href='$1' target=_blank>$1</a>"); var date = new Date(); var dateString = date.toLocaleDateString() + " " + date.toLocaleTimeString(); socket.broadcast.emit('message', {pseudo: socket.pseudo, message: linkifed, dateString: dateString}); });
socket.on('newName',function(data){ // Check name (not empty, not full of spaces, no XSS) newName = ent.encode(data.newName.trim()); if(newName != ''){ people[socket.id].name = newName; io.sockets.in(data.room).emit('participants', {people: people}); } });
socket.on('nouveau_client', function (pseudo) { pseudo = ent.encode(pseudo); socket.pseudo = pseudo; socket.broadcast.emit('nouveau_client', pseudo); users[pseudo]={name:pseudo, id:socket.id}; socket.emit('connected', users); // envoi à moi socket.broadcast.emit('connected', users); // envoi à tous });
req.on('end', function() { var ent = require('ent'); var sanitize = require('sanitize-html'); var S = require('string'); var querystring = require('querystring'); var input = querystring.parse(data); /**************************************** * For now, a rudimentary way to prevent randos from posting on my blog. * *************************************/ if (input["password"] != process.env.SENDGRID_KEY) { res.writeHead(403, {"Content-Type" : "text/plain"}); res.end("Sorry, you don't have permission to publish."); return; } // Strip bad HTML while keeping good HTML with tags var safeArticle = ent.encode(sanitize(input["article"])); // Calculate article reading time, where 1 min = 250 words var wordCount = S(safeArticle).stripTags().s.split(" ").length; var readTime = Math.round(wordCount / 250); readTime = readTime > 1 ? readTime : 1; // readTime at least 1 readTime += readTime === 1 ? " minute" : " minutes";// minute vs minutes var months = ["January", "February", "March", "April", "May", "June", "July", "August","September", "October", "November", "December"]; var date = new Date(); var dateStr = months[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear(); // Insert the article after getting the unique id getNextSequence("postid", function(seq) { var newArticle = { _id: seq, title: input["title"], article: safeArticle, path: input["path"], read: readTime, date: dateStr, visible: parseInt(input["visible"]) || 0 }; db.collection('articles').insert(newArticle, function(err, records) { console.log("Article inserted into database: ", records); if (err) { console.log("Error: ", err); } }); }); });
messageService.createMessage = function (roomMember, incomingText) { const text = ent.encode(incomingText); if (!text || !text.length) { throw new InvalidInputError(); // block the trolls } else if (/^\/nick\s+/i.test(text)) { // Change the current user's nick return userService.setUserNick(roomMember, text); } else if (/^\/(away|afk|busy)/i.test(text)) { return setUserBusy(roomMember, text); // away, afk, busy (with optional message) } else if (/^\/help/i.test(text)) { return getHelp(roomMember, text); } else if (/^\/stats/i.test(text)) { return stats(roomMember, text); } else if (/^\/(topic|name|privacy|icon)/i.test(text)) { return RoomService.setRoomAttribute(roomMember, text); } else if (/^\/magic8ball/i.test(text)) { return magic8ball(roomMember, text); // Jordan's Magic 8 Ball, Bitches } else if (/^\/soulsphere/i.test(text)) { return soulSphere(roomMember, text); // Spooky soul sphere } else if (/^\/roll/i.test(text)) { return roll(roomMember, text); } else if (/^\/show\s+:?\w+:?/i.test(text)) { return animation(roomMember, text); } else if (/^\/me\s+/i.test(text)) { return me(roomMember, text); } else if (/^\/h(?:angman)?(?:\s(\w)?|$)/i.test(text)) { return hangman(roomMember, text); } else if (/^\/f(?:ight)?(?:\s(\w)?|$)/i.test(text)) { return fight(roomMember, text); } else if (/^\/code /i.test(text)) { return code(roomMember, text); } else if (/^\/image(?:pick|search)*\s+/i.test(text)) { return imageSearch.image(roomMember, text); } else if (/^\/gif(?:pick|search)*\s+/i.test(text)) { return imageSearch.gif(roomMember, text); } else if (/^\/(promote|demote)\s+([\w\s\-\.]{0,19})/i.test(text)) { return userService.changeUserRole(roomMember, text); } else if (/^\/setinfo\s+/i.test(text)) { return userService.setInfo(roomMember, text); } else if (/^\/whois\s+/i.test(text)) { return userService.whois(roomMember, text); } else if (/^\/poll?(?:\s+(.+)?|$)/i.test(text)) { return pollService.poll(roomMember, text); } else if (/^\/vote\s+/i.test(text)) { return pollService.vote(roomMember, text); } else if (/^\/poll(\s?)close?(?:\s*)/i.test(text)) { return pollService.pollClose(roomMember, text); } else if (/^\/meme/i.test(text)) { return meme(roomMember, text); } else if (/^\/\w+/i.test(text)) { return badCommand(roomMember, text); } else { return message(roomMember, text, "standard"); } };
socket.on('desktop-update-name', function(data){ var previousName = desktops[socket.id].name, newName = ent.encode(data.name); console.log('>desktop update name from ',previousName, ' to ',newName); desktops[socket.id].name = newName; io.of('/desktop').emit('desktop-update-chat-users', { desktops : desktops, message : "<b>"+previousName + '</b> renamed to <b>' + newName +"<b>" }); });
function render(dirs, files) { // each entry in the array is a [name, stat] tuple // TODO: use stylessheets? var html = '<!doctype html>\ <html> \ <head> \ <meta charset="utf-8"> \ <title>Index of ' + pathname +'</title> \ </head> \ <body> \ <h1>Index of ' + pathname + '</h1>\n'; html += '<table>'; var failed = false; var writeRow = function (file, i) { // render a row given a [name, stat] tuple var isDir = file[1].isDirectory(); var href = parsed.pathname.replace(/\/$/, '') + '/' + encodeURIComponent(file[0]); // append trailing slash and query for dir entry if (isDir) { href += '/' + ((parsed.search)? parsed.search:''); } var displayName = ent.encode(file[0]) + ((isDir)? '/':''); // TODO: use stylessheets? html += '<tr>' + '<td><code>(' + permsToString(file[1]) + ')</code></td>' + '<td style="text-align: right; padding-left: 1em"><code>' + sizeToString(file[1], humanReadable, si) + '</code></td>' + '<td style="padding-left: 1em"><a href="' + href + '">' + displayName + '</a></td>' + '</tr>\n'; }; dirs.sort(function (a, b) { return b[0] - a[0]; } ).forEach(writeRow); files.sort(function (a, b) { return b.toString().localeCompare(a.toString()); }).forEach(writeRow); html += '</table>\n'; html += '<br><address>Node.js ' + process.version + '/ <a href="https://github.com/jesusabdullah/node-ecstatic">ecstatic</a> ' + 'server running @ ' + ent.encode(req.headers.host || '') + '</address>\n' + '</body></html>' ; if (!failed) { res.writeHead(200, { "Content-Type": "text/html" }); res.end(html); } }
/** * Creates a new event * * @constructor * @param {Object} data The events data object * @property {String} eventDate Event date in this format 'dd/mm/yyyy' * @property {String} eventName Event name * @property {String} eventBadge URL to event badge image * @property {String} eventLocation Event location i.e. 'South West' * @property {String} eventLoc Event location abbreviation i.e. 'SW' * @property {String} eventPostCode Event postcode * @property {String} eventDiscipline Event disclipline i.e. 'Cycling' * @property {String} eventDescription Event description * @property {Array} eventClasses Array of classes that belong to the event */ function Event(data) { this.eventDate = utils.parseDate(data[0]); this.eventName = data[1]; this.eventBadge = ''; this.eventLocation = data[5]; this.eventLoc = getLocationAbbr(data[5]); this.eventPostCode = data[6]; this.eventDiscipline = data[7]; this.eventDescription = ent.encode(data[8]); this.eventClasses = []; }
function each (key, elem) { if (isStream(res[key])) { tf.emit('stream', res[key]); res[key].pipe(elem.createWriteStream()); } else if (Array.isArray(res[key])) { var bufs = []; var write = function (buf) { bufs.push(buf) }; var end = function (next) { var html = Buffer.concat(bufs).toString('utf8'); if (html.length) { res[key].forEach(function (m) { var mm = {}; mm[key] = m; trf.queue(hyperglue(html, mm).outerHTML); }); } trf.queue(null); }; var trf = through(write, end); trf.pipe(elem.createStream({ outer: true })).pipe(trf); } else if (typeof res[key] === 'object') { Object.keys(res[key]).forEach(function (k) { var v = res[key][k]; if (k === '_html') { if (isStream(v)) { v.pipe(elem.createWriteStream()); } else if (typeof v === 'string' || Buffer.isBuffer(v)) { elem.createWriteStream().end(v); } else { elem.createWriteStream().end(String(v)); } } else if (k === '_text') { if (Buffer.isBuffer(v)) v = v.toString('utf8') else if (typeof v !== 'string') v = String(v); elem.createWriteStream().end(encode(v)); } else { if (Buffer.isBuffer(v)) v = v.toString('utf8') else if (typeof v !== 'string') v = String(v); elem.setAttribute(k, v); } }); } else { var v = res[key]; if (Buffer.isBuffer(v)) v = v.toString('utf8') else if (typeof v !== 'string') v = String(v); elem.createWriteStream().end(encode(v)); } }
generateCardHoverSpan: function(source) { var tagged; if (source !== undefined) { // Then generate the tags through setting the innerHtml. This is the only way to preserve the text around the img tags. // Encode the source in html, to prevent XSS nastiness. Then replace the newlines with <br/>. Then insert the <img> tags. tagged = <div dangerouslySetInnerHTML={{__html: ent.encode(source).replace(/ /g, '<br/>').replace(/\[(.*?)\]/g, (fullMatch, firstMatch) => `<span onMouseOver={this.onCardNameHover(${firstMatch})}><b>${firstMatch}</b></span>` )}}></div> } return tagged; },