I am working on angular firebase web app, in which as soon as admin login, he can create users by his own.
When admin log in , he is authenticated with firebase.auth()
But what is happening is, as admin creates a new user, the current auth details(admin) gets replaced by newly created user. I want the user creation without creating a newer session
Have a look at my controller:
app.controller('UserAdd', ['$scope','$sessionStorage','$http','$firebaseAuth', '$firebaseArray', '$location' ,'$firebaseObject', 'FBURL', function($scope,$sessionStorage,$http,$firebaseAuth,$firebaseArray, $location ,$firebaseObject, FBURL){
var user = firebase.database().ref().child("users");
$scope.user_auth_data = firebase.auth().currentUser;
$sessionStorage.uID = $scope.user_auth_data.uid ;
$scope.access_points= [];
$scope.teams = [];
$scope.org_details = [];
user.child($sessionStorage.uID).child("OrganizationId").on('value',function(org_id){
$sessionStorage.org_id = org_id.val();
})
user.child($sessionStorage.uID).child("ImagePath").on('value',function(img){
$scope.user_image = img.val();
})
//access points
firebase.database().ref().child("organization").child($sessionStorage.org_id).child("access_points").on('value',function(access_points){
angular.forEach(access_points.val(),function(ap,key){
$scope.access_points.push({id:key,ssid:ap.SSID,bssid:ap.BSSID,display_name:ap.DisplayName,lat:ap.Latitude,lng:ap.Longitude});
})
});
var obj = $firebaseArray(firebase.database().ref().child("organization").child($sessionStorage.org_id).child("access_points"));
obj.$loaded(
function(data) {
},
function(error) {
console.error("Error:", error);
}
);
firebase.database().ref().child("organization").child($sessionStorage.org_id).child("teams").on('value',function(teams){
angular.forEach(teams.val(),function(team,key){
$scope.teams.push({id:key,team_name:team.TeamName,team_leader:team.TeamLeader,channel_name:team.ChannelName});
})
});
var obj = $firebaseArray(firebase.database().ref().child("organization").child($sessionStorage.org_id).child("teams"));
obj.$loaded(
function(data) {
},
function(error) {
console.error("Error:", error);
}
);
$scope.selectItem = function(){
};
//add user
$scope.addUser = function() {
firebase.auth().createUserWithEmailAndPassword($scope.Email, $scope.Password)
.then(function(user) {
//adding single values in user node
var ref = firebase.database().ref().child("users").child(user.uid);
ref.set({
EmployeeId: $scope.emp_id,
Contact: $scope.Contact,
DOB: $scope.date_of_birth,
Designation: $scope.Designation,
Email: $scope.Email,
FirstName: $scope.FirstName,
LastName: $scope.LastName,
OrganizationId: $sessionStorage.org_id,
Gender: $scope.selectedGender,
IsAdmin: false
});
$scope.selectedAccess.forEach(function(access_values){ //adding nested access_points
var ref1 = firebase.database().ref().child("users").child(user.uid).child("AccessPoint").child(access_values.id);
ref1.set({
SSID: access_values.ssid,
BSSID: access_values.bssid,
DisplayName: access_values.display_name,
Latitude: access_values.lat,
Longitude: access_values.lng
});
});
$scope.selectedTeam.forEach(function(team_values){ //adding nested team
var ref2 = firebase.database().ref().child("users").child(user.uid).child("team").child(team_values.id);
ref2.set({
ChannelName: team_values.channel_name,
TeamName: team_values.team_name,
TeamLeader: team_values.team_leader
});
});
$scope.teams.forEach(function(team_values){
var ref3 = firebase.database().ref().child("organization").child($sessionStorage.org_id).child("channels").child(team_values.channel_name).child("info").child("users");
ref3.child(user.uid).set($scope.FirstName+" "+$scope.LastName);
var ref4 = firebase.database().ref().child("organization").child($sessionStorage.org_id).child("user_team").child(team_values.team_name).child(user.uid);
ref4.set($scope.FirstName+" "+$scope.LastName);
});
firebase.auth().sendPasswordResetEmail(user.email);
$location.path('/user_list');
}).catch(function(error) {
console.log(error);
});
};
}]);
Whats needs to be done to remain in same admin session instead of a new one?
Related
$scope.authenticateGoogle = function(google) {
var params = {
'clientid':'something',
'cookiepolicy':'single_host_origin',
'callback': function(result){
if(result['status']['signed_in']){
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp){
$scope.$apply(function(){
//
});
});
});
}
},
'approvalprompt':'force',
'scope':'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read'
};
gapi.auth.signIn(params);
};
Users land on the permissions screen upon every login.
How can I fix this code?
Google says that for basic information it does not require approval.
Please guide me.
Thanks a ton in advance
You're good try remove 'approvalprompt':'force',
$scope.authenticateGoogle = function(google) {
var params = {
'clientid':'something',
'cookiepolicy':'single_host_origin',
'callback': function(result){
if(result['status']['signed_in']){
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp){
$scope.$apply(function(){
//
});
});
});
}
},
'scope':'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read'
};
gapi.auth.signIn(params);
};
I'm trying to do a simple CRUD with ionic (v1) and angularfire. I can read and delete records but I need to edit and create. The actual problem is angularfire function $add`, this function doesn't do anything and doesn't return any error in the console. I have this code:
$scope.users = $firebaseArray(root.ref('/users/'));
$scope.user = {};
//Create
$scope.title = "New user"
$scope.button = "Create";
$scope.icon = "ion-person-add";
$scope.submit = function () {
var data = {
name: $scope.user.name,
username: $scope.user.username,
email: $scope.user.email,
street: $scope.user.street,
suite: $scope.user.suite,
city: $scope.user.city,
lat: $scope.user.lat,
lng: $scope.user.lng,
phone: $scope.user.phone,
website: $scope.user.website,
}
console.log(data);
$scope.users.$add(data).then(function (ref) {
console.log('contact added with Id: ' + id);;
})
Apparently the code is fine, but doesn't return console.log so maybe had some errors. Any ideas?
Well to find out if there is any error Javascript then takes to call back one for success and the other for failure something like the code below
$scope.user.$add(data).then(function (success){
return console.log(success);
}, function(error){
return console.log(error);
})
Now that's for then that way you can log returned errors
Error fixed.
$scope.users = $firebaseArray(root.ref('/users/'));
$scope.user = {};
//Create
$scope.title = "New user"
$scope.button = "Create";
$scope.icon = "ion-person-add";
$scope.submit = function () {
var data = {
name: $scope.user.name,
phone: $scope.user.phone,
email: $scope.user.email,
username: $scope.user.username,
city: $scope.user.city,
lat: $scope.user.lat,
lng: $scope.user.lng,
street: $scope.user.street,
suite: $scope.user.suite,
website: $scope.user.website,
zipcode: $scope.user.zipcode,
}
$scope.users.$add(data).then(function (response) {
if (response) {
$ionicPopup.alert({
title: '<div><i class="ion-checkmark-circled"></i></div>',
subTitle: '<h4>The user <b>' + data.name + '</b> is added.</h4>',
});
}
$scope.user=null;
With that all works properly and modal shows when we add user.
I'm using angular-fullstack-generator.
I'm having trouble with passing _id parameter to some function.
What I'm trying to achieve is after I created a user I want to create another Data in schema referencing to user's id
therefore here is my code
'use strict';
class SignupVendorController {
//end-non-standard
constructor(Auth, $state, $http) {
this.Auth = Auth;
this.$state = $state;
this.$http = $http;
this.submitted = false;
}
//start-non-standard
register(form) {
this.submitted = true;
if (form.$valid) {
this.Auth.createUser({
firstName: this.user.firstName,
lastName: this.user.lastName,
email: this.user.email,
password: this.user.password,
role: 'vendor'
})
.then( Auth => {
this.vendor = Auth.getCurrentUser;
this.createVendor(this.vendor._id);
console.log('user is ' + this.vendor.firstName);
console.log('vendor created');
// Account created, redirect to home
this.$state.go('main');
})
.catch(err => {
err = err.data;
this.errors = {};
// Update validity of form fields that match the mongoose errors
angular.forEach(err.errors, (error, field) => {
form[field].$setValidity('mongoose', false);
this.errors[field] = error.message;
});
});
}
}
createVendor(id) {
var vendor = {
category: ['publishing'],
_owner: id
}
this.$http.post('/api/vendors', vendor);
}
}
angular.module('aApp')
.controller('SignupVendorController', SignupVendorController);
I've tried several syntax modification but it all just got undefined variable on this.vendor.
like this, for instance
var vendor = Auth.getCurrentUser;
console.log('the user is ' + vendor.firstName);
the code cannot read either _id or firstName.
Any kind of help would be very appreciated.
Thank you !
Can you try this?:
this.vendor = Auth.getCurrentUser();
console.log('the user_id is ' + this.vendor._id);
In my App, that's working.
Background:
I have the following setup to authenticate retrieve my user and then retrieve his credentials. I am unclear on the event loop even after reading the documentation.
The Question:
The user is not displayed until I click a button? Every other kind of function runs on initialization like the alerts and stuff but why is my retrieve user function working until another button is pressed (pressing any button )?
Summary:
In order to retrieve the username for some reason I need to click something. I want the username to be retrieve on initialization .
crossfitApp.controller('globalIdCtrl', ["$scope",'$q','defautProfileData','$timeout', function ($scope,$q,defautProfileData,$timeout) {
$timeout(function() {
var dataRef = new Firebase("https://glowing-fire-5401.firebaseIO.com");
$scope.myFbvar =null;
$scope.authenticated={
currentUser: null,
avatarUrl: "",
emailAddress: "",
settings: "",
currentUserid: null,
};
function getProfile(userID){
myprofile= new Firebase("https://glowing-fire-5401.firebaseio.com/profiles/"+userID+"/username");
myprofile.once('value', function(nameSnapshot) {
$scope.authenticated.currentUser = nameSnapshot.val();
});
};
$scope.auth = new FirebaseSimpleLogin(dataRef, function(error, user) {
if (error) {
//Error
console.log ('error');
}
else if (user) {
//logged in
$scope.$apply(function(){getProfile(user.id);})
console.log('logged in');
$scope.authenticated.currentUserid = user.id ;//
}
else {
// user is logged out
console.log('logged out');
$scope.authenticated.currentUserid =null;
$scope.authenticated.currentUserid =null;
}
});
},100);
}]); //GlobaldCtrl
I would move most of your code to a service, and call the service from your controller, like this. I also included a deferred object in your login as I bet this is async
crossfittpApp.service('firebase',function($q) {
return {
getUser : function(authenticated) {
var dataRef = new Firebase("https://glowing-fire-5401.firebaseIO.com"),
myFbvar =null,
getProfile(userID) {
myprofile= new Firebase("https://glowing-fire-5401.firebaseio.com/profiles/"+userID+"/username");
myprofile.once('value', function(nameSnapshot) {
authenticated.currentUser = nameSnapshot.val();
});
},
deferredObj = $q.defer();
auth;
auth = new FirebaseSimpleLogin(dataRef, function(error, user) {
if (error) {
//Error
console.log ('error');
deferObj.reject();
}
else if (user) {
//logged in
getProfile(user.id);
console.log('logged in');
authenticated.currentUserid = user.id ;
deferObj.resolve(auth);
}
else {
// user is logged out
console.log('logged out');
authenticated.currentUserid =null;
deferObj.resolve();
}
}
return deferObj.promise;
}
}
});
crossfittpApp.controller('globalIdCtrl',function(firebase) {
$scope.authenticated = {
currentUser: null,
avatarUrl: "",
emailAddress: "",
settings: "",
currentUserid: null,
};
firebase.getUser(authenticated)
.then(function(_auth) {
$scope.auth = _auth;
},
function() {
//auth error here
});
});
You're not triggering Angular's HTML Compiler, so Angular doesn't know you've changed the JS variables.
Whenever you use an event like ng-click/ng-submit/etc, Angular fires $scope.$apply(), which checks for any changes to your $scope variables and applies them to the DOM, which is why it shows up after this.
You can correct this issue by alerting Angular that it needs to run $apply by using $timeout:
angular.controller('MyController', function($timeout) {
myprofile= new Firebase("https://glowing-fire-5401.firebaseio.com/profiles/"+userID+"/username");
myprofile.once('value', function(nameSnapshot) {
$timeout(function() {
authenticated.currentUser = nameSnapshot.val();
});
});
auth = new FirebaseSimpleLogin(dataRef, function(error, user) {
if (error) {
//Error
console.log ('error');
}
else if (user) {
$timeout(function() {
authenticated.currentUserid = user.id ;
});
}
else {
$timeout(function(){
authenticated.currentUserid =null;
});
}
});
});
You should utilize angularFire, which abstracts these complexities.
There are some more questions like this one here, here, and here.
I am connecting AngularJS with MongoLab and trying to update the "users" collection.
AngularJS resource service:
angular.module("myApp.services", ["ngResource"])
.constant({
DB_URL: "https://api.mongolab.com/api/1/databases/mydb/collections/users/:id",
API_KEY: "[SOME_RANDOM_KEY]"
})
.factory("UsersService", ["$resource", "DB_URL", "API_KEY", function($resource, DB_URL, API_KEY) {
return $resource(DB_URL, { apiKey: API_KEY, id: "#_id.$oid" }, { update: { method: "PUT" }});
}]);
This is how I am trying to update my users collection:
angular.module("myApp", ["myApp.services"])
.controller("AppController", ["$scope", "UsersService", function($scope, UsersService) {
$scope.users = [];
$scope.getAllUsers = function() {
$scope.users = UsersService.query();
};
$scope.updateUser = function(user) { // user: firstName, lastName, email
//delete user._id;
UsersService.update({}, user, function() {
$scope.users = UsersService.query();
console.log("Users updated successfully");
}, function() {
console.log("Some problems updating the user", arguments);
});
};
}]);
When I try to update the user information, it throws an exception stating:
{ "message" : "cannot change _id of a document old:{ _id: ObjectId('[SOME_RANDOM_KEY]'), firstName: \"Anup\", lastName: \"Vasudeva\", email: \"anup.vasudeva#emal.com\" } new:{ _id: {}, firstName: \"Anup\", lastName: \"Vasudeva\", email: \"anup.vasudeva#email.com\" }"
I am new to MongoDB, so I don't understand why it is creating an empty _id object for the new user instance?
Try changing your $scope.updateUser function to the following:
$scope.updateUser = function (user) {
var userId = user._id.$oid;
user._id = undefined;
UsersService.update({id: userId}, user, function () {
$scope.users = UsersService.query();
console.log("Users updated successfully");
}, function () {
console.log("Some problems updating the user", arguments);
});
};
The update/replacement object ('user'), should not contain the _id property when being passed to UsersService.update(). Mongo will not replace the _id value, so the id will stay the same after the update.
One other thing that's changed in this function is that we're passing the user id as the first parameter of the UsersService.update() function so that mongo knows which document to update.