mongodb next is not a function in angularjs - angularjs

I was working with this project, it is linked to mongodb, it was working perfectly, so I could register new users, edit and save them. I format my laptop, then I cloned my project but it doesn't work anymore, when I try to register a new user it gives me the error: "NEXT IS NOT A FUNCTION", I haven't modified anything. I don't know really what happened. I have tried it in a different laptop and it works. So I have to keep working on it but I can't because of it.
I leave some code in case if it is something wrong.
Thanks!
server.js
var express = require("express"); // ExperssJS Framework
var app = express(); // Invoke express to variable for use in application
var port = process.env.PORT || 5555; // Set default port or assign a port in enviornment
var morgan = require("morgan"); // Import Morgan Package
var mongoose = require("mongoose"); // HTTP request logger middleware for Node.js
var bodyParser = require("body-parser"); // Node.js body parsing middleware. Parses incoming request bodies in a middleware before your handlers, available under req.body.
var router = express.Router(); // Invoke the Express Router
var appRoutes = require("./app/routes/api")(router); // Import the application end points/API
var path = require("path"); // Import path module
var passport = require("passport"); // Express-compatible authentication middleware for Node.js.
var social = require("./app/passport/passport")(app, passport); // Import passport.js End Points/API
app.use(morgan("dev")); // Morgan Middleware
app.use(bodyParser.json()); // Body-parser middleware
app.use(bodyParser.urlencoded({ extended: true })); // For parsing application/x-www-form-urlencoded
app.use(express.static(__dirname + "/public")); // Allow front end to access public folder
app.use("/api", appRoutes); // Assign name to end points (e.g., '/api/management/', '/api/users' ,etc. )
//
// <---------- REPLACE WITH YOUR MONGOOSE CONFIGURATION ---------->
//
mongoose.connect(
"mongodb://localhost:27017/databasename",
{ useNewUrlParser: true },
function(err) {
if (err) {
console.log("Not connected to the database: " + err); // Log to console if unable to connect to database
} else {
console.log("Successfully connected to MongoDB"); // Log to console if able to connect to database
}
}
);
// Set Application Static Layout
app.get("*", function(req, res) {
res.sendFile(path.join(__dirname + "/public/app/views/index.html")); // Set index.html as layout
});
// Start Server
app.listen(port, function() {
console.log("Running the server on port " + port); // Listen on configured port
});
-
userCtrl.js
angular
.module("userControllers", ["userServices"])
// Controller: regCtrl is used for users to register an account
.controller("regCtrl", function($http, $location, $timeout, User, $scope) {
var app = this;
// Custom function that registers the user in the database
this.regUser = function(regData, valid, confirmed) {
app.disabled = true; // Disable the form when user submits to prevent multiple requests to server
app.loading = true; // Activate bootstrap loading icon
app.errorMsg = false; // Clear errorMsg each time user submits
// If form is valid and passwords match, attempt to create user
if (valid && confirmed) {
app.regData.name = app.regData.firstName + " " + app.regData.lastName; // Combine first and last name before submitting to database
// Runs custom function that registers the user in the database
User.create(app.regData).then(function(data) {
// Check if user was saved to database successfully
if (data.data.success) {
app.loading = false; // Stop bootstrap loading icon
$scope.alert = "alert alert-success"; // Set class for message
app.successMsg = data.data.message + "...Redirecting"; // If successful, grab message from JSON object and redirect to login page
// Redirect after 2000 milliseconds (2 seconds)
$timeout(function() {
$location.path("/login");
}, 2000);
} else {
app.loading = false; // Stop bootstrap loading icon
app.disabled = false; // If error occurs, remove disable lock from form
$scope.alert = "alert alert-danger"; // Set class for message
app.errorMsg = data.data.message; // If not successful, grab message from JSON object
}
});
} else {
app.disabled = false; // If error occurs, remove disable lock from form
app.loading = false; // Stop bootstrap loading icon
$scope.alert = "alert alert-danger"; // Set class for message
app.errorMsg = "Please ensure form is filled our properly"; // Display error if valid returns false
}
};
// Custom function that checks if username is available for user to use
this.checkUsername = function(regData) {
app.checkingUsername = true; // Start bootstrap loading icon
app.usernameMsg = false; // Clear usernameMsg each time user activates ngBlur
app.usernameInvalid = false; // Clear usernameInvalid each time user activates ngBlur
// Runs custom function that checks if username is available for user to use
User.checkUsername(app.regData).then(function(data) {
// Check if username is available for the user
if (data.data.success) {
app.checkingUsername = false; // Stop bootstrap loading icon
app.usernameMsg = data.data.message; // If successful, grab message from JSON object
} else {
app.checkingUsername = false; // Stop bootstrap loading icon
app.usernameInvalid = true; // User variable to let user know that the chosen username is taken already
app.usernameMsg = data.data.message; // If not successful, grab message from JSON object
}
});
};
// Custom function that checks if e-mail is available for user to use
this.checkEmail = function(regData) {
app.checkingEmail = true; // Start bootstrap loading icon
app.emailMsg = false; // Clear emailMsg each time user activates ngBlur
app.emailInvalid = false; // Clear emailInvalid each time user activates ngBlur
// Runs custom function that checks if e-mail is available for user to use
User.checkEmail(app.regData).then(function(data) {
// Check if e-mail is available for the user
if (data.data.success) {
app.checkingEmail = false; // Stop bootstrap loading icon
app.emailMsg = data.data.message; // If successful, grab message from JSON object
} else {
app.checkingEmail = false; // Stop bootstrap loading icon
app.emailInvalid = true; // User variable to let user know that the chosen e-mail is taken already
app.emailMsg = data.data.message; // If not successful, grab message from JSON object
}
});
};
app.addUser = function() {
if (app.showTheForm) {
app.showTheForm = false;
app.expand = false;
} else {
app.showTheForm = true;
app.expand = true;
}
};
})
// Custom directive to check matching passwords
.directive("match", function() {
return {
restrict: "A", // Restrict to HTML Attribute
controller: function($scope) {
$scope.confirmed = false; // Set matching password to false by default
// Custom function that checks both inputs against each other
$scope.doConfirm = function(values) {
// Run as a loop to continue check for each value each time key is pressed
values.forEach(function(ele) {
// Check if inputs match and set variable in $scope
if ($scope.confirm == ele) {
$scope.confirmed = true; // If inputs match
} else {
$scope.confirmed = false; // If inputs do not match
}
});
};
},
link: function(scope, element, attrs) {
// Grab the attribute and observe it
attrs.$observe("match", function() {
scope.matches = JSON.parse(attrs.match); // Parse to JSON
scope.doConfirm(scope.matches); // Run custom function that checks both inputs against each other
});
// Grab confirm ng-model and watch it
scope.$watch("confirm", function() {
scope.matches = JSON.parse(attrs.match); // Parse to JSON
scope.doConfirm(scope.matches); // Run custom function that checks both inputs against each other
});
}
};
});
Node.js
{ ValidationError: User validation failed: username: next is not a
function, password: next is not a function, email: next is not a function, name: next is not a function
at ValidationError.inspect (D:\Documents\Trabajo\gorotasnewest\node_modules\mongoose\lib\error\validation.js:56:24)
at ValidationError.deprecated (internal/util.js:70:15)
at formatValue (util.js:467:31)
at inspect (util.js:328:10)
at Object.formatWithOptions (util.js:182:12)
at Console.(anonymous function) (console.js:188:15)
at Console.log (console.js:199:31)
at D:\Documents\Trabajo\gorotasnewest\app\routes\api.js:70:17
at D:\Documents\Trabajo\gorotasnewest\node_modules\mongoose\lib\model.js:4423:16
at $__save.error (D:\Documents\Trabajo\gorotasnewest\node_modules\mongoose\lib\model.js:379:16)
at D:\Documents\Trabajo\gorotasnewest\node_modules\kareem\index.js:246:48
at next (D:\Documents\Trabajo\gorotasnewest\node_modules\kareem\index.js:167:27)
at Kareem.execPost (D:\Documents\Trabajo\gorotasnewest\node_modules\kareem\index.js:217:3)
at _handleWrapError (D:\Documents\Trabajo\gorotasnewest\node_modules\kareem\index.js:245:21)
at D:\Documents\Trabajo\gorotasnewest\node_modules\kareem\index.js:272:14
at _next (D:\Documents\Trabajo\gorotasnewest\node_modules\kareem\index.js:94:14)
errors:
{ username:
{ ValidatorError: next is not a function
at new ValidatorError (D:\Documents\Trabajo\gorotasnewest\node_modules\mongoose\lib\error\validator.js:25:11)
at validate (D:\Documents\Trabajo\gorotasnewest\node_modules\mongoose\lib\schematype.js:805:13)
at D:\Documents\Trabajo\gorotasnewest\node_modules\mongoose\lib\schematype.js:854:11
at Array.forEach ()
at SchemaString.SchemaType.doValidate (D:\Documents\Trabajo\gorotasnewest\node_modules\mongoose\lib\schematype.js:814:19)

Related

Angularjs : adding a new record using forum and controller

I am new to Angular and I am trying to add data from forum into the database, to do so i need the id of the current user which i get with no problem, only in my post method I rely entirely on the data that i get from the forum, but in the forum i wouldn't of course ask for the id to be filled so I need to add it automatically to my controller and i don't know how to do so : here is the function that I use in my controller :
app.addFT = function () {
//Get the current user Id
Auth.getUser().then(function (data) {
console.log(data.data.email);
Compte.getComptebymail(data.data.email).then(function(result)
{
console.log(result.data.col.IdCollaborateur);
lecollaborateur.push(result.data.col);
$scope.lecollaborateur = lecollaborateur;
});
});
console.log(app.addData);
//we connect it to the back end of the application
FT.createFT(app.addData).then(function (data) {
if(data.data.success){
//create success message
app.loading = false;
app.successMsg = data.data.message + '...Redirection';
//Redirect to show projet
$timeout(function () {
$location.path('/FeuillesTempsListe');
}, 2000);
}else{
//create an error message
app.loading = false;
app.errorMsg = data.data.message;
}
});
};
app.addData is the data the user fills in the view : I get the name,description,...but I don't know how to pass the Id to app.addData other then using the forum, I tried :
app.addData.Id=lecollaborateur.Id; but it's not working , any suggestions ?
You need call createFT only after the success call of getComptebymail.
So that you will have id in the app.addData.
app.addFT = function() {
//Get the current user Id
Auth.getUser().then(function(data) {
console.log(data.data.email);
Compte.getComptebymail(data.data.email).then(function(
result) {
console.log(result.data.col.IdCollaborateur);
lecollaborateur.push(result.data.col);
$scope.lecollaborateur = lecollaborateur;
app.addData.Id = lecollaborateur.Id;
console.log(app.addData);
//we connect it to the back end of the application
FT.createFT(app.addData).then(function(data) {
if (data.data.success) {
//create success message
app.loading = false;
app.successMsg = data.data.message +
'...Redirection';
//Redirect to show projet
$timeout(function() {
$location.path(
'/FeuillesTempsListe'
);
}, 2000);
} else {
//create an error message
app.loading = false;
app.errorMsg = data.data.message;
}
});
});
});
};

Lighthouse/Service Worker, how to return http 200 when offline

My application currently uses webpack,angular js, and a service worker.
Using sw-precache plugin to create my service worker.
https://www.npmjs.com/package/sw-precache-webpack-plugin
The service worker caching is going well and I can see my static resources being fetched from serviceworker.js from chrome dev tools.
Now when I run the lighthouse report I am getting the following error still :
URL responds with a 200 when offline
https://github.com/GoogleChrome/lighthouse
In Dev tools when I switch on offline, I can actually see my page load. Some errors in console for some 3rd party scripts failing. Is this the reason for not getting url response 200 because I have some console errors from 3rd party i.e. sample error :
GET https://fonts.googleapis.com/css?family=Roboto+Slab:300,400,700 net::ERR_INTERNET_DISCONNECTED
What exactly is this audit looking for, and how can I achieve it ?
Edit : I added a picture of my network tab when I turn on offline, as I said the page loads fine. I notice my sw.js get's loaded from disk cache which I don't notice on other sites so could be something there.
Also here is sw.js content
'use strict';
var precacheConfig = [["/css/app.styles.77e2a0c3e7ac001193566741984a07f0.css","77e2a0c3e7ac001193566741984a07f0"],["/css/vendor.styles.582e79ead0684a8fb648ce9e543ad810.css","582e79ead0684a8fb648ce9e543ad810"],["/favicon.ico","70ef569d9a12f6873e86ed57d575cf13"],["/fonts/MaterialIcons-Regular.eot","e79bfd88537def476913f3ed52f4f4b3"],["/fonts/MaterialIcons-Regular.svg","a1adea65594c502f9d9428f13ae210e1"],["/fonts/MaterialIcons-Regular.ttf","a37b0c01c0baf1888ca812cc0508f6e2"],["/fonts/MaterialIcons-Regular.woff","012cf6a10129e2275d79d6adac7f3b02"],["/fonts/MaterialIcons-Regular.woff2","570eb83859dc23dd0eec423a49e147fe"],["/icons/launcher-icon-2x.png","91896b953c39df7c40b4772100971220"],["/icons/launcher-icon-3x.png","0aee2add7f56559aeae9555e495c3881"],["/icons/launcher-icon-4x.png","b164109dd7640b14aaf076d55a0a637b"],["/images/aa_logo_only.png","b5b46a8c2ead9846df1f1d3035634310"],["/images/developer.png","e8df747b292fe6f5eb2403c7180c31da"],["/images/facebook.png","8ab42157d0974099a72e151c23073022"],["/images/home-bg.jpeg","0a0f7da8574b037463af2f1205801e56"],["/images/logo.png","e8712312e08ca427d79a9bf34aedd6fc"],["/images/map.png","af3443ef4ab2890cae371c7a3de437ed"],["/images/pattern.png","114d593511446b9a4c6e340f7fef5c84"],["/images/twitter.png","99da44949cd33e16d2d551d42559eaf2"],["/index.html","1e9b5c4b3abba7e13d8d28c98cfb3bb5"],["/js/app.d9ada27616bf469d794d.js","8e2fc74de7d5c122ab8f0aca7e31b075"],["/js/vendor.d9ada27616bf469d794d.js","3bbba4569b6f3b88881b0533260905fe"],["/manifest.json","4bea29155995b63a9f2855637c0fe74c"]];
var cacheName = 'sw-precache-v2-45-' + (self.registration ? self.registration.scope : '');
var ignoreUrlParametersMatching = [/^utm_/];
var addDirectoryIndex = function (originalUrl, index) {
var url = new URL(originalUrl);
if (url.pathname.slice(-1) === '/') {
url.pathname += index;
}
return url.toString();
};
var createCacheKey = function (originalUrl, paramName, paramValue,
dontCacheBustUrlsMatching) {
// Create a new URL object to avoid modifying originalUrl.
var url = new URL(originalUrl);
// If dontCacheBustUrlsMatching is not set, or if we don't have a match,
// then add in the extra cache-busting URL parameter.
if (!dontCacheBustUrlsMatching ||
!(url.toString().match(dontCacheBustUrlsMatching))) {
url.search += (url.search ? '&' : '') +
encodeURIComponent(paramName) + '=' + encodeURIComponent(paramValue);
}
return url.toString();
};
var isPathWhitelisted = function (whitelist, absoluteUrlString) {
// If the whitelist is empty, then consider all URLs to be whitelisted.
if (whitelist.length === 0) {
return true;
}
// Otherwise compare each path regex to the path of the URL passed in.
var path = (new URL(absoluteUrlString)).pathname;
return whitelist.some(function(whitelistedPathRegex) {
return path.match(whitelistedPathRegex);
});
};
var stripIgnoredUrlParameters = function (originalUrl,
ignoreUrlParametersMatching) {
var url = new URL(originalUrl);
url.search = url.search.slice(1) // Exclude initial '?'
.split('&') // Split into an array of 'key=value' strings
.map(function(kv) {
return kv.split('='); // Split each 'key=value' string into a [key, value] array
})
.filter(function(kv) {
return ignoreUrlParametersMatching.every(function(ignoredRegex) {
return !ignoredRegex.test(kv[0]); // Return true iff the key doesn't match any of the regexes.
});
})
.map(function(kv) {
return kv.join('='); // Join each [key, value] array into a 'key=value' string
})
.join('&'); // Join the array of 'key=value' strings into a string with '&' in between each
return url.toString();
};
var hashParamName = '_sw-precache';
var urlsToCacheKeys = new Map(
precacheConfig.map(function(item) {
var relativeUrl = item[0];
var hash = item[1];
var absoluteUrl = new URL(relativeUrl, self.location);
var cacheKey = createCacheKey(absoluteUrl, hashParamName, hash, false);
return [absoluteUrl.toString(), cacheKey];
})
);
function setOfCachedUrls(cache) {
return cache.keys().then(function(requests) {
return requests.map(function(request) {
return request.url;
});
}).then(function(urls) {
return new Set(urls);
});
}
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(cacheName).then(function(cache) {
return setOfCachedUrls(cache).then(function(cachedUrls) {
return Promise.all(
Array.from(urlsToCacheKeys.values()).map(function(cacheKey) {
// If we don't have a key matching url in the cache already, add it.
if (!cachedUrls.has(cacheKey)) {
return cache.add(new Request(cacheKey, {credentials: 'same-origin'}));
}
})
);
});
}).then(function() {
// Force the SW to transition from installing -> active state
return self.skipWaiting();
})
);
});
self.addEventListener('activate', function(event) {
var setOfExpectedUrls = new Set(urlsToCacheKeys.values());
event.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.keys().then(function(existingRequests) {
return Promise.all(
existingRequests.map(function(existingRequest) {
if (!setOfExpectedUrls.has(existingRequest.url)) {
return cache.delete(existingRequest);
}
})
);
});
}).then(function() {
return self.clients.claim();
})
);
});
self.addEventListener('fetch', function(event) {
if (event.request.method === 'GET') {
// Should we call event.respondWith() inside this fetch event handler?
// This needs to be determined synchronously, which will give other fetch
// handlers a chance to handle the request if need be.
var shouldRespond;
// First, remove all the ignored parameter and see if we have that URL
// in our cache. If so, great! shouldRespond will be true.
var url = stripIgnoredUrlParameters(event.request.url, ignoreUrlParametersMatching);
shouldRespond = urlsToCacheKeys.has(url);
// If shouldRespond is false, check again, this time with 'index.html'
// (or whatever the directoryIndex option is set to) at the end.
var directoryIndex = 'index.html';
if (!shouldRespond && directoryIndex) {
url = addDirectoryIndex(url, directoryIndex);
shouldRespond = urlsToCacheKeys.has(url);
}
// If shouldRespond is still false, check to see if this is a navigation
// request, and if so, whether the URL matches navigateFallbackWhitelist.
var navigateFallback = '';
if (!shouldRespond &&
navigateFallback &&
(event.request.mode === 'navigate') &&
isPathWhitelisted([], event.request.url)) {
url = new URL(navigateFallback, self.location).toString();
shouldRespond = urlsToCacheKeys.has(url);
}
// If shouldRespond was set to true at any point, then call
// event.respondWith(), using the appropriate cache key.
if (shouldRespond) {
event.respondWith(
caches.open(cacheName).then(function(cache) {
return cache.match(urlsToCacheKeys.get(url)).then(function(response) {
if (response) {
return response;
}
throw Error('The cached response that was expected is missing.');
});
}).catch(function(e) {
// Fall back to just fetch()ing the request if some unexpected error
// prevented the cached response from being valid.
console.warn('Couldn\'t serve response for "%s" from cache: %O', event.request.url, e);
return fetch(event.request);
})
);
}
}
});
Some data like
https://fonts.googleapis.com/css?family=Roboto+Slab:300,400,700
does not support offline mode download these file manually and add them with local path again.

Firebase .once(): Use success and failure callbacks

I have the following function in my Angular-app
$scope.retrieveProjectData = function() {
$scope.projectNumberNoChange = false;
// Only retrieve Data if the ProjectNumber changed
if (currentlySelectedProjectNumber != $scope.feedback.projectNumber.content) {
currentlySelectedProjectNumber = $scope.feedback.projectNumber.content;
// Go to database-reference based on the projectNumber
var projectsRef = firebaseDatabaseRef.child("projects");
var currentChild = projectsRef.child(currentlySelectedProjectNumber);
// retrieve data once and fill $scope.feedback
currentChild.once("value",
// If the project is found
function (dataSnapshot) {
// Fill selectedProject and hand over to writeDataFromSelectedProject()
var selectedProject = dataSnapshot.val();
// Fill $scope.feedback
writeDataFromSelectedProject(selectedProject);
},
// If no data is found
function () {
console.log("No data found");
});
}
// If the projectNumber didn't change, the projectNumberNoChangeMessage will be shown
else {
$scope.projectNumberNoChange = true;
}
};
The user has the possibility to load some data regarding his project-number (for instance: Name, email, tel) to make it faster for the user to fill a form.
In the part:
currentChild.once("value",
// If the project is found
function (dataSnapshot) {
// Fill selectedProject and hand over to writeDataFromSelectedProject()
var selectedProject = dataSnapshot.val();
// Fill $scope.feedback
writeDataFromSelectedProject(selectedProject);
},
// If no data is found
function () {
console.log("No data found");
});
only the first Callback-function is called, even if the projectNumber was not found. How can I use the "failureCallbackOrContext" as described in the docs?
Thanks for taking the time!
The problem was solved. I just checked the dataSnapshot.val() for beeing an object or null!

Socket authentication with node.js & socket.io (using DaftMonk's generator-angular-fullstack)

I'm using DaftMonk's generator-angular-fullstack for a project with everything set as default,
I find myself needing socket authentication with it so I have enabled "socketio-jwt" on the socketio.js
and on the Angular service.
This is how my Angular service looks like:
/* global io */
'use strict';
angular.module('myApp')
.factory('socket', function(socketFactory, Auth) {
// socket.io now auto-configures its connection when we ommit a connection url
var ioSocket = io('', {
// Send auth token on connection, you will need to DI the Auth service above
query: 'token=' + Auth.getToken(),
path: '/socket.io-client'
});
var socket = socketFactory({
ioSocket: ioSocket
});
return {
socket: socket,
/**
* Register listeners to sync an array with updates on a model
*
* Takes the array we want to sync, the model name that socket updates are sent from,
* and an optional callback function after new items are updated.
*
* #param {String} modelName
* #param {Array} array
* #param {Function} cb
*/
syncUpdates: function (modelName, array, cb) {
cb = cb || angular.noop;
/**
* Syncs item creation/updates on 'model:save'
*/
socket.on(modelName + ':save', function (item) {
var oldItem = _.find(array, {_id: item._id});
var index = array.indexOf(oldItem);
var event = 'created';
// replace oldItem if it exists
// otherwise just add item to the collection
if (oldItem) {
array.splice(index, 1, item);
event = 'updated';
} else {
array.push(item);
}
cb(event, item, array);
});
/**
* Syncs removed items on 'model:remove'
*/
socket.on(modelName + ':remove', function (item) {
var event = 'deleted';
_.remove(array, {_id: item._id});
cb(event, item, array);
});
},
/**
* Removes listeners for a models updates on the socket
*
* #param modelName
*/
unsyncUpdates: function (modelName) {
socket.removeAllListeners(modelName + ':save');
socket.removeAllListeners(modelName + ':remove');
}
};
});
This is how my socketio file on the server looks like:
/**
* Socket.io configuration
*/
'use strict';
var config = require('./environment');
// When the user disconnects.. perform this
function onDisconnect(socket) {
}
// When the user connects.. perform this
function onConnect(socket) {
//I dont have any decoded_token here
console.log(socket.handshake.decoded_token._id, 'connected');
// When the client emits 'info', this listens and executes
socket.on('info', function (data) {
console.info('[%s] %s', socket.address, JSON.stringify(data, null, 2));
});
// Insert sockets below
require('../api/conversation/conversation.socket').register(socket);
}
module.exports = function (socketio) {
// socket.io (v1.x.x) is powered by debug.
// In order to see all the debug output, set DEBUG (in server/config/local.env.js) to including the desired scope.
//
// ex: DEBUG: "http*,socket.io:socket"
// We can authenticate socket.io users and access their token through socket.handshake.decoded_token
//
// 1. You will need to send the token in `client/components/socket/socket.service.js`
//
// 2. Require authentication here:
// socketio.use(require('socketio-jwt').authorize({
// secret: config.secrets.session,
// handshake: true
// }));
socketio.use(require('socketio-jwt').authorize({
secret: config.secrets.session,
handshake: true
}));
socketio.on('connection', function (socket) {
socket.address = socket.handshake.address !== null ?
socket.handshake.address.address + ':' + socket.handshake.address.port :
process.env.DOMAIN;
socket.connectedAt = new Date();
// Call onDisconnect.
socket.on('disconnect', function () {
onDisconnect(socket);
console.info('[%s] DISCONNECTED', socket.address);
});
// Call onConnect.
onConnect(socket);
console.info('[%s] CONNECTED', socket.address);
});
};
I have read this blog post about socket authentication, and expected my socket to have a decoded_token value but it does not, I verified that the jwt sign attaches the userId to the token
but I still don't see it...
This is my jwt sign:
/**
* Returns a jwt token signed by the app secret
*/
function signToken(id) {
return jwt.sign({ _id: id }, config.secrets.session, { expiresInMinutes: 60*5 });
}
/**
* Set token cookie directly for oAuth strategies
*/
function setTokenCookie(req, res) {
if (!req.user) return res.json(404, { message: 'Something went wrong, please try again.'});
var token = signToken(req.user._id, req.user.role);
res.cookie('token', JSON.stringify(token));
}
My question is this, how do I get the current user info attached to the socket? (just the id is fine).
Silly me, it seems like I was looking for the decoded token in the wrong place, it was here:
socket.decoded_token._id

AngularJS: Assign variables to $scope after AJAX call

I am sooo close I can smell the finish line --
When my app starts, I harvest the login information from the user (it's an AngularJS SPA so I can get it easy from spInfoContext) and I check to see if the user is a returning user by searching a list called itiUsers for the userId. If no records are found, I immediately create a new record in itiUsers and then present a form for the new user to enter the information that I can't grab from SharePoint. The record is created properly. When the promise returns, I am trying to populate the $scope.current_user object so that it would be the same as if this were a returning user -- that's so I only have to have one My Preferences form.
However when I log out $scope after the record is created, current_user is empty.
Here's my Controller function (i reduced values for brevity and I tried to bold the problem line):
$.when(SharePointJSOMService.getCurrentUser())
.done(function(jsonObject){
if(jsonObject.d.results.length < 1 || jsonObject.d.results.newUser ){
// new user
$.when(SharePointJSOMService.getLoggedInUser())
.done(function(jsonObject){
$scope.loggedInUser = jsonObject.d;
$scope.isNewUser = true;
$.when(SharePointJSOMService.createNewUser($scope))
.done(function(jsonObject){
**$scope.current_user.DisplayName = $scope.loggedInUser.Title;
console.log($scope);**
})
.fail(function(err){
$scope.prefPane = true;
console.info(JSON.stringify(err));
});
})
.fail(function(err){
$scope.prefPane = true;
console.info(JSON.stringify(err));
});
$scope.prefPane = true; // force preference pane
$scope.taskClose = true;
$scope.$apply();
} else {
// existing user
$scope.isNewUser = false;
$scope.prefPane = false; // hide preference pane
$scope.current_user = jsonObject.d.results[0];
switch($scope.current_user.Role){
case 'USR':
$scope.projectClose = 'true';
break;
case 'PMG':
$scope.projectClose = 'false';
break;
default:
$scope.projectClose = 'true';
break;
} // end switch
$scope.$apply();
} // end if
})
.fail(function(err){
$scope.prefPane = true;
console.info(JSON.stringify(err));
});
It crashes because you are trying to set $scope.current_user.DisplayName after creating a new user but $scope.current_user object is undefined. Try instead:
$scope.current_user = {
DisplayName: $scope.loggedInUser.Title
}

Resources