Best JavaScript code snippet using webdriverio-monorepo
passport.js
Source:passport.js
1const LocalStrategy = require("passport-local").Strategy;2const googleStrategy = require("passport-google-oauth20").Strategy;3const User = require("../models/user");4const UserSession = require("../models/userSessions");5const Token = require("../models/tokenVerification");6const emailer = require("../emailer/impl");7const socialPostListener = require("../listeners/postSocial").em;8const socialPostKeys = require("../config/socialPostKeys");9const referralEmitter = require("../listeners/userReferral").em;10const crypto = require("crypto");11const uuid = require("uuid/v4")12require("dotenv").config();13const facebookStrategy = require("passport-facebook").Strategy;14const twitterStrategy = require("passport-twitter").Strategy;15const linkedinStrategy = require("passport-linkedin-oauth2").Strategy;16function newDefaultUser() {17 return new User({18 email: "",19 name: "",20 created: "",21 lastActive: "",22 userSession:"",23 profile: {},24 examData: {25 payment: {26 course_1: false,27 course_2: false,28 course_3: false,29 course_4: false,30 course_5: false,31 },32 examBasic: {33 attempts: 0,34 marks: 035 },36 examAdvanced: {37 attempts: 0,38 marks: 039 },40 examProfessional: {41 attempts: 0,42 marks: 043 },44 certificateHash: [{}]45 },46 auth: {47 facebook: {48 id: "",49 accessToken: "",50 refreshToken: ""51 },52 twitter: {53 id: "",54 token: "",55 tokenSecret: ""56 },57 google: {58 id: "",59 accessToken: "",60 refreshToken: ""61 },62 local: {63 password: "",64 isVerified: false65 },66 linkedin: {67 refreshToken:"",68 accessToken: "",69 id: ""70 }71 }72 });73}74module.exports = function(passport) {75 passport.serializeUser(function(user, done) {76 done(null, user.id);77 });78 passport.deserializeUser(function(id, done) {79 User.findById(id, function(err, user) {80 done(err, user);81 });82 });83 passport.use(84 "local-signup",85 new LocalStrategy(86 {87 usernameField: "email",88 passwordField: "password",89 passReqToCallback: true90 },91 function(req, email, password, done) {92 console.log(req.body, email, password);93 process.nextTick(function() {94 User.findOne({ email: email }, function(err, user) {95 if (err) {96 console.log("some error", err);97 return done(err);98 }99 if (user) {100 if (user.auth.local.password != "") {101 console.log("email already taken");102 return done(null, false, "That email is already taken.");103 } else {104 console.log("email registered to another social");105 return done(106 null,107 false,108 "This email is registered to another one of the socials."109 );110 }111 } else {112 // Validating user113 let refId = req.body.refId; 114 let validEm = validateEmail(email),115 validPwd = validatePWD(password),116 validFN = validateName(req.body.firstName),117 validLN = validateName(req.body.lastName);118 if (!validEm.valid) {119 return done(null, false, "Invalid Email");120 }121 if (!validPwd.valid) {122 return done(null, false, validPwd.msg);123 }124 if (!validFN.valid) {125 return done(null, false, validFN.msg);126 }127 if (!validLN.valid) {128 return done(null, false, validLN.msg);129 }130 console.log("in method creating user");131 var newUser = newDefaultUser();132 newUser.email = email;133 newUser.name = formatName(134 req.body.firstName + " " + req.body.lastName135 );136 newUser.timestamp = Date.now();137 newUser.timestamp = Date.now();138 newUser.auth.local.password = newUser.generateHash(password);139 newUser.created = Date.now();140 newUser.lastActive = Date.now();141 newUser.save(function(err) {142 if (err) {143 console.log("Error:", err);144 throw err;145 }146 socialPostListener.emit("varTriggerUpdate", "registrations");147 var token = new Token({148 email: email,149 token: crypto.randomBytes(16).toString("hex")150 });151 token.save(function(err) {152 if (err) {153 console.log(err);154 return done(null, false, "token errror");155 }156 console.log(email, token);157 emailer158 .sendTokenMail(email, token, req, "signup")159 .then(res => console.log("emailer res>>>>>", res))160 .catch(err => console.log("emailer err>>>>", err));161 referralEmitter.emit("createUserReferral", email);162 if (refId!==""){163 console.log(`|${refId}|`);164 165 referralEmitter.emit("referralUsage", refId, email);166 }167 return done(null, newUser);168 });169 });170 }171 });172 });173 }174 )175 );176 passport.use(177 "local-login",178 new LocalStrategy(179 {180 usernameField: "email",181 passwordField: "password",182 passReqToCallback: true183 },184 function(req, email, password, done) {185 let validEm = validateEmail(email);186 if (!validEm.valid) {187 return done(null, false, "Invalid email");188 }189 User.findOne({ email: email }, async function(err, user) {190 if (err) return done(err);191 if (!user) return done(null, false, "No user found.");192 if (user.auth.local.password == "") {193 console.log("Proper call");194 return done(195 null,196 false,197 "Email associated with a existing social login."198 );199 }200 if (!user.validPassword(password))201 return done(null, false, "Oops! Wrong password.");202 if (!user.auth.local.isVerified)203 return done(204 null,205 false,206 "User is not verified, Please check your email"207 );208 user.lastActive = Date.now();209 let sessionId = uuid();210 user.userSession = sessionId;211 let newSession = genSession(sessionId);212 newSession.email = user.email;213 newSession.ip = req.headers["x-forwarded-for"] || req.ip;214 newSession.startTime = Date.now();215 newSession.platform = "local";216 await newSession.save();217 await user.save();218 return done(null, user);219 });220 }221 )222 );223 // Google with Google224 passport.use(225 new googleStrategy(226 {227 clientID: process.env.GOOGLE_CLIENT_ID,228 clientSecret: process.env.GOOGLE_CLIENT_SECRET,229 callbackURL: "https://www.blockdegree.org/auth/google/callback",230 passReqToCallback: true231 },232 async (req, accessToken, refreshToken, profile, done) => {233 if (req.user) {234 if (235 req.user.auth.google.id == "" ||236 req.user.auth.google.id == undefined237 ) {238 // check if the credentials are associated with any other user.239 let otherUser = await User.findOne({240 "auth.google.id": profile.id241 });242 if (otherUser != null) {243 // this set of credentials are associated with another account, show error244 return done(245 "This social account is already linked to other account, please try logging in with other account.",246 null,247 "This social account is already linked to other account, please try logging in with other account."248 );249 }250 let user = await User.findOne({ email: req.user.email });251 user.auth.google.id = profile.id;252 user.auth.google.accessToken = accessToken;253 user.auth.google.refreshToken = refreshToken;254 user.lastActive = Date.now();255 let sessionId = uuid();256 user.userSession = sessionId;257 let newSession = genSession(sessionId);258 newSession.email = user.email;259 newSession.ip = req.headers["x-forwarded-for"] || req.ip;260 newSession.startTime = Date.now();261 newSession.platform = "google";262 await newSession.save();263 await user.save();264 return done(null, user);265 }266 let user = await User.findOne({ email: req.user.email });267 user.lastActive = Date.now();268 let sessionId = uuid();269 user.userSession = sessionId;270 let newSession = genSession(sessionId);271 newSession.email = user.email;272 newSession.ip = req.headers["x-forwarded-for"] || req.ip;273 newSession.startTime = Date.now();274 newSession.platform = "google";275 await newSession.save();276 await user.save();277 return done(null, req.user);278 }279 // find user by google id280 const existingUser = await User.findOne({281 "auth.google.id": profile.id282 });283 if (existingUser) {284 // console.log(` In passport verification ${existingUser.email}`)285 existingUser.lastActive = Date.now();286 let sessionId = uuid();287 existingUser.userSession = sessionId;288 let newSession = genSession(sessionId);289 newSession.email = existingUser.email;290 newSession.ip = req.headers["x-forwarded-for"] || req.ip;291 newSession.startTime = Date.now();292 newSession.platform = "google";293 await newSession.save();294 await existingUser.save();295 return done(null, existingUser);296 }297 // email registered298 if (profile.emails.length > 0) {299 const linkEmail = await User.findOne({300 email: profile.emails[0].value301 });302 if (linkEmail) {303 linkEmail.auth.google.id = profile.id;304 linkEmail.auth.google.accessToken = accessToken;305 linkEmail.auth.google.refreshToken = refreshToken;306 linkEmail.lastActive = Date.now();307 let sessionId = uuid();308 linkEmail.userSession = sessionId;309 let newSession = genSession(sessionId);310 newSession.email = linkEmail.email;311 newSession.ip = req.headers["x-forwarded-for"] || req.ip;312 newSession.startTime = Date.now();313 newSession.platform = "google";314 await newSession.save();315 await linkEmail.save();316 return done(null, linkEmail);317 }318 }319 if (profile.emails.length < 1) {320 return done(321 "no email-id not associated with this social account",322 null,323 "no email-id not associated with this social account"324 );325 }326 newUser = newDefaultUser();327 newUser.auth.google.id = profile.id;328 newUser.email = profile.emails[0].value;329 newUser.name = formatName(profile._json.name);330 newUser.auth.google.accessToken = accessToken;331 newUser.auth.google.refreshToken = refreshToken;332 newUser.created = Date.now();333 newUser.lastActive = Date.now();334 335 let sessionId = uuid();336 newUser.userSession = sessionId;337 let newSession = genSession(sessionId);338 newSession.email = newUser.email;339 newSession.ip = req.headers["x-forwarded-for"] || req.ip;340 newSession.startTime = Date.now();341 newSession.platform = "google";342 await newSession.save(); 343 await newUser.save();344 socialPostListener.emit("varTriggerUpdate", "registrations");345 done(null, newUser, "new-name");346 }347 )348 );349 // Login with Facebook350 passport.use(351 new facebookStrategy(352 {353 clientID: process.env.FACEBOOK_CLIENT_ID,354 clientSecret: process.env.FACEBOOK_CLIENT_SECRET,355 callbackURL: "https://www.blockdegree.org/auth/facebook/callback",356 passReqToCallback: true,357 profileFields: ["id", "emails", "name", "displayName"]358 },359 async (req, accessToken, refreshToken, profile, done) => {360 process.nextTick(async function() {361 if (req.user) {362 if (363 req.user.auth.facebook.id == "" ||364 req.user.auth.facebook.id == undefined365 ) {366 // check if the credentials are associated with any other user.367 let otherUser = await User.findOne({368 "auth.facebook.id": profile.id369 });370 if (otherUser != null) {371 // this set of credentials are associated with another account, show error372 return done(373 "This social account is already linked to other account, please try logging in with other account.",374 null,375 "This social account is already linked to other account, please try logging in with other account."376 );377 }378 let user = await User.findOne({ email: req.user.email });379 user.auth.facebook.id = profile.id;380 user.auth.facebook.accessToken = accessToken;381 user.auth.facebook.refreshToken = refreshToken;382 user.lastActive = Date.now();383 let sessionId = uuid();384 user.userSession = sessionId;385 let newSession = genSession(sessionId);386 newSession.email = user.email;387 newSession.ip = req.headers["x-forwarded-for"] || req.ip;388 newSession.startTime = Date.now();389 newSession.platform = "facebook";390 await newSession.save();391 await user.save();392 return done(null, user);393 }394 let user = await User.findOne({ email: req.user.email });395 let otherUserSocial = await User.findOne({396 "auth.facebook.id": profile.id397 });398 if (otherUserSocial!==null && otherUserSocial.email!==user.email){399 return done(400 "This social account is not linked to your account.",401 null,402 "This social account is not linked to your account."403 );404 }405 user.auth.facebook.accessToken = accessToken;406 user.auth.facebook.refreshToken = refreshToken;407 user.lastActive = Date.now();408 let sessionId = uuid();409 user.userSession = sessionId;410 411 let newSession = genSession(sessionId);412 newSession.email = user.email;413 newSession.ip = req.headers["x-forwarded-for"] || req.ip;414 newSession.startTime = Date.now();415 newSession.platform = "facebook";416 await newSession.save();417 await user.save();418 return done(null, req.user);419 }420 if (!profile) {421 return done("Profile not set", null);422 }423 let existingUser = await User.findOne({424 "auth.facebook.id": profile.id425 });426 if (existingUser) {427 existingUser.auth.facebook.accessToken = accessToken;428 existingUser.auth.facebook.refreshToken = refreshToken || "";429 existingUser.lastActive = Date.now();430 let sessionId = uuid();431 existingUser.userSession = sessionId;432 433 let newSession = genSession(sessionId);434 newSession.email = existingUser.email;435 newSession.ip = req.headers["x-forwarded-for"] || req.ip;436 newSession.startTime = Date.now();437 newSession.platform = "facebook";438 await newSession.save();439 await existingUser.save();440 return done(null, existingUser);441 }442 if (profile.emails == undefined || profile.emails == null) {443 return done(444 "no email-id not associated with this social account",445 null,446 "no email-id not associated with this social account"447 );448 }449 // email registered450 if (profile.emails.length > 0) {451 const linkEmail = await User.findOne({452 email: profile.emails[0].value453 });454 if (linkEmail) {455 linkEmail.auth.facebook.id = profile.id;456 linkEmail.auth.facebook.accessToken = accessToken;457 linkEmail.auth.facebook.refreshToken = refreshToken || "";458 linkEmail.lastActive = Date.now();459 let sessionId = uuid();460 linkEmail.userSession = sessionId;461 let newSession = genSession(sessionId);462 newSession.email = linkEmail.email;463 newSession.ip = req.headers["x-forwarded-for"] || req.ip;464 newSession.startTime = Date.now();465 newSession.platform = "facebook";466 await newSession.save();467 await linkEmail.save();468 done(null, linkEmail);469 }470 }471 let existingUser2 = await User.findOne({472 email: profile.emails[0].value473 });474 if (existingUser2) {475 let user = await User.findOne({ email: profile.emails[0].value });476 user.auth.facebook.id = profile.id;477 user.auth.facebook.accessToken = accessToken;478 user.auth.facebook.refreshToken = refreshToken || "";479 user.lastActive = Date.now();480 let sessionId = uuid();481 user.userSession = sessionId;482 let newSession = genSession(sessionId);483 newSession.email = user.email;484 newSession.ip = req.headers["x-forwarded-for"] || req.ip;485 newSession.startTime = Date.now();486 newSession.platform = "facebook";487 await newSession.save();488 489 await user.save();490 return done(null, user);491 }492 newUser = newDefaultUser();493 newUser.email = profile.emails[0].value;494 newUser.auth.facebook.id = profile.id;495 newUser.auth.facebook.accessToken = accessToken;496 newUser.auth.facebook.refreshToken = refreshToken || "";497 newUser.name = formatName(profile.displayName);498 newUser.created = Date.now();499 newUser.lastActive = Date.now();500 let sessionId = uuid();501 newUser.userSession = sessionId;502 503 let newSession = genSession(sessionId);504 newSession.email = newUser.email;505 newSession.ip = req.headers["x-forwarded-for"] || req.ip;506 newSession.startTime = Date.now();507 newSession.platform = "facebook";508 await newSession.save(); 509 await newUser.save();510 socialPostListener.emit("varTriggerUpdate", "registrations");511 done(null, newUser, "new-name");512 });513 }514 )515 );516 passport.use(517 "facebookAdminRefresh",518 new facebookStrategy(519 {520 clientID: socialPostKeys.facebook.app_id,521 clientSecret: socialPostKeys.facebook.app_secret,522 callbackURL: "https://www.blockdegree.org/admin/facebookRefresh/callback"523 },524 async (token, tokenSecret, profile, done) => {525 if (profile.emails[0].value === socialPostKeys.facebook.email){526 console.log(`Token: ${token} TokenSecret: ${tokenSecret}`);527 console.log(`Profile: ${profile}`);528 done(null, { token: token, tokenSecret: tokenSecret });529 }530 else{531 console.log(`Admin tried to referesh token with different account ${profile.emails[0].value}, actual: ${socialPostKeys.facebook.email}.`);532 done("invalid facaebook account", null);533 } 534 }535 )536 );537 // Login with Twitter538 passport.use(539 new twitterStrategy(540 {541 consumerKey: process.env.TWITTER_CLIENT_ID,542 consumerSecret: process.env.TWITTER_CLIENT_SECRET,543 callbackURL: "https://www.blockdegree.org/auth/twitter/callback",544 includeEmail: true,545 passReqToCallback: true546 },547 async (req, token, tokenSecret, profile, done) => {548 console.log("called twitter auth");549 if (req.user) {550 if (551 req.user.auth.twitter.id == "" ||552 req.user.auth.twitter.id == undefined553 ) {554 // check if the credentials are associated with any other user.555 let otherUser = await User.findOne({556 "auth.twitter.id": profile.id557 });558 if (otherUser != null) {559 // this set of credentials are associated with another account, show error560 return done(561 "This social account is already linked to other account, please try logging in with other account.",562 null,563 "This social account is already linked to other account, please try logging in with other account."564 );565 }566 // add credentials567 let user = await User.findOne({ email: req.user.email });568 let otherUserSocial = await User.findOne({569 "auth.twitter.id": profile.id570 });571 if (otherUserSocial!==null && otherUserSocial.email!==user.email){572 return done(573 "This social account is not linked to your account.",574 null,575 "This social account is not linked to your account."576 );577 }578 user.auth.twitter.id = profile.id;579 user.auth.twitter.token = token;580 user.auth.twitter.tokenSecret = tokenSecret;581 user.lastActive = Date.now();582 let sessionId = uuid();583 user.userSession = sessionId;584 let newSession = genSession(sessionId);585 newSession.email = user.email;586 newSession.ip = req.headers["x-forwarded-for"] || req.ip;587 newSession.startTime = Date.now();588 newSession.platform = "twitter";589 await newSession.save();590 await user.save();591 return done(null, user);592 }593 let user = await User.findOne({ email: req.user.email });594 user.auth.twitter.token = token;595 user.auth.twitter.tokenSecret = tokenSecret;596 user.lastActive = Date.now();597 let sessionId = uuid();598 user.userSession = sessionId;599 let newSession = genSession(sessionId);600 newSession.email = user.email;601 newSession.ip = req.headers["x-forwarded-for"] || req.ip;602 newSession.startTime = Date.now();603 newSession.platform = "twitter";604 await newSession.save();605 await user.save();606 return done(null, req.user);607 }608 let existingUser = await User.findOne({609 "auth.twitter.id": profile.id610 });611 if (existingUser) {612 existingUser.auth.twitter.token = token;613 existingUser.auth.twitter.tokenSecret = tokenSecret;614 existingUser.lastActive = Date.now();615 let sessionId = uuid();616 existingUser.userSession = sessionId;617 let newSession = genSession(sessionId);618 newSession.email = existingUser.email;619 newSession.ip = req.headers["x-forwarded-for"] || req.ip;620 newSession.startTime = Date.now();621 newSession.platform = "twitter";622 await newSession.save();623 await existingUser.save();624 return done(null, existingUser);625 }626 if (profile.emails == undefined || profile.emails == null) {627 return done(628 "no email-id not associated with this social account",629 null,630 "no email-id not associated with this social account"631 );632 }633 // Link auths via email634 if (profile.emails.length > 0) {635 const linkEmail = await User.findOne({636 email: profile.emails[0].value637 });638 if (linkEmail) {639 linkEmail.auth.twitter.id = profile.id;640 linkEmail.auth.twitter.token = token;641 linkEmail.auth.twitter.tokenSecret = tokenSecret;642 linkEmail.lastActive = Date.now();643 let sessionId = uuid();644 linkEmail.userSession = sessionId;645 let newSession = genSession(sessionId);646 newSession.email = linkEmail.email;647 newSession.ip = req.headers["x-forwarded-for"] || req.ip;648 newSession.startTime = Date.now();649 newSession.platform = "twitter";650 await newSession.save();651 await linkEmail.save();652 return done(null, linkEmail);653 }654 }655 let existingUser2 = await User.findOne({656 email: profile.emails[0].value657 });658 if (existingUser2) {659 let user = await User.findOne({ email: profile.emails[0].value });660 user.auth.twitter.id = profile.id;661 user.auth.twitter.token = token;662 user.auth.twitter.tokenSecret = tokenSecret;663 user.lastActive = Date.now();664 let sessionId = uuid();665 user.userSession = sessionId;666 let newSession = genSession(sessionId);667 newSession.email = user.email;668 newSession.ip = req.headers["x-forwarded-for"] || req.ip;669 newSession.startTime = Date.now();670 newSession.platform = "twitter";671 await newSession.save();672 await user.save();673 return done(null, user);674 }675 newUser = newDefaultUser();676 newUser.auth.twitter.id = profile.id;677 newUser.name = formatName(profile.displayName);678 newUser.email = profile.emails[0].value;679 newUser.auth.twitter.token = token;680 newUser.auth.twitter.tokenSecret = tokenSecret;681 newUser.created = Date.now();682 newUser.lastActive = Date.now();683 let sessionId = uuid();684 newUser.userSession = sessionId;685 let newSession = genSession(sessionId);686 newSession.email = newUser.email;687 newSession.ip = req.headers["x-forwarded-for"] || req.ip;688 newSession.startTime = Date.now();689 newSession.platform = "twitter";690 await newSession.save(); 691 await newUser.save();692 socialPostListener.emit("varTriggerUpdate", "registrations");693 done(null, newUser, "new-name");694 }695 )696 );697 // Login with Linkedin698 passport.use(699 new linkedinStrategy(700 {701 clientID: process.env.LINKEDIN_CLIENT,702 clientSecret: process.env.LINKEDIN_SECRET,703 callbackURL: "https://www.blockdegree.org/auth/linkedin/callback",704 scope: ["r_liteprofile", "r_emailaddress", "w_member_social"],705 passReqToCallback: true706 },707 async (req, accessToken, refreshToken, profile, done) => {708 process.nextTick(async function() {709 if (req.user) {710 if (711 req.user.auth.linkedin.id == "" ||712 req.user.auth.linkedin.id == undefined713 ) {714 // check if the credentials are associated with any other user.715 let otherUser = await User.findOne({716 "auth.linkedin.id": profile.id717 });718 if (otherUser != null) {719 // this set of credentials are associated with another account, show error720 return done(721 "This social account is already linked to other account, please try logging in with other account.",722 null,723 "This social account is already linked to other account, please try logging in with other account."724 );725 }726 // add credentials727 let user = await User.findOne({ email: req.user.email });728 user.auth.linkedin.id = profile.id;729 user.auth.linkedin.accessToken = accessToken;730 user.auth.linkedin.refreshToken = refreshToken;731 user.lastActive = Date.now();732 let sessionId = uuid();733 user.userSession = sessionId;734 735 let newSession = genSession(sessionId);736 newSession.email = user.email;737 newSession.ip = req.headers["x-forwarded-for"] || req.ip;738 newSession.startTime = Date.now();739 newSession.platform = "linkedin";740 await newSession.save();741 await user.save();742 return done(null, user);743 }744 let user = await User.findOne({ email: req.user.email });745 let otherUserSocial = await User.findOne({746 "auth.linkedin.id": profile.id747 });748 if (otherUserSocial!==null&&otherUserSocial.email!==user.email){749 return done(750 "This social account is not linked to your account.",751 null,752 "This social account is not linked to your account."753 );754 }755 user.auth.linkedin.accessToken = accessToken;756 user.auth.linkedin.refreshToken = refreshToken;757 user.lastActive = Date.now();758 let sessionId = uuid();759 user.userSession = sessionId;760 761 let newSession = genSession(sessionId);762 newSession.email = user.email;763 newSession.ip = req.headers["x-forwarded-for"] || req.ip;764 newSession.startTime = Date.now();765 newSession.platform = "linkedin";766 await newSession.save();767 await user.save();768 return done(null, user);769 }770 let existingUser = await User.findOne({771 "auth.linkedin.id": profile.id772 });773 if (existingUser) {774 // need to refresh token775 existingUser.auth.linkedin.accessToken = accessToken;776 existingUser.auth.linkedin.refreshToken = refreshToken;777 existingUser.lastActive = Date.now();778 let sessionId = uuid();779 existingUser.userSession = sessionId;780 781 let newSession = genSession(sessionId);782 newSession.email = existingUser.email;783 newSession.ip = req.headers["x-forwarded-for"] || req.ip;784 newSession.startTime = Date.now();785 newSession.platform = "linkedin";786 await newSession.save();787 await existingUser.save();788 return done(null, existingUser);789 }790 if (profile.emails == undefined || profile.emails == null) {791 return done(792 "no email-id not associated with this social account",793 null,794 "no email-id not associated with this social account"795 );796 }797 if (profile.emails.length > 0) {798 const linkEmail = await User.findOne({799 email: profile.emails[0].value800 });801 if (linkEmail) {802 linkEmail.auth.linkedin.id = profile.id;803 linkEmail.auth.linkedin.accessToken = accessToken;804 linkEmail.auth.linkedin.refreshToken = refreshToken;805 linkEmail.lastActive = Date.now();806 let sessionId = uuid();807 linkEmail.userSession = sessionId;808 let newSession = genSession(sessionId);809 newSession.email = linkEmail.email;810 newSession.ip = req.headers["x-forwarded-for"] || req.ip;811 newSession.startTime = Date.now();812 newSession.platform = "linkedin";813 await newSession.save();814 await linkEmail.save();815 return done(null, linkEmail);816 }817 }818 let existingUser2 = await User.findOne({819 email: profile.emails[0].value820 });821 if (existingUser2) {822 let user = await User.findOne({ email: profile.emails[0].value });823 user.auth.linkedin.id = profile.id;824 user.auth.linkedin.accessToken = accessToken;825 user.auth.linkedin.refreshToken = refreshToken;826 user.lastActive = Date.now();827 let sessionId = uuid();828 user.userSession = sessionId;829 830 let newSession = genSession(sessionId);831 newSession.email = user.email;832 newSession.ip = req.headers["x-forwarded-for"] || req.ip;833 newSession.startTime = Date.now();834 newSession.platform = "linkedin";835 await newSession.save();836 await user.save();837 return done(null, user);838 }839 newUser = newDefaultUser();840 newUser.auth.linkedin.id = profile.id;841 newUser.name = formatName(profile.displayName);842 newUser.email = profile.emails[0].value;843 newUser.auth.linkedin.accessToken = accessToken;844 newUser.created = Date.now();845 newUser.lastActive = Date.now();846 let sessionId = uuid();847 newUser.userSession = sessionId;848 849 let newSession = genSession(sessionId);850 newSession.email = newUser.email;851 newSession.ip = req.headers["x-forwarded-for"] || req.ip;852 newSession.startTime = Date.now();853 newSession.platform = "linkedin";854 await newSession.save(); 855 await newUser.save();856 socialPostListener.emit("varTriggerUpdate", "registrations");857 done(null, newUser, "new-name");858 });859 }860 )861 );862};863function validateEmail(email) {864 var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;865 return { valid: re.test(email) };866}867function validatePWD(pwd) {868 let upperCaseLetters = /[A-Z]/g;869 let numbers = /[0-9]/g;870 let validPWD = false;871 let msg;872 if (!pwd.match(numbers)) {873 msg = "Atleast One Number";874 }875 if (!pwd.match(upperCaseLetters)) {876 msg = "Atlest One Uppercase";877 }878 if (pwd.length < 8) {879 msg = "Atlest 8 characters";880 }881 if (pwd.match(numbers) && pwd.match(numbers) && pwd.length >= 8) {882 validPWD = true;883 msg = null;884 }885 return { msg: msg, valid: validPWD };886}887function validateName(name) {888 let validFN = true;889 let onlyWhiteSpace = "^\\s+$";890 let anyWhitespace = ".*\\s.*";891 let onlyLetter = "^[a-zA-Z]+$";892 let msg;893 if (!name.match(onlyLetter)) {894 msg = "name should consist of only letters";895 validFN = false;896 }897 if (name.match(onlyWhiteSpace) || name.match(anyWhitespace)) {898 // Has a whitespace899 msg = "no space allowed in first-name";900 validFN = false;901 }902 if (name.length < 2) {903 msg = "name too short";904 validFN = false;905 }906 if (name.length > 20) {907 msg = "name too long";908 validFN = false;909 }910 return { msg: msg, valid: validFN };911}912function formatName(fullName) {913 const lowerFN = fullName.toLowerCase();914 const splitFN = lowerFN.split(" ");915 let formattedName = "";916 for (name of splitFN) {917 formattedName += name.charAt(0).toUpperCase() + name.slice(1) + " ";918 }919 const finalFN = formattedName.trim();920 return finalFN;921}922function genSession(id){923 return new UserSession({924 sessionId: id,925 email: '',926 startTime: '',927 endTime: '',928 ip: '',929 platform:''930 })931}932function validateRefId(refId) {933 if (refId.length===15 && refId.startsWith("bd-")){934 return true;935 }936 return false...
index.test.js
Source:index.test.js
1const request = require('supertest');2const {3 testContent, testCYATemplate, testExistenceCYA,4 testErrors, testRedirect5} = require('test/util/assertions');6const { withSession } = require('test/util/setup');7const moment = require('moment');8const server = require('app');9const idamMock = require('test/mocks/idam');10const { removeStaleData } = require('app/core/helpers/staleDataManager');11const { expect } = require('test/util/chai');12const { clone } = require('lodash');13const modulePath = 'app/steps/grounds-for-divorce/separation-date';14const content = require(`${modulePath}/content`);15let s = {};16let agent = {};17let underTest = {};18describe(modulePath, () => {19 beforeEach(() => {20 idamMock.stub();21 s = server.init();22 agent = request.agent(s.app);23 underTest = s.steps.SeparationDate;24 });25 afterEach(() => {26 idamMock.restore();27 });28 describe('success', () => {29 let session = {};30 beforeEach(done => {31 session = {32 divorceWho: 'wife',33 marriageDate: '2001-02-02T00:00:00.000Z',34 reasonForDivorce: 'separation-2-years'35 };36 withSession(done, agent, session);37 });38 it('renders the content from the content file', done => {39 testContent(done, agent, underTest, content, session);40 });41 it('renders errors for missing required context', done => {42 const context = {};43 const onlyKeys = ['reasonForDivorceSeperationDate'];44 testErrors(done, agent, underTest, context,45 content, 'required', onlyKeys, session);46 });47 it('renders error for missing day', done => {48 const context = {49 reasonForDivorceSeperationDay: '',50 reasonForDivorceSeperationMonth: '2',51 reasonForDivorceSeperationYear: '2000'52 };53 testErrors(done, agent, underTest, context, content, 'day.required');54 });55 it('renders error for missing month', done => {56 const context = {57 reasonForDivorceSeperationDay: '1',58 reasonForDivorceSeperationMonth: '',59 reasonForDivorceSeperationYear: '2000'60 };61 testErrors(done, agent, underTest, context, content, 'month.required');62 });63 it('renders error for missing year', done => {64 const context = {65 reasonForDivorceSeperationDay: '1',66 reasonForDivorceSeperationMonth: '2',67 reasonForDivorceSeperationYear: ''68 };69 testErrors(done, agent, underTest, context, content, 'year.required');70 });71 it('renders error for invalid date', done => {72 const context = {73 reasonForDivorceSeperationDay: '31',74 reasonForDivorceSeperationMonth: '2',75 reasonForDivorceSeperationYear: '2013'76 };77 testErrors(done, agent, underTest, context,78 content, 'reasonForDivorceSeperationDate.invalid');79 });80 it('renders error for future date', done => {81 const reasonForDivorceSeperationDateInFuture = moment().add(1, 'years');82 const context = {83 reasonForDivorceSeperationDay:84 reasonForDivorceSeperationDateInFuture.date(),85 reasonForDivorceSeperationMonth:86 reasonForDivorceSeperationDateInFuture.month() + 1,87 reasonForDivorceSeperationYear:88 reasonForDivorceSeperationDateInFuture.year()89 };90 testErrors(done, agent, underTest, context,91 content, 'reasonForDivorceSeperationDateInFuture.invalid');92 });93 it('renders error for "before marriage date"', done => {94 const reasonForDivorceSeperationDateBeforeMarriage = moment(95 session.marriageDate96 ).subtract(1, 'years');97 const context = {98 reasonForDivorceSeperationDay:99 reasonForDivorceSeperationDateBeforeMarriage.date(),100 reasonForDivorceSeperationMonth:101 reasonForDivorceSeperationDateBeforeMarriage.month(),102 reasonForDivorceSeperationYear:103 reasonForDivorceSeperationDateBeforeMarriage.year()104 };105 testErrors(done, agent, underTest, context,106 content, 'reasonForDivorceSeperationDateBeforeMarriageDate.invalid');107 });108 });109 describe('success (separation-2-years)', () => {110 let session = {};111 beforeEach(done => {112 session = {113 divorceWho: 'wife',114 marriageDate: '2001-02-02T00:00:00.000Z',115 reasonForDivorce: 'separation-2-years'116 };117 withSession(done, agent, session);118 });119 it('redirects to the next page when separation date is before 2 years ago', done => {120 const context = {121 reasonForDivorceSeperationDay: '01',122 reasonForDivorceSeperationMonth: '01',123 reasonForDivorceSeperationYear: '2015'124 };125 testRedirect(done, agent, underTest, context, s.steps.LegalProceedings);126 });127 it('redirects to the exit page when separation date is after 2 years ago', done => {128 const date1YearAgo = moment().subtract(1, 'years');129 const context = {130 reasonForDivorceSeperationDay: date1YearAgo.date(),131 reasonForDivorceSeperationMonth: date1YearAgo.month() + 1,132 reasonForDivorceSeperationYear: date1YearAgo.year()133 };134 testRedirect(done, agent, underTest, context, s.steps.ExitSeparation);135 });136 });137 describe('success (separation-5-years)', () => {138 let session = {};139 beforeEach(done => {140 session = {141 divorceWho: 'wife',142 marriageDate: '2001-02-02T00:00:00.000Z',143 reasonForDivorce: 'separation-5-years'144 };145 withSession(done, agent, session);146 });147 it('redirects to the next page when separation date is before 5 years ago', done => {148 const context = {149 reasonForDivorceSeperationDay: '01',150 reasonForDivorceSeperationMonth: '01',151 reasonForDivorceSeperationYear: '2010'152 };153 testRedirect(done, agent, underTest, context, s.steps.LegalProceedings);154 });155 it('redirects to the exit page when separation date is after 5 years ago', done => {156 const FOUR_YEARS = 4;157 const date1YearAgo = moment().subtract(FOUR_YEARS, 'years');158 const context = {159 reasonForDivorceSeperationDay: date1YearAgo.date(),160 reasonForDivorceSeperationMonth: date1YearAgo.month() + 1,161 reasonForDivorceSeperationYear: date1YearAgo.year()162 };163 testRedirect(done, agent, underTest, context, s.steps.ExitSeparation);164 });165 });166 describe('Watched session values', () => {167 it('removes context if reasonForDivorce is not seperation-2-years', () => {168 const previousSession = {169 reasonForDivorce: 'seperation-2-years',170 reasonForDivorceSeperationDay: '1',171 reasonForDivorceSeperationMonth: '1',172 reasonForDivorceSeperationYear: '2010',173 reasonForDivorceSeperationDate: 'date',174 reasonForDivorceSeperationDateIsSameOrAfterLimitDate: true,175 reasonForDivorceSeperationDateInFuture: true,176 reasonForDivorceSeperationDateBeforeMarriageDate: true177 };178 const session = clone(previousSession);179 session.reasonForDivorce = 'adultery';180 const newSession = removeStaleData(previousSession, session);181 expect(typeof newSession.reasonForDivorceSeperationDay)182 .to.equal('undefined');183 expect(typeof newSession.reasonForDivorceSeperationMonth)184 .to.equal('undefined');185 expect(typeof newSession.reasonForDivorceSeperationYear)186 .to.equal('undefined');187 expect(typeof newSession.reasonForDivorceSeperationDate)188 .to.equal('undefined');189 expect(typeof newSession.reasonForDivorceSeperationDateIsSameOrAfterLimitDate) // eslint-disable-line max-len190 .to.equal('undefined');191 expect(typeof newSession.reasonForDivorceSeperationDateInFuture)192 .to.equal('undefined');193 expect(typeof newSession.reasonForDivorceSeperationDateBeforeMarriageDate)194 .to.equal('undefined');195 });196 it('removes context if reasonForDivorce is not seperation-5-years', () => {197 const previousSession = {198 reasonForDivorce: 'seperation-5-years',199 reasonForDivorceSeperationDay: '1',200 reasonForDivorceSeperationMonth: '1',201 reasonForDivorceSeperationYear: '2010',202 reasonForDivorceSeperationDate: 'date',203 reasonForDivorceSeperationDateIsSameOrAfterLimitDate: true,204 reasonForDivorceSeperationDateInFuture: true,205 reasonForDivorceSeperationDateBeforeMarriageDate: true206 };207 const session = clone(previousSession);208 session.reasonForDivorce = 'adultery';209 const newSession = removeStaleData(previousSession, session);210 expect(typeof newSession.reasonForDivorceSeperationDay)211 .to.equal('undefined');212 expect(typeof newSession.reasonForDivorceSeperationMonth)213 .to.equal('undefined');214 expect(typeof newSession.reasonForDivorceSeperationYear)215 .to.equal('undefined');216 expect(typeof newSession.reasonForDivorceSeperationDate)217 .to.equal('undefined');218 expect(typeof newSession.reasonForDivorceSeperationDateIsSameOrAfterLimitDate) // eslint-disable-line max-len219 .to.equal('undefined');220 expect(typeof newSession.reasonForDivorceSeperationDateInFuture)221 .to.equal('undefined');222 expect(typeof newSession.reasonForDivorceSeperationDateBeforeMarriageDate)223 .to.equal('undefined');224 });225 it('does not remove context if reasonForDivorce is set to seperation-2-years', () => {226 const previousSession = {227 reasonForDivorce: 'seperation-5-years',228 reasonForDivorceSeperationDay: '1',229 reasonForDivorceSeperationMonth: '1',230 reasonForDivorceSeperationYear: '2010',231 reasonForDivorceSeperationDate: 'date',232 reasonForDivorceSeperationDateIsSameOrAfterLimitDate: true,233 reasonForDivorceSeperationDateInFuture: true,234 reasonForDivorceSeperationDateBeforeMarriageDate: true235 };236 const session = clone(previousSession);237 session.reasonForDivorce = 'separation-2-years';238 const newSession = removeStaleData(previousSession, session);239 expect(newSession.reasonForDivorce).to.equal('separation-2-years');240 expect(newSession.reasonForDivorceSeperationDay)241 .to.equal(previousSession.reasonForDivorceSeperationDay);242 expect(newSession.reasonForDivorceSeperationMonth)243 .to.equal(previousSession.reasonForDivorceSeperationMonth);244 expect(newSession.reasonForDivorceSeperationYear)245 .to.equal(previousSession.reasonForDivorceSeperationYear);246 expect(newSession.reasonForDivorceSeperationDate)247 .to.equal(previousSession.reasonForDivorceSeperationDate);248 expect(newSession.reasonForDivorceSeperationDateIsSameOrAfterLimitDate)249 .to.equal(250 previousSession.reasonForDivorceSeperationDateIsSameOrAfterLimitDate251 );252 expect(newSession.reasonForDivorceSeperationDateInFuture)253 .to.equal(previousSession.reasonForDivorceSeperationDateInFuture);254 expect(newSession.reasonForDivorceSeperationDateBeforeMarriageDate)255 .to.equal(256 previousSession.reasonForDivorceSeperationDateBeforeMarriageDate257 );258 });259 it('does not remove context if reasonForDivorce is set to seperation-5-years', () => {260 const previousSession = {261 reasonForDivorce: 'seperation-2-years',262 reasonForDivorceSeperationDay: '1',263 reasonForDivorceSeperationMonth: '1',264 reasonForDivorceSeperationYear: '2010',265 reasonForDivorceSeperationDate: 'date',266 reasonForDivorceSeperationDateIsSameOrAfterLimitDate: true,267 reasonForDivorceSeperationDateInFuture: true,268 reasonForDivorceSeperationDateBeforeMarriageDate: true269 };270 const session = clone(previousSession);271 session.reasonForDivorce = 'separation-5-years';272 const newSession = removeStaleData(previousSession, session);273 expect(newSession.reasonForDivorce).to.equal('separation-5-years');274 expect(newSession.reasonForDivorceSeperationDay)275 .to.equal(previousSession.reasonForDivorceSeperationDay);276 expect(newSession.reasonForDivorceSeperationMonth)277 .to.equal(previousSession.reasonForDivorceSeperationMonth);278 expect(newSession.reasonForDivorceSeperationYear)279 .to.equal(previousSession.reasonForDivorceSeperationYear);280 expect(newSession.reasonForDivorceSeperationDate)281 .to.equal(previousSession.reasonForDivorceSeperationDate);282 expect(newSession.reasonForDivorceSeperationDateIsSameOrAfterLimitDate)283 .to.equal(284 previousSession.reasonForDivorceSeperationDateIsSameOrAfterLimitDate285 );286 expect(newSession.reasonForDivorceSeperationDateInFuture)287 .to.equal(previousSession.reasonForDivorceSeperationDateInFuture);288 expect(newSession.reasonForDivorceSeperationDateBeforeMarriageDate)289 .to.equal(290 previousSession.reasonForDivorceSeperationDateBeforeMarriageDate291 );292 });293 });294 describe('Check Your Answers', () => {295 it('renders the cya template', done => {296 testCYATemplate(done, underTest);297 });298 it('renders reason for divorce seperation date', done => {299 const contentToExist = ['question'];300 const valuesToExist = ['reasonForDivorceSeperationDate'];301 const context = {302 reasonForDivorceSeperationDay: '10',303 reasonForDivorceSeperationMonth: '10',304 reasonForDivorceSeperationYear: '2010',305 reasonForDivorceSeperationDate: '10th October 2010'306 };307 testExistenceCYA(done, underTest, content,308 contentToExist, valuesToExist, context);309 });310 });...
nextSession.js
Source:nextSession.js
1const Discord = require('discord.js');2const Session = require('../Session.js');3const client = new Discord.Client();4const schedulingTest = '750746205667197048';5module.exports = {6 name: 'nextsession',7 description: 'this command schedules next session (???)',8 execute(message, args) {9 let isMe = message.author.id === '455826573594198016';10 if (isMe) {11 var newSession = new Session.Session();12 var newDate = new Date(args);13 let isValidDate = function (date) {14 return date instanceof Date && !isNaN(date);15 }16 if (isValidDate(newDate)) {17 newSession.date = newDate;18 } else {19 var today = new Date();20 today.setHours(11, 00, 00)21 for (let i = 0; i < 7; i++) {22 if (today.getDay() === 0) {23 break;24 } else {25 today.setDate(today.getDate() + 1);26 }27 }28 newSession.date = today;29 }30 let newEmbed = function (session) {31 var rsvpd;32 var noRsvpd;33 if (session.goodPlayers.length === 0) {34 rsvpd = '\u200b';35 } else {36 rsvpd = session.goodPlayers.map(user => {37 return user;38 });39 }40 if (session.badPlayers.length === 0) {41 noRsvpd = '\u200b';42 } else {43 noRsvpd = session.badPlayers.map(user => {44 return user;45 })46 }47 let embed = new Discord.MessageEmbed()48 .setColor(0x1D82B6)49 .setTitle("**NEXT TIME ON DUNGEONS AND DRAGONS**")50 .addFields(51 {52 name: ':calendar_spiral: **Dungeons and Dragons**',53 value: '\u200b'54 },55 {56 name: '**Time**',57 value: `${session.date.toDateString().substring(0, 11)}, ${session.date.toTimeString().substring(0, 5)}`,58 },59 {60 name: `:white_check_mark: **Attendees:** (${session.goodPlayers.length})`,61 value: rsvpd62 },63 {64 name: `â **Can't come:** (${session.badPlayers.length})`,65 value: noRsvpd66 },67 {68 name: '\u200b',69 value: 'Click on the :white_check_mark: or the â reaction below to get that sweet sweet XP!'70 }71 )72 return embed;73 }74 message.client.db = newSession;75 message.channel.messages.fetch(true)76 .then(async function (messages) {77 messages.forEach(message => {78 if (message.pinned) {79 message.delete()80 }81 })82 })83 message.channel.send(newEmbed(newSession))84 .then(async function (message) {85 message.pin()86 await message.react('â
')87 await message.react('â')88 const filter = (reaction, user) => {89 return user.bot === false && (reaction.emoji.name === 'â
' || reaction.emoji.name === 'â');90 };91 const collector = message.createReactionCollector(filter, { dispose: true });92 collector.on('collect', (reaction, reactionCollector) => {93 reaction.users.cache.map(user => {94 if (user.bot === false && reaction.emoji.name === 'â
') {95 if (newSession.badPlayers.includes(user)) {96 alreadyRSVP(user, reaction, newEmbed);97 // console.log('this player is on the bad list')98 // newSession.removeBadPlayer(user)99 // console.log(reaction.message.reactions.cache.get('â').users)100 // const userReactions = reaction.message.reactions.cache.filter(reaction => reaction.users.cache.has(user.id));101 // try {102 // for (const reaction of userReactions.values()) {103 // reaction.users.remove(user.id);104 // newSession.addGoodPlayer(user)105 // reaction.message.edit(newEmbed(newSession));106 // }107 // } catch (error) {108 // console.log('failed to remove reaction')109 // }110 } else if (newSession.goodPlayers.includes(user)) {111 return;112 } else {113 newSession.addGoodPlayer(user)114 reaction.message.edit(newEmbed(newSession));115 }116 } else if (user.bot === false && reaction.emoji.name === 'â') {117 if (newSession.goodPlayers.includes(user)) {118 alreadyRSVP(user, reaction, newEmbed)119 // console.log('this player is on the good list')120 // newSession.removeGoodPlayer(user)121 // reaction.message.reactions.cache.get('â
').users.remove(user)122 // const userReactions = reaction.message.reactions.cache.filter(reaction => reaction.users.cache.has(user.id));123 // try {124 // for (const reaction of userReactions.values()) {125 // reaction.users.remove(user.id);126 // newSession.addGoodPlayer(user)127 // reaction.message.edit(newEmbed(newSession));128 // }129 // } catch (error) {130 // console.log('failed to remove reaction')131 // }132 } else if (newSession.badPlayers.includes(user)) {133 return;134 } else {135 newSession.addBadPlayer(user)136 reaction.message.edit(newEmbed(newSession));137 }138 }139 })140 reaction.client.db = newSession;141 })142 collector.on('remove', (reaction, user) => {143 if (reaction.emoji.name === 'â
') {144 for (let i = 0; i < newSession.goodPlayers.length; i++) {145 if (newSession.goodPlayers[i].id === user.id) {146 newSession.removeGoodPlayer(user);147 reaction.message.edit(newEmbed(newSession));148 }149 }150 } else if (reaction.emoji.name === 'â') {151 for (let i = 0; i < newSession.badPlayers.length; i++) {152 if (newSession.badPlayers[i].id === user.id) {153 newSession.removeBadPlayer(user);154 reaction.message.edit(newEmbed(newSession));155 }156 }157 }158 message.client.db = newSession;159 })160 })161 } else {162 session = message.client.db;163 message.channel.send(`Our next session is currently being planned for ${session.date}! Hope you can make it.`)164 }165 const alreadyRSVP = function (user, reaction, func) {166 console.log('this player has already RSVPd')167 const reactionList = reaction.message.reactions;168 if (reaction.emoji.name === 'â') {169 newSession.removeGoodPlayer(user)170 const oldReaction = reactionList.cache.get('â
').users;171 oldReaction.remove(user)172 newSession.addBadPlayer(user)173 } else if (reaction.emoji.name === 'â
') {174 newSession.removeBadPlayer(user)175 const oldReaction = reactionList.cache.get('â').users;176 oldReaction.remove(user)177 newSession.addGoodPlayer(user)178 }179 reaction.message.edit(func(newSession))180 }181 }...
App.js
Source:App.js
...27 this.setState({28 viewId:2,29 });30 }31 newSession(){32 this.setState({33 newSession:!this.state.newSession34 });35 console.log(this.state.newSession);36 }37 setView(viewIdFromChild) {38 //console.log({this.props.viewId});39 this.setState({viewId:viewIdFromChild});40 }41 render() {42 console.ignoredYellowBox = ['Remote debugger'];43 if (this.state.newSession) {44 return(45 <View style={styles.container}>...
EShell.js
Source:EShell.js
1import SocketIO from '../socketio/SocketIO'2class EShell {3 constructor() {4 this.uniqueSessionId = 05 this.sessions = []6 this.sendQueues = {}7 }8 createSession({ namespace='eshell', data }={}) {9 const newSession = {10 sessionId: this.uniqueSessionId++,11 input: inputFunction => newSession.input = inputFunction, // Crazy, but it works...12 output: data => this.send({ session: newSession, data }),13 onWindowSizeChanged: (cols, rows) => this.send({ channel: 'term_size', session: newSession, data: {cols, rows} }),14 connected: false,15 isRdy: false,16 emit: data => this.send({ session: newSession, data }),17 connect: () => this.connectSession(newSession, namespace, data),18 disconnect: () => this.disconnectSession(newSession),19 remove: () => this.removeSession(newSession),20 }21 this.sessions = [...this.sessions, newSession]22 return newSession23 }24 removeSession(session) {25 this.disconnectSession(session)26 const sessionId = this.sessions.indexOf(session)27 this.sessions = [28 ...this.sessions.slice(0, sessionId),29 ...this.sessions.slice(sessionId + 1)30 ]31 }32 connectSession(session, namespace='eshell', data) {33 const socket = SocketIO({ namespace, query: {type: 'user'} })34 session.socket = socket35 socket.on('connect', () => {36 socket.emit('authenticate', {userId: data.userId, deviceId: data.deviceId})37 socket.on('authenticated', () => {38 session.connected = true39 socket.on('rdy', data => {40 for (const [key, value] of Object.entries(data)) {41 session[key] = value42 }43 44 session.isRdy = true45 if (this.sendQueues.hasOwnProperty(session)) {46 this.sendQueues[session].forEach(([ channel, data ]) => this.send({ channel, session, data }))47 delete this.sendQueues[session]48 }49 })50 51 socket.on('msg', data => session.input(data))52 })53 })54 return session.socket55 }56 disconnectSession(session) {57 session.socket.disconnect()58 }59 send({ channel='cmd', session, data }) {60 if (session.connected && session.isRdy) {61 session.socket.emit(channel, data)62 }63 else {64 this.sendQueues.hasOwnProperty(session)65 ? this.sendQueues[session].push([channel, data])66 : this.sendQueues[session] = [[channel, data]]67 }68 }69}...
UserData.js
Source:UserData.js
1class UserData {2 constructor(session){3 if (session === undefined) {4 this.session = {};5 } else {6 this.session = session;7 }8 this.error = (this.session.error === undefined) ? 0 : this.session.error;9 this.token = (this.session.token === undefined) ? 0 : this.session.token;10 this.id = (this.session.id === undefined) ? 0 : this.session.id;11 this.pwd = (this.session.pwd === undefined) ? 0 : this.session.pwd; 12 this.firstName = (this.session.firstName === undefined) ? 0 : this.session.firstName;13 this.lastName = (this.session.lastName === undefined) ? 0 : this.session.lastName;14 this.dailycal = (this.session.dailycal === undefined) ? 0 : this.session.dailycal; 15 this.dailycarbo = (this.session.dailycarbo === undefined) ? 0 : this.session.dailycarbo; 16 this.dailyprotein = (this.session.dailyprotein === undefined) ? 0 : this.session.dailyprotein; 17 this.dailyfat = (this.session.dailyfat === undefined) ? 0 : this.session.dailyfat; 18 this.dailyactivity = (this.session.dailyactivity === undefined) ? 0 : this.session.dailyactivity; 19 }20 updateSession(newSession){21 22 this.token = (this.newSession.token === undefined) ? this.session.token: newSession.token;23 this.id = (this.newSession.id === undefined) ? this.session.id: newSession.id;24 this.pwd = (this.newSession.pwd === undefined) ? this.session.pwd : newSession.id;25 this.firstName = (this.newSession.firstName === undefined) ? this.session.firstName : newSession.firstName;26 this.lastName = (this.newSession.lastName === undefined) ? this.session.lastName : newSession.lastName;27 this.dailycal = (this.newSession.dailycal === undefined) ? this.session.dailycal : newSession.dailycal; 28 this.dailycarbo = (this.newSession.dailycarbo === undefined) ? this.session.dailycarbo : newSession.dailycarbo; 29 this.dailyprotein = (this.newSession.dailyprotein === undefined) ? this.session.dailyprotein : newSession.dailyprotein; 30 this.dailyfat = (this.newSession.dailyfat === undefined) ? this.session.dailyfat : newSession.dailyfat; 31 this.dailyactivity = (this.newSession.dailyactivity === undefined) ? this.session.dailyactivity: newSession.dailyactivity; 32 return this;33 }34}...
session.controller.js
Source:session.controller.js
1'use strict';2export default class {3 /*@ngInject*/4 constructor($http, $filter) {5 this.$http = $http;6 this.$filter = $filter;7 this.showNotes = false;8 }9 $onInit() {10 this.inf = true;11 this.newSession = {12 instances: 0,13 duration: 60,14 color: 'blue',15 frequency: 716 };17 this.$http.get('/api/students')18 .then(response => {19 this.students = [];20 response.data.forEach(student => {21 if (student.isActive)22 this.students.push(student);23 });24 });25 this.$http.get('/api/tutors')26 .then(response => {27 this.tutors = response.data;28 });29 this.colors = ['blue', 'orange', 'red', 'purple', 'grey', 'green', 'yellow', 'lime'];30 }31 returnFilter(results, $query) {32 return results.filter(function (item) {33 if (item.isActive === false) {34 return false;35 }36 return item.fullName.toLowerCase().indexOf($query.toLowerCase()) != -1;37 })38 }39 changeDuration(duration) {40 this.newSession.duration = duration;41 if (duration === 30) {42 console.log('showing notes...')43 this.showNotes = true;44 }45 }46 submit(data, callback) {47 if (!this.selectedStudent || !this.selectedTutor || !data) {48 this.error = 'Incomplete form or front-end bug. Refresh browser.';49 return;50 }51 this.newSession.startTime = data.startTime;52 this.newSession.room = data.room;53 this.newSession.location = data.location;54 this.newSession.date = this.$filter('date')(data.date, 'dd/MM/yyyy');55 this.newSession.clientUID = this.selectedStudent[0]._id;56 this.newSession.tutorUID = this.selectedTutor[0]._id;57 if (this.newSession._changeover === 'present') {58 this.newSession.changeover = true;59 }60 if (this.newSession._changeover === 'one off') {61 this.newSession.overwriteChangeover = { 0: true };62 }63 //if one off, set instances to 164 if (!this.newSession.frequency)65 this.newSession.instances = 1;66 //if not a one off and infinite, set instances to 067 if (this.newSession.frequency && this.inf)68 this.newSession.instances = 0;69 //(implied) if not inf then allow the instances to pass70 this.$http.post('/api/lessons', this.newSession)71 .then(res => {72 this.error = '';73 callback({ reason: 'success', data: res.data });74 })75 .catch(res => {76 console.log(res);77 this.error = JSON.stringify(res.data, null, '\t');78 });79 }...
Session.js
Source:Session.js
1const con = require("../config/db");2const uuid4 = require("uuid4");3class Session {4 constructor(id, projectId, name, date, start, end, description) {5 this.id = id;6 this.projectId = projectId;7 this.name = name;8 this.date = date;9 this.start = start;10 this.end = end;11 this.description = description;12 this.created_at = new Date();13 }14}15module.exports = {16 Session,17 // create new member by user or by admin18 create: async function (body, result) {19 const newSession = new Session(uuid4(), body.session.project_id, body.session.name, body.session.date, body.session.start, body.session.end, body.session.description);20 const sql = `INSERT INTO sessions (id, projects_id, name, date, start, end, description, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;21 con.query(sql, [newSession.id, newSession.projectId, newSession.name, newSession.date, newSession.start, newSession.end, newSession.description, newSession.created_at], (err, res) => {22 if (err) {23 result(err, null);24 return;25 }26 result(null, newSession);27 return;28 });29 },30 find: async function (projectId, result) {31 const sql = `SELECT * FROM sessions WHERE projects_id = ?`;32 con.query(sql, [projectId], (err, res) => {33 if (err) {34 result(err, null);35 return;36 }37 result(null, res);38 return;39 });40 },41 findOne: async function (id, result) {42 const sql = `SELECT * FROM sessions WHERE id = ?`;43 con.query(sql, [id], (err, res) => {44 if (err) {45 result(err, null);46 return;47 }48 result(null, res);49 return;50 });51 }...
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6 .remote(options)7 .init()8 .getTitle().then(function(title) {9 console.log('Title was: ' + title);10 })11 .end();
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6 .remote(options)7 .init()8 .getTitle().then(function(title) {9 console.log('Title was: ' + title);10 })11 .end();12var webdriverio = require('webdriverio');13var options = {14 desiredCapabilities: [{15 }, {16 }]17};18 .remote(options)19 .init()20 .getTitle().then(function(title) {21 console.log('Title was: ' + title);22 })23 .end();24var webdriverio = require('webdriverio');25var options = {26 desiredCapabilities: [{27 }, {28 }]29};30 .remote(options)31 .init()32 .getTitle().then(function(title) {33 console.log('Title was: ' + title);34 })35 .end();
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6 .remote(options)7 .init()8 .getTitle().then(function(title) {9 console.log('Title was: ' + title);10 })11 .end();12 1 passing (1.9s)13 OK. 1 assertions passed. (1.9s)14Your name to display (optional):15Your name to display (optional):
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6 .remote(options)7 .init()8 .getTitle().then(function(title) {9 console.log('Title was: ' + title);10 })11 .end();12var selenium = require('selenium-standalone');13var webdriver = require('selenium-webdriver');14var driver;15selenium.start(function(err, child) {16 driver = new webdriver.Builder().usingServer(child).withCapabilities({17 }).build();18 driver.getTitle().then(function(title) {19 console.log('Title was: ' + title);20 });21 driver.quit();22 selenium.child.kill();23});
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6 .remote(options)7 .init()8 .getTitle().then(function(title) {9 console.log('Title was: ' + title);10 })11 .end();12var webdriverio = require('webdriverio');13var options = {14 desiredCapabilities: {15 }16};17 .remote(options)18 .init()19 .getTitle().then(function(title) {20 console.log('Title was: ' + title);21 })22 .end();23var webdriverio = require('webdriverio');24var options = {25 desiredCapabilities: {26 }27};28 .remote(options)29 .init()30 .getTitle().then(function(title) {31 console.log('Title was: ' + title);32 })33 .end();34var webdriverio = require('webdriverio');35var options = {36 desiredCapabilities: {37 }38};39 .remote(options)40 .init()41 .getTitle().then(function(title) {42 console.log('Title was: ' + title);43 })44 .end();45var webdriverio = require('webdriverio');46var options = {47 desiredCapabilities: {48 }49};50 .remote(options)51 .init()
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = { desiredCapabilities: { browserName: 'chrome' } };3var client = webdriverio.remote(options);4 .init()5 .getTitle().then(function(title) {6 console.log('Title was: ' + title);7 })8 .end();9var wd = require('wd');10 .init({browserName:'chrome'})11 .title()12 .then(function(title) {13 console.log('Title was: ' + title);14 })15 .quit();
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6var client = webdriverio.remote(options);7 .init()8 .newSession('firefox')9 .getTitle().then(function(title) {10 console.log('Title was: ' + title);11 })12 .end();
Using AI Code Generation
1var webdriverio = require('webdriverio');2var client = webdriverio.remote({3 desiredCapabilities: {4 }5});6 .init()7 .getTitle().then(function(title) {8 console.log('Title was: ' + title);9 })10 .end();11var webdriver = require('selenium-webdriver');12var driver = new webdriver.Builder()13 .forBrowser('chrome')14 .build();15driver.getTitle().then(function(title) {16 console.log('Title was: ' + title);17});18driver.quit();19exports.command = function(callback) {20 this.requestHandler.create(21 {},22 );23 return this;24};25function RequestHandler(options) {26 this.options = options;27 this.sessionID = null;28 this.queue = Promise.resolve();29}30RequestHandler.prototype.create = function(path, data, callback) {31 var self = this;32 this.queue = this.queue.then(function() {33 return self._create(path, data, callback);34 });35 return this.queue;36};37RequestHandler.prototype._create = function(path, data, callback) {38 var self = this;39 return new Promise(function(resolve, reject) {40 var requestOptions = {41 };42 if (self.sessionID) {43 requestOptions.path = '/session/' + self.sessionID + path;44 }45 requestOptions.data = data;46 self._request(requestOptions, function(err, res) {47 if (err) {48 return reject(err);49 }
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 browser.newSession();4 });5});6exports.config = {7 capabilities: [{8 }],9 jasmineNodeOpts: {10 expectationResultHandler: function(passed, assertion) {11 }12 },13 before: function (capabilities, specs) {14 require('@babel/register');15 }16}17describe('My First Test', function() {18 it('Does not do much!', function() {19 browser.newSession();20 });21});22exports.config = {23 capabilities: [{24 }],25 jasmineNodeOpts: {26 expectationResultHandler: function(passed, assertion) {27 }28 },29 before: function (capabilities, specs) {30 require('@babel/register');31 }32}
Wondering what could be a next-gen browser and mobile test automation framework that is also simple and concise? Yes, that’s right, it's WebdriverIO. Since the setup is very easy to follow compared to Selenium testing configuration, you can configure the features manually thereby being the center of attraction for automation testing. Therefore the testers adopt WedriverIO to fulfill their needs of browser testing.
Learn to run automation testing with WebdriverIO tutorial. Go from a beginner to a professional automation test expert with LambdaTest WebdriverIO tutorial.
Running Your First Automation Script - Learn the steps involved to execute your first Test Automation Script using WebdriverIO since the setup is very easy to follow and the features can be configured manually.
Selenium Automation With WebdriverIO - Read more about automation testing with WebdriverIO and how it supports both browsers and mobile devices.
Browser Commands For Selenium Testing - Understand more about the barriers faced while working on your Selenium Automation Scripts in WebdriverIO, the ‘browser’ object and how to use them?
Handling Alerts & Overlay In Selenium - Learn different types of alerts faced during automation, how to handle these alerts and pops and also overlay modal in WebdriverIO.
How To Use Selenium Locators? - Understand how Webdriver uses selenium locators in a most unique way since having to choose web elements very carefully for script execution is very important to get stable test results.
Deep Selectors In Selenium WebdriverIO - The most popular automation testing framework that is extensively adopted by all the testers at a global level is WebdriverIO. Learn how you can use Deep Selectors in Selenium WebdriverIO.
Handling Dropdown In Selenium - Learn more about handling dropdowns and how it's important while performing automated browser testing.
Automated Monkey Testing with Selenium & WebdriverIO - Understand how you can leverage the amazing quality of WebdriverIO along with selenium framework to automate monkey testing of your website or web applications.
JavaScript Testing with Selenium and WebdriverIO - Speed up your Javascript testing with Selenium and WebdriverIO.
Cross Browser Testing With WebdriverIO - Learn more with this step-by-step tutorial about WebdriverIO framework and how cross-browser testing is done with WebdriverIO.
Get 100 minutes of automation test minutes FREE!!