How to render data related specifically to a user when they login? - javascript

I'm working on a small application and I'm relatively new to programming. I've been using MEAN stack to start and have run into a snag. I have this code here that will render a name when a page is loaded.
<tr ng-repeat = "contact in users">
<td>{{contact.name}}</td>
</tr>
In my controller I have this code:
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {
console.log("Hello World from controller");
var refresh = function() {
$http.get('/users').success(function(response) {
console.log("I got the data I requested");
$scope.users = response;
$scope.contact = "";
});
};
refresh();
And then in my server I have this
app.get('/users', function (req, res) {
console.log('I received a GET request');
db.users.find( {_id: mongojs.ObjectId("55563359e430458542c0f36f")}, function (err, docs) {
console.log(docs);
res.json(docs);
});
});
This works great when I want to render that user. However this only allows me to render one of my users names. And it's whichever one I hard code into the db.user.find. What I would like to do is figure out a way to render a user's name based of off some specific session/variable when they login. So essentially when a user logs in have the values specific to their credentials display I used this tutorial https://scotch.io/tutorials/easy-node-authentication-setup-and-local for a beginners authentication. I figured I would be able to take the session and then somehow pass it down to my get statement on the server but so far I haven't been able to figure it out. Any suggestion would be great even if it means me scrapping what I have.

Related

Sending email in Ionic app results in following error: TypeError: $cordovaEmailComposer.isAvailable is not a function

I am working on an Ionic Android/iOS app that will primarily be used to scan barcodes then email a CSV (.txt) attachment containing all scans to a distribution group. This app uses ngCordova + the Cordova Email Composer plugin (cordova-plugin-email-composer) for email functionality. Upon initiating an email send in Android (6.0.1 on Nexus 5), I get the following console error:
TypeError: $cordovaEmailComposer.isAvailable is not a function
All other processes seem to work correctly (e.g. correct platform-dependent file path generation, attachment formatting and generation) and ngCordova + Cordova Barcode Scanner plugin (phonegap-plugin-barcodescanner) functions properly.
I did have some issues with Cordova Email Composer v0.8.3 always returning 'false' on .isAvailable() in Android, however I successfully worked around this using v0.8.2. This new problem occurs with both versions.
Please see below for the portion of the Angular service that contains the problem code. scanData is a simple service that temporarily holds the scanned information including paths and an array of all scans. processFile is a servce that handles all file processing (e.g. save, load, remove, dynamically generate file name, determine correct file path).
angular
.module('app')
.factory('emailService', ['$ionicPlatform', '$ionicPopup', '$ionicHistory', '$cordovaEmailComposer', 'scanData', 'processFile', emailService]);
function emailService($ionicPlatform, $ionicPopup, $cordovaEmailComposer, $ionicHistory, scanData, processFile) {
var path = scanData.filePath,
file = scanData.fileName;
var service = {
send: send
};
return service;
//------------------------------
/**
* Send email
*/
function send() {
processFile.save('csv')
.then(function () {
console.info('CSV file saved.');
sendEmail();
}, function (error) {
console.error(error);
//TODO: handle failed save attempt
});
}
/**
* Invoke cordova email composer to open email client and create pre-defined draft with attachment.
*/
function sendEmail() {
console.info('Sending email...');
$ionicPlatform.ready(function () {
$cordovaEmailComposer
.isAvailable() //ERROR OCCURS HERE
.then(function () {
console.info('Email app available.');
var attachmentPath = getAttachmentPath();
console.info('Attachment path: ' + attachmentPath);
var email = {
to: 'foo#bar.com',
attachments: [ attachmentPath ],
subject: 'Incoming Scan',
body: 'See attached.'
};
$cordovaEmailComposer
.open(email)
.then(null, function () {
clearDataPopup();
});
}, function () {
console.warn('Email app not available.');
});
});
}
Also, all components/dependencies are up-to-date, and I have run ionic state reset with no change. I haven't had a chance to test on iOS yet but will update the question once I can do so. Android is the most important platform at this time, so I'm focusing on it for now.
It's very likely this is just some stupid little thing that I'm overlooking, but I'm currently at a loss.
You had mismatch in dependency sequence. Keep one thing in mind, the sequence in which you inject dependency inside DI Inline array do add you should get their respective instance inside controller factory function one the same number of parameter. You $ionicHistory is missed to inject in 3rd place of controller factory function.
.factory('emailService', ['$ionicPlatform', '$ionicPopup', '$ionicHistory', '$cordovaEmailComposer', 'scanData', 'processFile', emailService]);
//VVVVV//this was missing
function emailService($ionicPlatform, $ionicPopup, $ionicHistory, $cordovaEmailComposer, $ionicHistory, scanData, processFile) {
Because of missing parameter $cordovaEmailComposer is holding the reference of $ionicHistory

angular directive is undefined in browser console, but defined in nodejs console

I am currently putting together an admin dashboard which displays data retrieved from a db. I am currently having an issue with the attribute {{pledges}} displaying in the browser window or console, and I am seeking a bit of assistance with this. I suspect it is something either very large or very small that I am just not seeing. Here are the following steps I have taken:
1.) attempted to get the retrieved data to display in chrome's console and is returned undefined. I also put in some static data along with the directive to see what is and is not being loaded. The directive was blank as expected.
2.) made sure the controllers names are spelled correctly and scopes are correct.
3.) performed a console.log on the back-end on pledge[0].avg_amt_pledge which displayed accurately.
HTML
<div class="box-info">
<p class="size-h2" ng-controller="pledgeCtrl">{{pledges}}<span class="size-h4"></span></p>
<p class="text-muted"><span data-i18n="Median Pledges"></span></p></div>
Controller
function(){
"use strict";
angular.module("pledgeDisplay", []).controller("pledgeCtrl", ["$scope","$http", function($scope, $http){
$http.get("javascripts/avg.js")
.success(function(pledge){
$scope.pledges = pledge[0].avg_amt_pledge;
});l
}])}.call(this);
DB query
var query2 = connection.query("SELECT AVG (amt_donate) AS avg_amt_pledge FROM donations WHERE org_id = '3' ",
function (err, rows) {
if (err) throw err;
pledge = rows;
console.log(pledge[0].avg_amt_pledge);
//outputs queried data held in var avg_amt_pledge.
});
});

Calling the app config method inside ajax response - AngularJS

I am developing an app using angularjs and this is my first hands on using angular. Although, I have started understanding it and have developed some part of the app but I am stuck at one particular point.
I am trying to implement login functionality, so as the page loads, I am authenticating user and redirecting him to login page. On successful login, I am storing some values of user in one of the config provider.
Now I am using an API which has their own method of authentication and they have expose the ajax method which I can use to authenticate a user.
I have provided a snippet below. What I am primarily doing is using the external API, authenticating the user and once authenticated, I am getting roles associated to that user using another ajax method of the API, called "GetUserDetails".
And inside the response of the "GetUserDetails", I am injecting a provider and setting some values, so I can use this across my app.
The problem here is the app.config method is never called/executded. I mean the ajax request is returning response, and the alert is displayed on my page, but app.config is never executed.
But the same app.config if I call inside the done() of GetUser method, the app.config gets executed and stores values in my provider. But I want the GetuserDetails values also to be stored before I do anything in my app as I want to execute certain functionality based on user.
Below is my function in main.js file
function(angular,angularRoute,app,routes,configService){
var $html = angular.element(document.getElementsByTagName('html')[0]);
angular.element().ready(function() {
$.c.authentication.getUser()
.done(function(response){
if(response.userName!="anonymous"){
$.c.ajax({
method: "GetUserDetails",
parameters: {
User: response.user
}
})
.done(function(res) {
alert("I have reached the destination").
app.config(['configServiceProvider', function(configServiceProvider){
configServiceProvider.setLoginStatus(true);
configServiceProvider.setUserName(response.userName);
configServiceProvider.setUserObject(response);
configServiceProvider.setUserRoleDetails(res);
}]);
})
.fail(function(res) {
alert("Error while getting user roles ."+res);
});
angular.resumeBootstrap([app['name']]);
}
else
{
app.config(['configServiceProvider', function(configServiceProvider){
configServiceProvider.setLoginStatus(false);
configServiceProvider.setUserName(response.userName);
}]);
//Show Login Screen
var url = window.location.href.split("#")[0];
window.location.href = url + "#/Login";
angular.resumeBootstrap([app['name']]);
}
})
.fail(function(response){
$rootScope.isLoggedIn=false;
});
});
Here is my configServiceProvider
define(['../app'],function(app){
return app.provider('configService', function(){
var options={};
this.setLoginStatus = function(status){
//$rootScope.isLoggedIn = status;
options.isLoggedIn=status;
};
this.setPreLoginInfo=function(info){
options.preLoginInfo=info;
};
this.setUserName=function(name){
options.username=name;
}
this.setUserObject = function(userObject) {
options.userObject = userObject;
}
this.setUserRoleDetails = function(userRoleDetails) {
options.userRoleDetails = userRoleDetails;
}
this.$get=[function(){
if(!options){
}
return options;
}];
});
})
Can anyone please explain me what's going wrong here or what I am missing ?
Also, is there any alternative to achieve the same functionality ?
No luck in figuring out why the above scenario was not working. Since I had already spent lot of time behind this, I have found a workaround to achieve the same with the use of services.

Can't figure out using Firebase to login with Github

In my home page, I have a link to the following:
Login with Github
And in my app.js I have the following:
app.get('/login', function(req, res) {
var ref = new Firebase('https://hrr-kitchen.firebaseio.com');
ref.authWithOAuthPopup('github', function(err, authData) {
console.log('in authWithOAuthPopup');
if (err) {
console.log(err.code);
} else if (authData) {
// user authenticated with GitHub
console.log('User ID: ' + authData.uid);
}
});
});
I've spent hours on this searching on the web and I've tried so many different things, that my eyes are loopy. I'm thinking I may need to call a function from the html and put the code in a function and I'm tempted at this point to try and just do it in javascript outside of the server, but I think that's janky.
I'm new to firebase and express and I just can't figure this out. Please help?
EDIT: I've been able to get something working by changing my HTML to look like this:
<script type="text/javascript">
var ref = new Firebase('https://hrr-kitchen.firebaseio.com');
githubLogin = function () {
login(function(err, authData) {
var username = authData.github.username;
});
};
var login = function(cb) {
ref.authWithOAuthPopup('github', cb, {
remember: "sessionOnly"
});
};
</script>
<button onclick="githubLogin();">Login with Github</button>
But I really would like to figure out how to do it in express correctly! Thanks!!
The authentication methods in the Firebase library only work on the client-side.
If you need to authenticate on the server, you should use authWithCustomToken from a generated token. The Firebase docs have a detailed section on generating tokens.
The real question though, is why do you need to authenticate with GitHub on the server? Firebase is designed to do nearly all of the development on the client.
I ended up trashing the login through Firebase and used passport-github. Thanks for the help!

Swapping Handlebars for Angular in MEAN app

I'm building a MEAN app with user authentication and I'm currently in the process of learning Angular (I like to learn by using whatever it is I'm learning in a practical way). Anyway, before I stripped the handlebars view engine and changed the view files from .hbs to .html I was able to display the username of the currently authenticated user like so:
Handlebars: {{user.username}} = req.user.username and it displays the username of the current authenticated user.
Rather than using render for rendering my pages, I'm now using sendfile:
app.get('/dashboard', Auth.ensureAuthenticated, function (req, res) {
res.sendfile('./app/views/admin.html', req);
});
I'd like to know how I go about rendering the username of the currently authenticated user in Angular.
You can send the user info by
Setting a global variable using your handlebar template.
app.get('/dashboard', Auth.ensureAuthenticated, function (req, res) {
res.render('admin',{user: user});
});
And in handlebar template add something like below
<script type="text/javascript">
window.user = {{user}};
</script>
wrap this global in angular service
angular.module('myApp').service('Global', ['$window', function($window){
function _getUser() {
return $window.user;
}
return {
user: _getUser()
};
}]);
Now in your controller, you can access the user data by injecting Global service
angular.module('myApp').controller('AdminController', ['$scope', 'Global', function($scope, Global) {
$scope.user = Global.user;
}])
User will be available in your angular partial views.
<div data-ng-controller="AdminController">
Welcome <span ng-bind="user"></span>
</div>
or you can send the information via cookie. After reading the cookie value inside _getUser function in angular service, delete the cookie.
or you can send an ajax request for fetching the data inside angular service.

Categories