I'm working on a website with Parse.com and JavaScript. I have my "User" class, but I have added more fields than those that come by default.
I want to get one specific attribute from my User class (IdGroup) when user logs in, so I'm trying to capture the IdGroup using user object when login has been succesfully.
I have tried this:
Parse.User.logIn(username, pass, {
success: function (user) {
//var idGroup = user.get("IdGroup");
localStorage.setItem("parseUser", true);
localStorage.setItem("guestUser", false);
localStorage.setItem("username", username);
user.fetch().then(function (fetchedUser) {
var idGroup = user.get("IdGroup");
localStorage.setItem("IdGroup", idGroup);
});
window.location.href = 'index.html';
},
error: function (user, error) {
alert('Invalid username or password!');
}
});
This doesn't work.
If anyone could give me a hand, I will really appreciate.
Thanks!!
I would have assumed that the user was already fetched at login.
But your callback function passes in the object fetchedUser, and you're accessing the user object. So, var idGroup = fetchedUser.get("IdGroup"); is probably what you're looking for.
Related
I'm trying to update/add data on firebase. I used the Facebook login and I want to use the UserID as a key for the new data aded.
(check pict below)
The userID that I want to use it:
I want to replace that key with the userID:
fblogin(){
this.facebook.login(['email'])
.then(res=> {
const fc = firebase.auth.FacebookAuthProvider.credential(res.authResponse.accessToken);
firebase.auth().signInWithCredential(fc)
.then(fs => {
this.facebook.api('me?fields=id,name,email,first_name,picture.width(720).height(720).as(picture_large)', []).then(profile => {
this.newuser = {name: profile['first_name'] ,email: profile['email'],picture: profile['picture_large']['data']['url'],phone:''}
this.navCtrl.push(HomePage);
console.log(fs.uid);
this.db.list('/users/'+ fs.uid).update(this.newuser);
});
I got this error in compilation:
supplied parameters do not matchany signature of call target
In this line: this.db.list('/users/'+ fs.uid).update(this.newuser);
Any help?
The FB error looks correct. You cant update on the uid as the user has been saved with a unique FB id
You do not show the code that created the users record in the database, but what i think you want to do is set and object when you first save the users record. However this could be an issue because the user could be saved before the return of the uid. I cant tell with your code snippet. Regardless, I will write the code that i think will work if the users/ record is created at the time that of registration.
The service
async signupUser(email: string, password: string) {
try {
const result = await this.afA.auth.createUserWithEmailAndPassword(email, password);
return result;
} catch (err) {
console.log('error', err);
}
}
So this initially creates a user without facebook, The key here is that the users FB uid was created and is held in the returned result
The component
this.authData.signupUser(email,password).then(userData => {
console.log(userData) // <- this is result
}
Then we create a record in FB with the uid returned
this.db.object(`users/${userData.uid}/`).set(data);
.set(data) is whatever data you want to save in the users/uid namespace.
So basically you need to create that user table with its uid namespace when the user first registers. Then you can update the user with the uid returned from the facebook fs.uid
With your current code you could find the user based on the email ( because the email should be unique to all users) and then update ...
with lodash is it just
let foundUser = find(this.db.list('users'),{ 'email' : fs.email }
// and then update based on the object key
this.db.list('/users/'+ Object.keys(foundUser)).update(this.newuser);
i fixed the problem by using:
this.db.object('/users/'+ fs.uid).update(this.newuser);
instead of :
this.db.list('/users/'+ fs.uid).update(this.newuser);
And it works correctly !
Thanks all for help.
As part of my studies I need to develop web-app (javasript language) Where we work with firebase realtime database.
currently inside the database,I have a tree of users objects that representing all the users who registered to the system. And what I'm trying to do is a simple user login function.
After the user entered his username and his password, I created an array to enter the entire user tree from a database. The problem is that when im calling the function from the Firebase it's not enough to ended.. and what happens is that the array remains empty and you can not verify that the user is registered on the system.
now I have used a temporary solution that Im using setTimeout function,I understand that this is wrong programming, and also i do not want the user to wait 2 seconds every time he wants to login to the system.
Can someone please help me? how to do it right without the setTimeout function?
I want that the function of the Firebase ends so only then start with the Authentication process.
Here is the code I wrote so far,
var correntUser;
var userlist = [];
var usersRef = database.ref('users');
// Query that inserts all users keys and names to an array.
usersRef.orderByChild("username").on("child_added", function(snapshot)
{
userlist.push({userKey:snapshot.key,username:snapshot.val().username,password:snapshot.val().password});
});
setTimeout(function()
{
//check if user exist in userlist.
for(var i=0; i<userlist.length;i++)
if (userlist[i].username == usernameArg && userlist[i].password == passwordArg)
correntUser = userlist[i].userKey;
if(correntUser == undefined)
{
//check if undefined
alert("wrong username or password");
document.getElementById("username").value = "";
document.getElementById("password").value = "";
return;
}
mainPage.addHeader();
},2000);
thank you all.
There is no need to manually check all users and see if there is a match with the attempted login credentials when Firebase provides built-in authentication. Password-based accounts require email addresses, although you can combine the username with any domain name to satisfy that requirement as suggested here.
You did not explain what your database structure looks like under the users path, but one way to handle that is to incorporate the user's unique id that gets returned as part of the createUserWithEmailAndPassword password:
function createAccount(email, password) {
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function(userData) {
// account created successfully
usersRef.child(userData.uid).set({
email: email,
creation_date: new Date(),
...
})
}
.catch(function(error) {
...
})
}
Then for login attempts:
function login(email, password) {
firebase.auth().signInWithEmailAndPassword(email, password)
.then(function(userData) {
// login successful
mainPage.addHeader();
})
.catch(function(error) {
alert("wrong username or password");
document.getElementById("username").value = "";
document.getElementById("password").value = "";
})
}
I have Parse table with entities.
User - default class
Commets - class with pointer to _User entity.
I need to delete user from entity User together with all its comments, located in Comments entity:
Right now I have JS Cloud code:
Parse.Cloud.define("deleteUser", function(request, response) {
var User = Parse.Object.extend("User");
var query = new Parse.Query(User);
var userID = request.params.userID;
query.get(userID,{
success: function(User) {
var message = 'success';
User.destroy({
useMasterKey: true ,
success:function() {
response.success(message);
return;
},
error:function(error) {
response.error('Could not delete object '+ User.id);
return;
}
});
},
error: function(object, error) {
var message = 'User could not found';
response.error(message);
}
});
});
It's removing user only.
How I can combine to remove also records from other entity by user?
Thanks for advance
As eth3lbert pointed out in the comments, you should use an afterDelete hook that gets called after the User object has been deleted. You can kick off any other delete operations you want.
However, there is a little gotcha, the before* and after* methods get killed after 3 seconds of wall clock time which might lead to unwanted results depending on the amount of data that you need to delete.
The best solution for you is to setup a background job (they can run for up to 15 minutes), schedule it to run, lets say once every day, and do any cleanup work in that job.
You could create a simple table for that, that contains the objectIds of deleted users, whenever your afterDelete method gets called, you add the deleted users id into that table, your background job then queries that table on run and deletes the content that was associated with it.
You can delete user easily from user request as below.
Parse.Cloud.define('deleteUser', async (req) => {
const user = req.user;
return user.destroy({ useMasterKey: true});
})
and add additional deleting logic related to User.
I've been doing some research into how I can add data based on the login credentials. as an example scenario lets say I want a user to login to the application and then based on there login, add there hours they have done for that day, so like a timesheet application.
I don't want the user that is logged in to see any other names other
than there own.
the browse screen would show only there times they have submitted
rather than everyones aswell.
when using the insert call method in (_customnameDataService.cs) you can add in a username by associating a field within a table like below:
entity.Username = Application.User.Name
so if this is possible there must be a way of calling this in JavaScript when logging in so any help or pointers would be great help. Adding a DataItem and displaying the username would be most preferable. (using edit render code) then from this I can pass it through the hierarchy and display only the information associated with the logged in user.
follow these steps to achieve the above question:
Google GetUserName.ashx to get the code for this file to add to your
Lightswitch HTML Project.
copy the below function into the javascript file (in my case a Browse screen for my users)
function CallGetUserName(operation) {
$.ajax({
type: 'post',
data: {},
url: '../web/GetUserName.ashx',
success: operation.code(function AjaxSuccess(AjaxResult) {
operation.complete(AjaxResult);
})
});
}
For the users that can login in and access the Lightswitch Application, the user information must be stored somewhere, in my case "tbl_Users". This table has a row called username. Using the below code this enables an administrator or someone high up in the hierarchy to access all the users, and also the specific user referenced in the table to access themselves.
myapp.BrowseUsers.username_postRender = function (element,
contentItem) {
msls.promiseOperation(CallGetUserName).then(function PromiseSuccess(PromiseResult) {
if (PromiseResult == 'TestUser' || PromiseResult == 'administrator') {
} else {
contentItem.value = PromiseResult;
}
});
};
What is actually happening?
The function is calling the GetUserName.ashx file, which in turn retrieves the current user logged in. (from the aspnet_Users table which is automatically created) I have used a foreign key to associated my table (tbl_Users) and aspnet_Users together.
in the debug or release environment if you were to add a data item (string) and display this information, it would return ("TestUser")
myapp.BrowseUsers.displayUsername_postRender = function (element,
contentItem) {
msls.promiseOperation(CallGetUserName).then(function PromiseSuccess(PromiseResult)
{
element.innerText = PromiseResult;
}); };
I have a facebook application where I need to get the name, category list of user like pages.
I have added 'user_likes' to my permission list and successfully got the permission to access user like page list.
What I want to know is how to access these details and assign them into variables?
I tried bellow code
FB.Event.subscribe("auth.login", function (response) {
FB.api('/me/likes', function(user) {
if (user) {
var pageCount = user.data.length; //just try to get the length to check wheter it works
// I want to add name and category into variables here
});
});
And it assign '184' to the pageCount which means it works. I want to access name and category list
Can anyone please tell me how to do this?
Just used bellow code to get the data
FB.Event.subscribe("auth.login", function (response) {
FB.api('/me/likes', function(user) {
if (user) {
var pageCount = user.data.length;
var pageName = user.data[0].name;
var pageCategory = user.data[0].category;
});
});
This will assign the name and category of first liked page, use for loop to get all data