Getting error while integrating "Google Identity Services" in angular13 - google-signin

I am working in angular13 and updating the "Google Sign-In JavaScript Platform Library" to "Google Identity Services".
test.component.ts
google.accounts.id.initialize({
client_id: clientId,
callback: this.handleCredentialResponse
});
google.accounts.id.renderButton(
document.getElementById("googleBtn"),
{
theme: "outline",
size: "large",
width: "300px",
type: "standard",
shape: "rectangular",
text: "'Google sign in'",
logo_alignment: "center"
} // customization attributes
);
handleCredentialResponse(response) {
var base64Url = (response.credential).split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
const responsePayload = JSON.parse(jsonPayload);
let user : any = {
id : responsePayload.sub,
name : responsePayload.name,
email : responsePayload.email,
photoUrl : responsePayload.picture,
firstName : responsePayload.given_name,
lastName : responsePayload.family_name,
provider : 'GOOGLE'
}
this.getUserData(user);
}
getUserData(user: any){
....
}
getting error: this.getUserData(user) is not a function.
I am unable to access any functions under handleCredentialResponse() function.

Related

React-Admin with .net .The response to 'getList' must be like { data : [{ id: 123, ...}, ...] }, but the received data items do not have an 'id' key

I have an ASP.NET Core Web API and a React client. I'm trying to build admin dashboard with React-Admin. My problem is when I receive the data from server, my object are with property Id (uppercase), then in console I'm getting an error
The response to 'getList' must be like { data : [{ id: 123, ...}, ...] }, but the received data items do not have an 'id' key
I tried making new test class with property id (lowercase) in my server and then the problem is gone.
How can I fix this issue?
This is my test class and its working.
public class CityModel
{
public string id { get; set; }
public string Name { get; set; }
}
[HttpGet("Cities")]
public CityModel[] GetCities()
{
var city1 = new CityModel()
{
id = "ahsxge",
Name = "Berlin"
};
var city2 = new CityModel()
{
id = "axhdagw",
Name = "London"
};
var list = new List<CityModel>();
list.Add(city1);
list.Add(city2);
Response.Headers.Add("Access-Control-Expose-Headers", "X-Total-Count");
Response.Headers.Add("X-Total-Count", list.Count.ToString());
return list.ToArray();
}
This is my component in react :
const AppAdmin = () => {
const jwt = localStorage.getItem("jwt");
const httpClient = (url, options = {}) => {
options.user = {
authenticated: true,
token: 'Bearer ' + jwt
};
return fetchUtils.fetchJson(url, options);
};
const dataProvider = jsonServerProvider('https://localhost:44366/api', httpClient);
dataProvider.getList('Cities/Cities', {
pagination: { page: 1, perPage: 15 },
sort: { field: 'Name', order: 'ASC' },
})
.then(response => console.log(response));
return (
<Admin dataProvider={dataProvider}>
<Resource name='Cities/Cities' list={CitiesList} />
</Admin>
)
}
export default AppAdmin
You can configure the json converter to use camelCase serialization int the ConfigureServices method in the Startup.cs file the following way:
services
.AddControllers()
.AddJsonOptions(opts =>
{
opts.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
})
This way you can use PascalCase properties in your c# code (which you should do), but your client will recieve camelCase json properties.

Get profile information retrieved from sign in users firebase null return

From my firebase data I`m trying to access the users information like what government agency and displayname using this example from firebase docs. When I use this example came f
{
"users" : {
"citizen" : {
"NiPS4VtdFPgVMVyhCVfMtzdP85g1" : {
"displayName" : "user-citizen",
"email" : "user#user.com",
"password" : "palls123",
"pnumber" : "123",
"repassword" : "palls123"
},
"Pba7iULL4wYkTQxHB5tpbNDj7v02" : {
"displayName" : "kevin",
"email" : "ez#ez.com",
"password" : "palls123",
"pnumber" : "545",
"repassword" : "palls123"
},
"gf2o8dhs9VhIsCK5Ui5rEizESbj1" : {
"displayName" : "kevin",
"email" : "dli#dli.com",
"password" : "palls123",
"pnumber" : "5454",
"repassword" : "palls123"
}
},
"government" : {
"bfp" : {
"AgIqgADtMeNS5d3BJTnCI0uCjcl1" : {
"displayName" : "bfp-user",
"email" : "bfp#bfp.com",
"gov_agency" : "bfp",
"gov_id" : "123",
"password" : "palls123",
"pnumber" : "1234",
"repassword" : "palls123",
"toggle" : true
}
},
"ndrmmc" : {
"XdoC2Dny5ZM69z8B2BrSWBS3CIY2" : {
"displayName" : "ndrmmc-user",
"email" : "ndrmmc#ndrmmc.com",
"gov_agency" : "ndrmmc",
"gov_id" : "123",
"password" : "palls123",
"pnumber" : "123",
"repassword" : "palls123",
"toggle" : true
}
},
"pnp" : {
"MhKiEoCtytQAHooHclSZIB3gsK42" : {
"displayName" : "pnp-user",
"email" : "pnp#pnp.com",
"gov_agency" : "pnp",
"gov_id" : "23455",
"password" : "palls123",
"pnumber" : "1234",
"repassword" : "palls123",
"toggle" : true
}
},
"rta" : {
"fehvPVwX6NXnVkf3hOyRsQBDH2Y2" : {
"displayName" : "rta-user",
"email" : "rta#rta.com",
"gov_agency" : "rta",
"gov_id" : "1234",
"password" : "palls123",
"pnumber" : "123",
"repassword" : "palls123",
"toggle" : true
}
}
}
}
I`m trying to access the users information like what government agency and displayname using this example from firebase docs. When I use this example came from the docs
var user = firebase.auth().currentUser;
if (user != null) {
user.providerData.forEach(function (profile) {
console.log(" Gov Agency : " + profile.gov_agency);
console.log(" Provider-specific UID: " + profile.uid);
console.log(" Name: " + profile.displayName);
});
}
It returns null on my side except for the uid it gives email of the user. Where did I go wrong?
PS: There are two types of user a gov client and citizen client
It is normal that you get a null value for profile.gov_agency: as detailed here, the providerData property of a User is a "non-null Array of firebase.UserInfo"
In turns, a UserInfo has a set of defined properties: email, phoneNumber, etc. So the profile does not have any gov_agency property.
You are apparently mixing up the values you can get from firebase.auth with the ones that you have saved in the real time database.
You should therefore query the database, based on the userId or on the email (depends on your data model), in order to get the values of gov_agency (and displayName) to "determine if it is a gov client or a citizen client".
To query the database, refer to https://firebase.google.com/docs/database/web/read-and-write and https://firebase.google.com/docs/database/web/lists-of-data
Note that displayName IS also property of UserInfo, but apparently you have not set it when creating the users.
Note from the doc:
currentUser might also be null because the auth object has not
finished initializing...
Try:
firebase.auth().onAuthStateChanged(user => {
if (user) {
// User is signed in.
console.log('User is signed in:', user);
} else {
// No user is signed in.
console.log('No user is signed in', user);
}
});
CMIIW

Group users in Firebase RTDB

I am using Firebase in my Qt app for Authentication and Realtime Database features, when users register they need to be assigned into the selected groups then departments of that group. Each group will have admin(s), who can access the entire group database, but the users will only access their department.
Below is my code for my registration form which assigns certain user values, how would i go about grouping the users in the database with additional options on my registration form?
onUserRegistered: {
indicator.stopAnimating()
console.debug("User login " + success + " - " + message)
if(success) {
loginDialog.title = "Success!"
firebaseDb.setUserValue("Firstname", firstname.text)
firebaseDb.setUserValue("Surname", surname.text)
} else {
loginDialog.title = "An Issue occured!"
}
loginDialog.text = message
loginbutton.visible = true
registerCheckbox.visible = true
loginDialog.open()
}
I would like my database to be laid out as below, if this is appropriate for use? Multiple location groups with users within to access thier part of the database!
{
"groups" : {
"Colchester" : {
},
"Ipswich" : {
},
"CanaryWharf" : {
"Departments" : {
"Admin" : {
"members" : {
"user1" : true
}
},
"Assistant" : {
"members" : {
"user2" : true
}
},
"Reception" : {
"members" : {
"user3" : true,
"user1" : true
}
},
"Stylist" : {
"members" : {
"user4" : true
}
},
"Technician" : {
"members" : {
"user5" : true
}
}
}
}
}
Without access to the Firebase Cloud Firestore collections, detailed in the link;
Google Firebase Cloud Firestore Collections
I achieved the result of grouping of my users by the following code, if anyone still wants to add an improved version please do, but for now this works as intended for me:
App {
id: app
property var groupName
property var subGroupName
//these values are assigned when my user logs in from user values
//set in firebase on registration
firebaseDb.getUserValue("group", {
}, function(success, key, value) {
if(success){
groupName = value
console.log("GROUPNAME LOG: " + groupName)}})
}
//I then use these values across my app when storing data in the database
//an example of which is an AppButton elsewhere in my app
AppButton {
id: saveButton
onClicked: {
userData = ({"date": calendar.selectedDate, "name": userName +" "+ userSurname, "details": dayCycle.text, "status": "pending"})
var time = new Date().getTime()
firebaseDb.setValue("groups" + "/" + groupName + "/" + subGroupName + "/" + time, userData)
}
}

Looping through firebase unique keys and adding data to each

I have firebase database in this form.
"items":{
"-Jp9VLYBwENfNVLKYyCG" : {
"-Jp9VMKkTUggcMrUCO8S" : {
"author" : "facebook:#########",
"created" : 1431474107638,
},
"-Jp9VobJP0qbSbbEdyW0" : {
"author" : "facebook:#########",
"created" : 1431474227548
}
},
"-JpEbifKeRj-_H7TWhQ2" : {
"-JpEbrnT6SFRFc6U_HWX" : {
"author" : "facebook:#########",
"created" : 1431559961683
},
"-JpEby5mZuQMsU-9YCpk" : {
"author" : "facebook:##########",
"created" : 1431559987495
}
}
}
I want to add the following object to each $id containing author and created key-value pairs.
upVote: {
active: true,
total: 0
},
downVote: {
active: true,
total: 0
}
I am first trying to fetch the values using DataSnapshot. But it doesn't print the keys in console. What is wrong here?
var ref = new Firebase(FBURL + "/items");
ref.once("value", function(snapshot) {
console.log("snapshot key: " + snapshot.key());
snapshot.forEach(function(childSnapshot){
var key = childSnapshot.key();
var val = childSnapshot.val();
console.log("child snapshot key: " + key);
childSnapshot.forEach(function(deepSnap){
console.log("deep shot key: " + deepSnap.key());
});
});
});
RESOLVED The problem was that I had some security rules set up with read and write permissions. Therefore wasn't allowing me to read the element from the user scope that I was calling the script. It was one gotcha like problems.
After this step, it was easy to update the database with values:
var deepRef = ref.child(key).child(deepSnap.key());
deepRef.update({upVote: {
active: true,
total: 0
},downVote: {
active: true,
total: 0
}});

Meteor - New user created after validating login is not recognized

I have a login validation function setup to check if a new user registered outside of the app. That users info is stored in a temporary collection. If the users info validates I want to be able to use Accounts.createUser on the Client side, but I can't figure out how to do that. The documentation says that "registered validate login callbacks are called with a single argument, the attempt info object", but I can't find any examples of how to do this.
environment.js
Accounts.config({
forbidClientAccountCreation : true
});
server.js
Accounts.validateLoginAttempt(function(info){
if (!info.allowed)
{
var userEmail = info.methodArguments[0].user['email'].toLowerCase();
var userPass = info.methodArguments[0].password['digest'];
// check if this is a temp user
if (tmpUsers.find({'email': userEmail}).count() == 1)
{
var user = tmpUsers.findOne({'email': userEmail})
// check for active
if (user.active == "Yes")
{
// check password
if (userPass == user.password)
{
var accountId = Accounts.createUser({
'password': userPass,
'email': userEmail,
'profile': ({'acctType': user.type})
});
return true;
} else {
throw new Meteor.Error(403, "Incorrect password.");
return false;
}
} else {
throw new Meteor.Error(403, "Your account has yet to be activated.);
return false;
}
} else {
throw new Meteor.Error(403, "Can not find user " + userEmail);
return false;
}
} else {
return true;
}
});
Update:
I ended up putting the Account.userCreate part on the server side and now it does get the user created but when I try to login I get "Email already exists." So it appears as though it doesn't expect the login to be successful and tries to create the user again.
{ // This user works
"_id" : "hCBLo3AJJwmtR6s62",
"createdAt" : ISODate("2014-12-26T20:27:58.44Z"),
"services" : {
"password" : {
"bcrypt" : "$2a$10$pxlEy.JFomgwQwV2cpm72.TBG4.llP98BF9ssTCptC4WsekLzJO9G"
},
"resume" : {
"loginTokens" : []
}
},
"emails" : [{
"address" : "demo#demo.com",
"verified" : false
}]
}
{ // This one does not
"_id" : "w6SGuqJJPs5LoCTTj",
"createdAt" : ISODate("2015-01-10T20:54:16.032Z"),
"services" : {
"password" : {
"bcrypt" : "$2a$10$VJFj0UOrQiLs7djfGWAeMeruDactDFrl1nlEsXh/r5Z/895C5ubAW"
}
},
"emails" : [{
"address" : "demo2#demo.com",
"verified" : false
}],
"profile" : {
"acctType" : null
}
}
Would something like this work for you?
var options = {
username: "username", // you'll need to fill this in
email: userEmail,
password: userPass,
profile: {name: "name"} // you'll need to fill this in
};
Accounts.createUser(options, function (error) {
if (error) {
console.log("Cannot create user");
}
});

Resources