Best JavaScript code snippet using jest
passport.js
Source:passport.js
1const passport = require('passport');2const request = require('request');3const InstagramStrategy = require('passport-instagram').Strategy;4const LocalStrategy = require('passport-local').Strategy;5const FacebookStrategy = require('passport-facebook').Strategy;6const TwitterStrategy = require('passport-twitter').Strategy;7const GitHubStrategy = require('passport-github').Strategy;8const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;9const LinkedInStrategy = require('passport-linkedin-oauth2').Strategy;10const OpenIDStrategy = require('passport-openid').Strategy;11const OAuthStrategy = require('passport-oauth').OAuthStrategy;12const OAuth2Strategy = require('passport-oauth').OAuth2Strategy;13const User = require('../models/User');14passport.serializeUser((user, done) => {15 done(null, user.id);16});17passport.deserializeUser((id, done) => {18 User.findById(id, (err, user) => {19 done(err, user);20 });21});22/**23 * Sign in using Email and Password.24 */25passport.use(new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {26 User.findOne({ email: email.toLowerCase() }, (err, user) => {27 if (err) { return done(err); }28 if (!user) {29 return done(null, false, { msg: `Email ${email} not found.` });30 }31 user.comparePassword(password, (err, isMatch) => {32 if (err) { return done(err); }33 if (isMatch) {34 return done(null, user);35 }36 return done(null, false, { msg: 'Invalid email or password.' });37 });38 });39}));40/**41 * OAuth Strategy Overview42 *43 * - User is already logged in.44 * - Check if there is an existing account with a provider id.45 * - If there is, return an error message. (Account merging not supported)46 * - Else link new OAuth account with currently logged-in user.47 * - User is not logged in.48 * - Check if it's a returning user.49 * - If returning user, sign in and we are done.50 * - Else check if there is an existing account with user's email.51 * - If there is, return an error message.52 * - Else create a new account.53 */54/**55 * Sign in with Facebook.56 */57passport.use(new FacebookStrategy({58 clientID: process.env.FACEBOOK_ID,59 clientSecret: process.env.FACEBOOK_SECRET,60 callbackURL: '/auth/facebook/callback',61 profileFields: ['name', 'email', 'link', 'locale', 'timezone'],62 passReqToCallback: true63}, (req, accessToken, refreshToken, profile, done) => {64 if (req.user) {65 User.findOne({ facebook: profile.id }, (err, existingUser) => {66 if (err) { return done(err); }67 if (existingUser) {68 req.flash('errors', { msg: 'There is already a Facebook account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });69 done(err);70 } else {71 User.findById(req.user.id, (err, user) => {72 if (err) { return done(err); }73 user.facebook = profile.id;74 user.tokens.push({ kind: 'facebook', accessToken });75 user.profile.name = user.profile.name || `${profile.name.givenName} ${profile.name.familyName}`;76 user.profile.gender = user.profile.gender || profile._json.gender;77 user.profile.picture = user.profile.picture || `https://graph.facebook.com/${profile.id}/picture?type=large`;78 user.save((err) => {79 req.flash('info', { msg: 'Facebook account has been linked.' });80 done(err, user);81 });82 });83 }84 });85 } else {86 User.findOne({ facebook: profile.id }, (err, existingUser) => {87 if (err) { return done(err); }88 if (existingUser) {89 return done(null, existingUser);90 }91 User.findOne({ email: profile._json.email }, (err, existingEmailUser) => {92 if (err) { return done(err); }93 if (existingEmailUser) {94 req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with Facebook manually from Account Settings.' });95 done(err);96 } else {97 const user = new User();98 user.email = profile._json.email;99 user.facebook = profile.id;100 user.tokens.push({ kind: 'facebook', accessToken });101 user.profile.name = `${profile.name.givenName} ${profile.name.familyName}`;102 user.profile.gender = profile._json.gender;103 user.profile.picture = `https://graph.facebook.com/${profile.id}/picture?type=large`;104 user.profile.location = (profile._json.location) ? profile._json.location.name : '';105 user.save((err) => {106 done(err, user);107 });108 }109 });110 });111 }112}));113/**114 * Sign in with GitHub.115 */116passport.use(new GitHubStrategy({117 clientID: process.env.GITHUB_ID,118 clientSecret: process.env.GITHUB_SECRET,119 callbackURL: '/auth/github/callback',120 passReqToCallback: true121}, (req, accessToken, refreshToken, profile, done) => {122 if (req.user) {123 User.findOne({ github: profile.id }, (err, existingUser) => {124 if (existingUser) {125 req.flash('errors', { msg: 'There is already a GitHub account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });126 done(err);127 } else {128 User.findById(req.user.id, (err, user) => {129 if (err) { return done(err); }130 user.github = profile.id;131 user.tokens.push({ kind: 'github', accessToken });132 user.profile.name = user.profile.name || profile.displayName;133 user.profile.picture = user.profile.picture || profile._json.avatar_url;134 user.profile.location = user.profile.location || profile._json.location;135 user.profile.website = user.profile.website || profile._json.blog;136 user.save((err) => {137 req.flash('info', { msg: 'GitHub account has been linked.' });138 done(err, user);139 });140 });141 }142 });143 } else {144 User.findOne({ github: profile.id }, (err, existingUser) => {145 if (err) { return done(err); }146 if (existingUser) {147 return done(null, existingUser);148 }149 User.findOne({ email: profile._json.email }, (err, existingEmailUser) => {150 if (err) { return done(err); }151 if (existingEmailUser) {152 req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with GitHub manually from Account Settings.' });153 done(err);154 } else {155 const user = new User();156 user.email = profile._json.email;157 user.github = profile.id;158 user.tokens.push({ kind: 'github', accessToken });159 user.profile.name = profile.displayName;160 user.profile.picture = profile._json.avatar_url;161 user.profile.location = profile._json.location;162 user.profile.website = profile._json.blog;163 user.save((err) => {164 done(err, user);165 });166 }167 });168 });169 }170}));171// Sign in with Twitter.172passport.use(new TwitterStrategy({173 consumerKey: process.env.TWITTER_KEY,174 consumerSecret: process.env.TWITTER_SECRET,175 callbackURL: '/auth/twitter/callback',176 passReqToCallback: true177}, (req, accessToken, tokenSecret, profile, done) => {178 if (req.user) {179 User.findOne({ twitter: profile.id }, (err, existingUser) => {180 if (err) { return done(err); }181 if (existingUser) {182 req.flash('errors', { msg: 'There is already a Twitter account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });183 done(err);184 } else {185 User.findById(req.user.id, (err, user) => {186 if (err) { return done(err); }187 user.twitter = profile.id;188 user.tokens.push({ kind: 'twitter', accessToken, tokenSecret });189 user.profile.name = user.profile.name || profile.displayName;190 user.profile.location = user.profile.location || profile._json.location;191 user.profile.picture = user.profile.picture || profile._json.profile_image_url_https;192 user.save((err) => {193 if (err) { return done(err); }194 req.flash('info', { msg: 'Twitter account has been linked.' });195 done(err, user);196 });197 });198 }199 });200 } else {201 User.findOne({ twitter: profile.id }, (err, existingUser) => {202 if (err) { return done(err); }203 if (existingUser) {204 return done(null, existingUser);205 }206 const user = new User();207 // Twitter will not provide an email address. Period.208 // But a personâs twitter username is guaranteed to be unique209 // so we can "fake" a twitter email address as follows:210 user.email = `${profile.username}@twitter.com`;211 user.twitter = profile.id;212 user.tokens.push({ kind: 'twitter', accessToken, tokenSecret });213 user.profile.name = profile.displayName;214 user.profile.location = profile._json.location;215 user.profile.picture = profile._json.profile_image_url_https;216 user.save((err) => {217 done(err, user);218 });219 });220 }221}));222/**223 * Sign in with Google.224 */225passport.use(new GoogleStrategy({226 clientID: process.env.GOOGLE_ID,227 clientSecret: process.env.GOOGLE_SECRET,228 callbackURL: '/auth/google/callback',229 passReqToCallback: true230}, (req, accessToken, refreshToken, profile, done) => {231 if (req.user) {232 User.findOne({ google: profile.id }, (err, existingUser) => {233 if (err) { return done(err); }234 if (existingUser) {235 req.flash('errors', { msg: 'There is already a Google account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });236 done(err);237 } else {238 User.findById(req.user.id, (err, user) => {239 if (err) { return done(err); }240 user.google = profile.id;241 user.tokens.push({ kind: 'google', accessToken });242 user.profile.name = user.profile.name || profile.displayName;243 user.profile.gender = user.profile.gender || profile._json.gender;244 user.profile.picture = user.profile.picture || profile._json.image.url;245 user.save((err) => {246 req.flash('info', { msg: 'Google account has been linked.' });247 done(err, user);248 });249 });250 }251 });252 } else {253 User.findOne({ google: profile.id }, (err, existingUser) => {254 if (err) { return done(err); }255 if (existingUser) {256 return done(null, existingUser);257 }258 User.findOne({ email: profile.emails[0].value }, (err, existingEmailUser) => {259 if (err) { return done(err); }260 if (existingEmailUser) {261 req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with Google manually from Account Settings.' });262 done(err);263 } else {264 const user = new User();265 user.email = profile.emails[0].value;266 user.google = profile.id;267 user.tokens.push({ kind: 'google', accessToken });268 user.profile.name = profile.displayName;269 user.profile.gender = profile._json.gender;270 user.profile.picture = profile._json.image.url;271 user.save((err) => {272 done(err, user);273 });274 }275 });276 });277 }278}));279/**280 * Sign in with LinkedIn.281 */282passport.use(new LinkedInStrategy({283 clientID: process.env.LINKEDIN_ID,284 clientSecret: process.env.LINKEDIN_SECRET,285 callbackURL: process.env.LINKEDIN_CALLBACK_URL,286 scope: ['r_basicprofile', 'r_emailaddress'],287 passReqToCallback: true288}, (req, accessToken, refreshToken, profile, done) => {289 if (req.user) {290 User.findOne({ linkedin: profile.id }, (err, existingUser) => {291 if (err) { return done(err); }292 if (existingUser) {293 req.flash('errors', { msg: 'There is already a LinkedIn account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });294 done(err);295 } else {296 User.findById(req.user.id, (err, user) => {297 if (err) { return done(err); }298 user.linkedin = profile.id;299 user.tokens.push({ kind: 'linkedin', accessToken });300 user.profile.name = user.profile.name || profile.displayName;301 user.profile.location = user.profile.location || profile._json.location.name;302 user.profile.picture = user.profile.picture || profile._json.pictureUrl;303 user.profile.website = user.profile.website || profile._json.publicProfileUrl;304 user.save((err) => {305 if (err) { return done(err); }306 req.flash('info', { msg: 'LinkedIn account has been linked.' });307 done(err, user);308 });309 });310 }311 });312 } else {313 User.findOne({ linkedin: profile.id }, (err, existingUser) => {314 if (err) { return done(err); }315 if (existingUser) {316 return done(null, existingUser);317 }318 User.findOne({ email: profile._json.emailAddress }, (err, existingEmailUser) => {319 if (err) { return done(err); }320 if (existingEmailUser) {321 req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with LinkedIn manually from Account Settings.' });322 done(err);323 } else {324 const user = new User();325 user.linkedin = profile.id;326 user.tokens.push({ kind: 'linkedin', accessToken });327 user.email = profile._json.emailAddress;328 user.profile.name = profile.displayName;329 user.profile.location = profile._json.location.name;330 user.profile.picture = profile._json.pictureUrl;331 user.profile.website = profile._json.publicProfileUrl;332 user.save((err) => {333 done(err, user);334 });335 }336 });337 });338 }339}));340/**341 * Sign in with Instagram.342 */343passport.use(new InstagramStrategy({344 clientID: process.env.INSTAGRAM_ID,345 clientSecret: process.env.INSTAGRAM_SECRET,346 callbackURL: '/auth/instagram/callback',347 passReqToCallback: true348}, (req, accessToken, refreshToken, profile, done) => {349 if (req.user) {350 User.findOne({ instagram: profile.id }, (err, existingUser) => {351 if (err) { return done(err); }352 if (existingUser) {353 req.flash('errors', { msg: 'There is already an Instagram account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });354 done(err);355 } else {356 User.findById(req.user.id, (err, user) => {357 if (err) { return done(err); }358 user.instagram = profile.id;359 user.tokens.push({ kind: 'instagram', accessToken });360 user.profile.name = user.profile.name || profile.displayName;361 user.profile.picture = user.profile.picture || profile._json.data.profile_picture;362 user.profile.website = user.profile.website || profile._json.data.website;363 user.save((err) => {364 req.flash('info', { msg: 'Instagram account has been linked.' });365 done(err, user);366 });367 });368 }369 });370 } else {371 User.findOne({ instagram: profile.id }, (err, existingUser) => {372 if (err) { return done(err); }373 if (existingUser) {374 return done(null, existingUser);375 }376 const user = new User();377 user.instagram = profile.id;378 user.tokens.push({ kind: 'instagram', accessToken });379 user.profile.name = profile.displayName;380 // Similar to Twitter API, assigns a temporary e-mail address381 // to get on with the registration process. It can be changed later382 // to a valid e-mail address in Profile Management.383 user.email = `${profile.username}@instagram.com`;384 user.profile.website = profile._json.data.website;385 user.profile.picture = profile._json.data.profile_picture;386 user.save((err) => {387 done(err, user);388 });389 });390 }391}));392/**393 * Tumblr API OAuth.394 */395passport.use('tumblr', new OAuthStrategy({396 requestTokenURL: 'http://www.tumblr.com/oauth/request_token',397 accessTokenURL: 'http://www.tumblr.com/oauth/access_token',398 userAuthorizationURL: 'http://www.tumblr.com/oauth/authorize',399 consumerKey: process.env.TUMBLR_KEY,400 consumerSecret: process.env.TUMBLR_SECRET,401 callbackURL: '/auth/tumblr/callback',402 passReqToCallback: true403},404 (req, token, tokenSecret, profile, done) => {405 User.findById(req.user._id, (err, user) => {406 if (err) { return done(err); }407 user.tokens.push({ kind: 'tumblr', accessToken: token, tokenSecret });408 user.save((err) => {409 done(err, user);410 });411 });412 }413));414/**415 * Foursquare API OAuth.416 */417passport.use('foursquare', new OAuth2Strategy({418 authorizationURL: 'https://foursquare.com/oauth2/authorize',419 tokenURL: 'https://foursquare.com/oauth2/access_token',420 clientID: process.env.FOURSQUARE_ID,421 clientSecret: process.env.FOURSQUARE_SECRET,422 callbackURL: process.env.FOURSQUARE_REDIRECT_URL,423 passReqToCallback: true424},425 (req, accessToken, refreshToken, profile, done) => {426 User.findById(req.user._id, (err, user) => {427 if (err) { return done(err); }428 user.tokens.push({ kind: 'foursquare', accessToken });429 user.save((err) => {430 done(err, user);431 });432 });433 }434));435/**436 * Steam API OpenID.437 */438passport.use(new OpenIDStrategy({439 apiKey: process.env.STEAM_KEY,440 providerURL: 'http://steamcommunity.com/openid',441 returnURL: 'http://localhost:3000/auth/steam/callback',442 realm: 'http://localhost:3000/',443 stateless: true444}, (identifier, done) => {445 const steamId = identifier.match(/\d+$/)[0];446 const profileURL = `http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=${process.env.STEAM_KEY}&steamids=${steamId}`;447 User.findOne({ steam: steamId }, (err, existingUser) => {448 if (err) { return done(err); }449 if (existingUser) return done(err, existingUser);450 request(profileURL, (error, response, body) => {451 if (!error && response.statusCode === 200) {452 const data = JSON.parse(body);453 const profile = data.response.players[0];454 const user = new User();455 user.steam = steamId;456 user.email = `${steamId}@steam.com`; // steam does not disclose emails, prevent duplicate keys457 user.tokens.push({ kind: 'steam', accessToken: steamId });458 user.profile.name = profile.personaname;459 user.profile.picture = profile.avatarmedium;460 user.save((err) => {461 done(err, user);462 });463 } else {464 done(error, null);465 }466 });467 });468}));469/**470 * Pinterest API OAuth.471 */472passport.use('pinterest', new OAuth2Strategy({473 authorizationURL: 'https://api.pinterest.com/oauth/',474 tokenURL: 'https://api.pinterest.com/v1/oauth/token',475 clientID: process.env.PINTEREST_ID,476 clientSecret: process.env.PINTEREST_SECRET,477 callbackURL: process.env.PINTEREST_REDIRECT_URL,478 passReqToCallback: true479},480 (req, accessToken, refreshToken, profile, done) => {481 User.findById(req.user._id, (err, user) => {482 if (err) { return done(err); }483 user.tokens.push({ kind: 'pinterest', accessToken });484 user.save((err) => {485 done(err, user);486 });487 });488 }489));490/**491 * Login Required middleware.492 */493exports.isAuthenticated = (req, res, next) => {494 if (req.isAuthenticated()) {495 return next();496 }497 res.redirect('/login');498};499/**500 * Authorization Required middleware.501 */502exports.isAuthorized = (req, res, next) => {503 const provider = req.path.split('/').slice(-1)[0];504 const token = req.user.tokens.find(token => token.kind === provider);505 if (token) {506 next();507 } else {508 res.redirect(`/auth/${provider}`);509 }...
api.js
Source:api.js
...59//60// api.get('/watsonjson', function(req, res){61// // console.log("Triggered Waton API route.")62// // console.log(req.body.text)63// personality_insights.profile({ text: my_profile },64// function (err, profile) {65// if (err) throw err66// res.json(profile)67// });68// })69//WATSON TESTING END//70api.post('/watson', function(req, res){71 console.log("Triggered Waton API route.")72 console.log(req.body.text)73 personality_insights.profile({ text: req.body.text },74 function (err, profile) {75 if (err) throw err76 var newProfile = new Profile()77 //saving text input78 newProfile.textInput = req.body.text79 //saving big 5 personality trait data80 newProfile.big5personality.openness = profile.tree.children[0].children[0].children[0].percentage81 newProfile.big5personality.conscientiousness = profile.tree.children[0].children[0].children[1].percentage82 newProfile.big5personality.extraversion = profile.tree.children[0].children[0].children[2].percentage83 newProfile.big5personality.agreeableness = profile.tree.children[0].children[0].children[3].percentage84 newProfile.big5personality.emotionalRange = profile.tree.children[0].children[0].children[4].percentage85 //big 5 subcategory openness86 newProfile.opennessBreakdown.adventurousness = profile.tree.children[0].children[0].children[0].children[0].percentage87 newProfile.opennessBreakdown.artisticInterests = profile.tree.children[0].children[0].children[0].children[1].percentage...
EditProfile.js
Source:EditProfile.js
1import React, { Component } from "react";2import { connect } from "react-redux";3import { withRouter } from "react-router-dom";4import PropTypes from "prop-types";5import TextFieldGroup from "../common/TextFieldGroup";6import TextAreaFieldGroup from "../common/TextAreaFieldGroup";7import InputGroup from "../common/InputGroup";8import SelectListGroup from "../common/SelectListGroup";9import { createProfile, getCurrentProfile } from "../../actions/profileActions";10import isEmpty from "../../validation/is-empty";11class CreateProfile extends Component {12 constructor(props) {13 super(props);14 this.state = {15 displaySocialInputs: false,16 handle: "",17 company: "",18 website: "",19 location: "",20 status: "",21 skills: "",22 githubusername: "",23 bio: "",24 twitter: "",25 facebook: "",26 linkedin: "",27 youtube: "",28 instagram: "",29 errors: {}30 };31 }32 componentDidMount() {33 this.props.getCurrentProfile();34 }35 componentWillReceiveProps(nextProps) {36 if (nextProps.errors) {37 this.setState({ errors: nextProps.errors });38 }39 if (nextProps.profile.profile) {40 const profile = nextProps.profile.profile;41 // Bring skills array back to comma separated values42 // ERROR Cannot read property 'join' of undefined which means profile.skills is undefined43 //const skillsCSV = profile.skills.join(",");44 // If profile field doesn't exist, make empty string45 profile.company = !isEmpty(profile.company) ? profile.company : "";46 profile.website = !isEmpty(profile.website) ? profile.website : "";47 profile.location = !isEmpty(profile.location) ? profile.location : "";48 profile.githubusername = !isEmpty(profile.githubusername)49 ? profile.githubusername50 : "";51 profile.bio = !isEmpty(profile.bio) ? profile.bio : "";52 profile.social = !isEmpty(profile.social) ? profile.social : {};53 profile.facebook = !isEmpty(profile.social.facebook)54 ? profile.social.facebook55 : "";56 profile.instagram = !isEmpty(profile.social.instagram)57 ? profile.social.instagram58 : "";59 profile.linkedin = !isEmpty(profile.social.linkedin)60 ? profile.social.linkedin61 : "";62 profile.youtube = !isEmpty(profile.social.youtube)63 ? profile.social.youtube64 : "";65 profile.twitter = !isEmpty(profile.social.twitter)66 ? profile.social.twitter67 : "";68 // Set component fields state69 this.setState({70 handle: profile.handle,71 company: profile.company,72 website: profile.website,73 location: profile.location,74 status: profile.status,75 //skills: skillsCSV,76 githubusername: profile.githubusername,77 bio: profile.bio,78 twitter: profile.twitter,79 facebook: profile.facebook,80 linkedin: profile.linkedin,81 youtube: profile.youtube,82 instagram: profile.instagram83 });84 }85 }86 onSubmit = e => {87 e.preventDefault();88 //console.log("submit");89 const profileData = {90 handle: this.state.handle,91 company: this.state.company,92 website: this.state.website,93 location: this.state.location,94 status: this.state.status,95 skills: this.state.skills,96 githubusername: this.state.githubusername,97 bio: this.state.bio,98 twitter: this.state.twitter,99 facebook: this.state.facebook,100 linkedin: this.state.linkedin,101 youtube: this.state.youtube,102 instagram: this.state.instagram103 };104 this.props.createProfile(profileData, this.props.history);105 };106 onChange = e => {107 this.setState({ [e.target.name]: e.target.value });108 };109 render() {110 const { errors, displaySocialInputs } = this.state;111 let socialInputs;112 if (displaySocialInputs) {113 socialInputs = (114 <div>115 <InputGroup116 placeholder="Twitter profile"117 name="twitter"118 icon="fab fa-twitter"119 value={this.state.twitter}120 onChange={this.onChange}121 error={errors.twitter}122 />123 <InputGroup124 placeholder="Linkedin profile"125 name="linkedin"126 icon="fab fa-linkedin"127 value={this.state.linkedin}128 onChange={this.onChange}129 error={errors.linkedin}130 />131 <InputGroup132 placeholder="Youtube profile"133 name="youtube"134 icon="fab fa-youtube"135 value={this.state.youtube}136 onChange={this.onChange}137 error={errors.youtube}138 />139 <InputGroup140 placeholder="Instagram profile"141 name="instagram"142 icon="fab fa-instagram"143 value={this.state.instagram}144 onChange={this.onChange}145 error={errors.instagram}146 />147 <InputGroup148 placeholder="Facebook profile"149 name="facebook"150 icon="fab fa-facebook"151 value={this.state.facebook}152 onChange={this.onChange}153 error={errors.facebook}154 />155 </div>156 );157 }158 // Select options for status159 const options = [160 { label: "* Select investor profile", value: 0 },161 {162 label: "Getting started: want to learn",163 value: "Getting started: and want to learn"164 },165 {166 label: "Passive: want to let kari take care of everything",167 value: "Passive: want to let kari take care of everything"168 },169 {170 label: "Active: want to have more control on your investments",171 value: "Active: want to have more control on your investments"172 }173 ];174 return (175 <div className="create-profile">176 <div className="container">177 <div className="row">178 <div className="col-md-8 m-auto">179 <h1 className="display-4 text-center">Edit your profile</h1>180 <small className="d-block pb-3">*required fields</small>181 <form onSubmit={this.onSubmit}>182 <TextFieldGroup183 placeholder="* Username"184 name="handle"185 value={this.state.handle}186 onChange={this.onChange}187 error={errors.handle}188 info="a unique username for your profile"189 />190 <SelectListGroup191 placeholder="* Investment style"192 name="status"193 value={this.state.status}194 onChange={this.onChange}195 options={options}196 error={errors.status}197 info="Give us an idea of your investment style"198 />199 <TextFieldGroup200 placeholder="Company"201 name="company"202 value={this.state.company}203 onChange={this.onChange}204 error={errors.company}205 info="Employment details"206 />207 <TextFieldGroup208 placeholder="Company Website"209 name="website"210 value={this.state.website}211 onChange={this.onChange}212 error={errors.website}213 info="Company Website address"214 />215 <TextFieldGroup216 placeholder="Country"217 name="location"218 value={this.state.location}219 onChange={this.onChange}220 error={errors.location}221 info="Country of residence"222 />223 <TextFieldGroup224 placeholder="*Investments to date"225 name="skills"226 value={this.state.skills}227 onChange={this.onChange}228 error={errors.skills}229 info="Please use comma separated e.g. Facebook shares, US Government bonds"230 />231 <TextFieldGroup232 placeholder="Education Level"233 name="githubusername"234 value={this.state.githubusername}235 onChange={this.onChange}236 error={errors.githubusername}237 info="Highest education qualification"238 />239 <TextAreaFieldGroup240 placeholder="Investment objectives"241 name="bio"242 value={this.state.bio}243 onChange={this.onChange}244 error={errors.bio}245 info="Tell us what your investment goals are e.g. saving for retirement or child education fund"246 />247 <div className="mb-3">248 <button249 type="button"250 onClick={() => {251 this.setState(prevState => ({252 displaySocialInputs: !prevState.displaySocialInputs253 }));254 }}255 className="btn btn-light"256 >257 Add Social Network258 </button>259 <span className="text-muted">Optional</span>260 </div>261 {socialInputs}262 <input263 type="submit"264 value="Submit"265 className="btn btn-info btn-block mt-4 submitbutton"266 />267 </form>268 </div>269 </div>270 </div>271 </div>272 );273 }274}275CreateProfile.propTypes = {276 createProfile: PropTypes.func.isRequired,277 getCurrentProfile: PropTypes.func.isRequired,278 profile: PropTypes.object.isRequired,279 errors: PropTypes.object.isRequired280};281const mapStateToProps = state => ({282 profile: state.profile,283 errors: state.errors284});285export default connect(286 mapStateToProps,287 { createProfile, getCurrentProfile }...
profile.js
Source:profile.js
1const express = require("express");2const router = express.Router();3const mongoose = require("mongoose");4const passport = require("passport");5// Load Validation6const validateProfileInput = require("../../validation/profile");7const validateExperienceInput = require("../../validation/experience");8const validateEducationInput = require("../../validation/education");9// Load Profile model10const Profile = require("../../models/Profile");11// Load User model12const User = require("../../models/User");13// route will go to /api/profile/....14// @route GET api/profile/test15// @desc Tests profile route16// @access Public17router.get("/test", (req, res) => res.json({ msg: "Profile works" }));18// @route GET api/profile19// @desc Get current users profile20// @access Private21router.get(22 "/",23 passport.authenticate("jwt", { session: false }),24 (req, res) => {25 const errors = {};26 Profile.findOne({ user: req.user.id })27 .populate("user", ["name", "avatar"])28 .then(profile => {29 if (!profile) {30 errors.noprofile = "There is no profile for this user";31 return res.status(404).json(errors);32 }33 res.json(profile);34 })35 .catch(err => res.status(404).json(err));36 }37);38// @route GET api/profile/all39// @desc Get all profiles40// @access Public41router.get("/all", (req, res) => {42 Profile.find()43 .populate("user", ["name", "avatar"])44 .then(profiles => {45 if (!profiles) {46 rrors.noprofile = "There is no profiles";47 return res.status(404).json(errors);48 }49 res.json(profiles);50 })51 .catch(err => res.status(404).json({ profile: "There are no profiles" }));52});53// @route GET api/profile/handle/:handle54// @desc Get profile by handle55// @access Public56router.get("/handle/:handle", (req, res) => {57 const errors = {};58 Profile.findOne({ handle: req.params.handle })59 .populate("user", ["name", "avatar"])60 .then(profile => {61 if (!profile) {62 errors.noprofile = "There is no profile for this user";63 return res.status(404).json(errors);64 }65 res.json(profile);66 })67 .catch(err => res.status(404).json(err));68});69// @route GET api/profile/user/:user_id70// @desc Get profile by ID71// @access Public72router.get("/user/:user_id", (req, res) => {73 const errors = {};74 Profile.findOne({ user: req.params.user_id })75 .populate("user", ["name", "avatar"])76 .then(profile => {77 if (!profile) {78 errors.noprofile = "There is no profile for this user";79 return res.status(404).json(errors);80 }81 res.json(profile);82 })83 .catch(err =>84 res.status(404).json({ profile: "There is no profile for this user" })85 );86});87// @route POST api/profile88// @desc Create or Edit user profile89// @access Private90router.post(91 "/",92 passport.authenticate("jwt", { session: false }),93 (req, res) => {94 const { errors, isValid } = validateProfileInput(req.body);95 // Check Validation96 if (!isValid) {97 return res.status(400).json(errors);98 }99 // Get fields100 const profileFields = {};101 profileFields.user = req.user.id;102 if (req.body.handle) profileFields.handle = req.body.handle;103 if (req.body.company) profileFields.company = req.body.company;104 if (req.body.website) profileFields.website = req.body.website;105 if (req.body.location) profileFields.location = req.body.location;106 if (req.body.bio) profileFields.bio = req.body.bio;107 if (req.body.status) profileFields.status = req.body.status;108 if (req.body.githubusername)109 profileFields.githubusername = req.body.githubusername;110 // Skills - split into array111 if (typeof req.body.skills !== "undefined") {112 profileFields.skills = req.body.skills.split(",");113 }114 // Social115 profileFields.social = {};116 if (req.body.youtube) profileFields.social.youtube = req.body.youtube;117 if (req.body.twitter) profileFields.social.twitter = req.body.twitter;118 if (req.body.facebook) profileFields.social.facebook = req.body.facebook;119 if (req.body.linkedin) profileFields.social.linkedin = req.body.linkedin;120 if (req.body.instagram) profileFields.social.instagram = req.body.instagram;121 Profile.findOne({ user: req.user.id }).then(profile => {122 if (profile) {123 // Update124 Profile.findOneAndUpdate(125 { user: req.user.id },126 { $set: profileFields },127 { new: true }128 ).then(profile => res.json(profile));129 } else {130 // Create131 // Check if handle exists132 Profile.findOne({ handle: profileFields.handle }).then(profile => {133 if (profile) {134 errors.handle = "That handle already exists";135 res.status(400).json(errors);136 }137 // Save Profile138 new Profile(profileFields).save().then(profile => res.json(profile));139 });140 }141 });142 }143);144// @route POST api/profile/experience145// @desc Add experience to profile146// @access Private147router.post(148 "/experience",149 passport.authenticate("jwt", { session: false }),150 (req, res) => {151 const { errors, isValid } = validateExperienceInput(req.body);152 // Check Validation153 if (!isValid) {154 return res.status(400).json(errors);155 }156 Profile.findOne({ user: req.user.id }).then(profile => {157 const newExp = {158 title: req.body.title,159 company: req.body.company,160 location: req.body.location,161 from: req.body.from,162 to: req.body.to,163 current: req.body.current,164 description: req.body.description165 };166 // Add to exp Array167 profile.experience.unshift(newExp);168 profile.save().then(profile => res.json(profile));169 });170 }171);172// @route POST api/profile/education173// @desc Add education to profile174// @access Private175router.post(176 "/education",177 passport.authenticate("jwt", { session: false }),178 (req, res) => {179 const { errors, isValid } = validateEducationInput(req.body);180 // Check Validation181 if (!isValid) {182 return res.status(400).json(errors);183 }184 Profile.findOne({ user: req.user.id }).then(profile => {185 const newEdu = {186 school: req.body.school,187 degree: req.body.degree,188 fieldofstudy: req.body.fieldofstudy,189 from: req.body.from,190 to: req.body.to,191 current: req.body.current,192 description: req.body.description193 };194 // Add to exp Array195 profile.education.unshift(newEdu);196 profile.save().then(profile => res.json(profile));197 });198 }199);200// @route DELETE api/profile/experience/:exp_id201// @desc Add experience to profile202// @access Private203router.delete(204 "/experience/:exp_id",205 passport.authenticate("jwt", { session: false }),206 (req, res) => {207 Profile.findOne({ user: req.user.id })208 .then(profile => {209 // Get remove index210 const removeIndex = profile.experience211 .map(item => item.id)212 .indexOf(req.params.exp_id);213 // Splice out of array214 profile.experience.splice(removeIndex, 1);215 // Save216 profile.save().then(profile => res.json(profile));217 })218 .catch(err => res.status(404).json(err));219 }220);221// @route DELETE api/profile/education/:edu_id222// @desc Add education to profile223// @access Private224router.delete(225 "/education/:edu_id",226 passport.authenticate("jwt", { session: false }),227 (req, res) => {228 Profile.findOne({ user: req.user.id })229 .then(profile => {230 // Get remove index231 const removeIndex = profile.education232 .map(item => item.id)233 .indexOf(req.params.edu_id);234 // Splice out of array235 profile.education.splice(removeIndex, 1);236 // Save237 profile.save().then(profile => res.json(profile));238 })239 .catch(err => res.status(404).json(err));240 }241);242// @route DELETE api/profile/243// @desc Delete User and Profile244// @access Private245router.delete(246 "/",247 passport.authenticate("jwt", { session: false }),248 (req, res) => {249 Profile.findOneAndRemove({ user: req.user.id }).then(() => {250 User.findOneAndRemove({ _id: req.user.id }).then(() =>251 res.json({ sucess: true })252 );253 });254 }255);...
ProfileRound.js
Source:ProfileRound.js
1export default class ProfileRound {2 3 /**4 * timeoutId used for the debounce5 * 6 * @type {number}7 */8 timer = null9 /**10 * Profile marked "is me" that must be in the bottom center11 * 12 * @type {Profile}13 */14 myProfile = null15 /**16 * Create new ProfileRound object17 * 18 * @param {HTMLElement} round The element container for the round19 * @param {number} duration The duration in ms (/10 frames) for animations20 * @param {Arrow} arrow Arrow object for pointing the active profile21 * @param {Array.<Profile>} profiles Profiles to add to the round immediatly22 */23 constructor (round, duration = 400, arrow = null, profiles = []) {24 this.round = round25 this.duration = duration26 this.arrow = arrow27 this.profiles = []28 profiles.forEach(profile => this.addProfile(profile))29 this.showProfiles(profiles)30 this.align()31 }32 /**33 * Get profiles marked as invisible34 * 35 * @returns {Array.<Profile>}36 */37 getInvisibleProfiles () {38 return this.profiles.filter(profile => !profile.visible)39 }40 /**41 * Get profiles marked as visible42 * 43 * @returns {Array.<Profile>}44 */45 getVisibleProfiles () {46 return this.profiles.filter(profile => profile.visible)47 }48 /**49 * Set the profile active, add the class `active` to the element and point it with the arrow (if defined)50 * 51 * @param {Profile|undefined} profile The profile to set active or undefined to unset active profile52 */53 setActive (profile = undefined) {54 if (this.activeProfile !== undefined) this.activeProfile.element.classList.remove('active')55 this.activeProfile = profile56 if (this.activeProfile !== undefined) this.activeProfile.element.classList.add('active')57 if (this.activeProfile !== undefined && this.arrow !== null) {58 this.arrow.show()59 this.arrow.setMove(this.activeProfile.targetAngle, this.duration / 20)60 this.arrow.anime()61 } else if (this.arrow !== null) {62 this.arrow.hide()63 }64 }65 /**66 * Get the angle of a profile by its index67 * 68 * @param {number} index Index of the profile in the profiles array69 * @returns {number}70 */71 getAngle (index) {72 index = index - this.profiles.findIndex(profile => profile === this.myProfile)73 if (index < 0) index += this.profiles.length74 return index * (Math.PI*2) / this.profiles.length75 }76 /**77 * Add a profile to the round78 * 79 * @param {Profile} profile Profile to add to the round80 */81 addProfile (profile) {82 const profilesVisibles = this.getVisibleProfiles().length83 if (profile.isMe) {84 if (this.myProfile !== null) this.myProfile.isMe = false85 this.myProfile = profile86 this.profiles.forEach(eachProfile => { eachProfile.hide(this.duration, () => this.align())})87 }88 if (isNaN(profile.position)) {89 profile.position = this.profiles.length+190 this.profiles.push(profile)91 } else {92 this.profiles.splice(profile.position, 0, profile)93 }94 const child = profile.element95 const after = this.profiles.filter(eachProfile => this.round.contains(eachProfile.element)).find(eachProfile => eachProfile.position >= profile.position)96 this.round.insertBefore(child, after !== undefined ? after.element : null)97 if (!profile.isMe || profilesVisibles < 2) this.align()98 }99 /**100 * Remove a profile in the round101 * 102 * @param {Profile} profile Profile to remove from the round103 */104 removeProfile (profile) {105 const removeElement = () => {106 this.round.removeChild(profile.element)107 this.profiles.splice(this.profiles.findIndex(eachProfile => eachProfile === profile), 1)108 this.align()109 }110 profile.hide(this.duration, removeElement)111 if (profile === this.myProfile) {112 this.myProfile = null113 this.profiles.forEach(theProfile => theProfile.hide(this.duration))114 }115 }116 /**117 * Show each profiles118 * 119 * @param {Array.<Profile>} profiles Profiles to show120 */121 showProfiles (profiles) {122 profiles.forEach(profile => profile.show(this.duration))123 }124 /**125 * Set the angles of the profiles in the round and animate them126 */127 align () {128 const addedProfiles = this.getInvisibleProfiles()129 this.profiles.forEach((profile, index) => {130 profile.setMove(this.getAngle(index), this.duration / 10)131 const animationEnd = () => {132 if (profile.currentAngle !== profile.targetAngle || this.profiles.length <= 2) this.timer = setTimeout(() => this.showProfiles(addedProfiles), 2)133 }134 clearTimeout(this.timer)135 profile.anime(animationEnd)136 if (profile === this.activeProfile && this.arrow !== null) {137 this.arrow.setMove(this.getAngle(index), this.duration / 10)138 this.arrow.anime()139 }140 })141 }...
profile-settings.controller.js
Source:profile-settings.controller.js
1/**2* ProfileSettingsController3* @namespace iupds.profiles.controllers4*/5(function () {6 'use strict';7 angular8 .module('iupds.profiles.controllers')9 .controller('ProfileSettingsController', ProfileSettingsController);10 ProfileSettingsController.$inject = [11 '$location', '$routeParams', 'Authentication', 'Profile', 'Snackbar'12 ];13 /**14 * @namespace ProfileSettingsController15 */16 function ProfileSettingsController($location, $routeParams, Authentication, Profile, Snackbar) {17 var vm = this;18 vm.destroy = destroy;19 vm.update = update;20 activate();21 /**22 * @name activate23 * @desc Actions to be performed when this controller is instantiated.24 * @memberOf iupds.profiles.controllers.ProfileSettingsController25 */26 function activate() {27 var authenticatedAccount = Authentication.getAuthenticatedAccount();28 var username = $routeParams.username.substr(1);29 // Redirect if not logged in30 if (!authenticatedAccount) {31 $location.url('/');32 Snackbar.error('You are not authorized to view this page.');33 } else {34 // Redirect if logged in, but not the owner of this profile.35 if (authenticatedAccount.username !== username) {36 $location.url('/');37 Snackbar.error('You are not authorized to view this page.');38 }39 }40 Profile.get(username).then(profileSuccessFn, profileErrorFn);41 /**42 * @name profileSuccessFn43 * @desc Update `profile` for view44 */45 function profileSuccessFn(data, status, headers, config) {46 vm.profile = data.data;47 }48 /**49 * @name profileErrorFn50 * @desc Redirect to index51 */52 function profileErrorFn(data, status, headers, config) {53 $location.url('/');54 Snackbar.error('That user does not exist.');55 }56 }57 /**58 * @name destroy59 * @desc Destroy this user's profile60 * @memberOf iupds.profiles.controllers.ProfileSettingsController61 */62 function destroy() {63 Profile.destroy(vm.profile.username).then(profileSuccessFn, profileErrorFn);64 /**65 * @name profileSuccessFn66 * @desc Redirect to index and display success snackbar67 */68 function profileSuccessFn(data, status, headers, config) {69 Authentication.unauthenticate();70 window.location = '/';71 Snackbar.show('Your account has been deleted.');72 }73 /**74 * @name profileErrorFn75 * @desc Display error snackbar76 */77 function profileErrorFn(data, status, headers, config) {78 Snackbar.error(data.error);79 }80 }81 /**82 * @name update83 * @desc Update this user's profile84 * @memberOf iupds.profiles.controllers.ProfileSettingsController85 */86 function update() {87 Profile.update(vm.profile).then(profileSuccessFn, profileErrorFn);88 /**89 * @name profileSuccessFn90 * @desc Show success snackbar91 */92 function profileSuccessFn(data, status, headers, config) {93 Snackbar.show('Your profile has been updated.');94 }95 /**96 * @name profileErrorFn97 * @desc Show error snackbar98 */99 function profileErrorFn(data, status, headers, config) {100 Snackbar.error(data.error);101 }102 }103 }...
ProfileController.js
Source:ProfileController.js
1ProfileController.$inject = ["$scope", "$http", "$routeParams"];2function ProfileController($scope, $http, $routeParams) {3 var userId = $routeParams.id || 14;4 $scope.isUpdating = function (setValue) {5 return (setValue == true) ? setValue : false;6 }7 var setOtherFields = function () {8 $scope.profileViewModel.Id = userId;9 $scope.profileViewModel.PersonTypeId = 3; // private account10 $scope.profileViewModel.Rating = 7;11 if ($scope.profileViewModel.Password == "" || $scope.profileViewModel.Password == undefined) {12 $scope.profileViewModel.Password = "1234";13 }14 $scope.profileViewModel.PersonType = "Privatni";15 /*16 if ($scope.profileViewModel.Id == 0 || $scope.profileViewModel.Id == undefined) {17 $scope.profileViewModel.Id = 14;18 }19 if ($scope.profileViewModel.PersonTypeId = 0 || $scope.profileViewModel.PersonTypeId == undefined) {20 $scope.profileViewModel.PersonTypeId = 3; // private account21 }22 if ($scope.profileViewModel.Rating == 0 || $scope.profileViewModel.Rating == undefined) {23 $scope.profileViewModel.Rating = 7;24 }25 if ($scope.profileViewModel.Password == "" || $scope.profileViewModel.Password == undefined) {26 $scope.profileViewModel.Password = "1234";27 }28 if ($scope.profileViewModel.PersonType == "" || $scope.profileViewModel.PersonType == undefined) {29 $scope.profileViewModel.PersonType = "Privatni";30 }*/31 }32 $scope.updateProfile = function () {33 $scope.isUpdating(true);34 setOtherFields();35 $http.post('Api/ProfileApi/Update/', $scope.profileViewModel).then(function () {36 $scope.updateProfileMessage = "Successfully updated profile data...";37 $scope.isUpdating(false);38 });39 }40 //$http.get('Api/ProfileApi/GetProfile/', { id: 0 }).then(function (response) {41 42 $http.get('Api/ProfileApi/Get/', { params: { id: userId } }).then(function (response) {43 $scope.profileViewModel = response.data;44 setOtherFields();45 });46 if ($scope.isUpdating) {47 }48}...
profiles.js
Source:profiles.js
1import { Profile } from "../models/profile.js"2export{3 index,4 show,5 createSkill,6 deleteSkill,7 createBrand,8 newBrand,9}10function createBrand(req, res) {11 console.log(req.user)12 Profile.findById(req.user.profile._id)13 .then(profile => {14 profile.brands = req.body15 profile.save(() => {16 res.redirect(`/profiles/${req.user.profile._id}`)17 })18 })19 .catch(err => {20 console.log(err)21 res.redirect(`/profiles/${req.user.profile}`)22 })23 console.log(req.body)24 25}26function newBrand(req, res){27 console.log("this better work, I am tired")28 res.render("brands/new",{29 Profile,30 User31 })32}33function deleteSkill(req, res){34 Profile.findById(req.user.profile)35 .then(profile => {36 profile.skills.remove({_id: req.params.id})37 profile.save()38 .then(() => {39 res.redirect(`/profiles/${req.user.profile._id}`)40 })41 })42 .catch(err => {43 console.log(err)44 res.redirect(`/profiles/${req.user.profile._id}`)45 })46}47function createSkill(req, res){48 console.log("this works")49 console.log(req.body)50 Profile.findById(req.user.profile._id)51 .then(profile => {52 profile.skills.push(req.body)53 profile.save()54 .then(() => {55 res.redirect(`/profiles/${req.user.profile._id}`)56 })57 })58 .catch(err => {59 console.log(err)60 res.redirect(`/profiles/${req.user.profile}`)61 })62}63function show(req, res){64 console.log(req.params.id)65 Profile.findById(req.params.id)66 .populate("skills")67 .then(profile => {68 Profile.findById(req.user.profile._id)69 .then(self => {70 console.log(profile, "profile")71 const isSelf = self._id.equals(profile._id)72 res.render("profiles/show", {73 title: `${profile.name}'s profile`,74 profile,75 self,76 isSelf77 })78 })79 })80 .catch((err) => {81 console.log(err)82 res.redirect("/")83 })84}85function index(req, res) {86 Profile.find({})87 .then(profiles => {88 res.render("profiles/index", {89 profiles,90 title: "Profile"91 })92 })93 .catch(err => {94 console.log(err)95 res.redirect(`/profiles/${req.user.profile}`)96 })...
LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.
|<p>it('check_object_of_Car', () => {</p><p>
expect(newCar()).toBeInstanceOf(Car);</p><p>
});</p>|
| :- |
Get 100 minutes of automation test minutes FREE!!