getter called on null in flutter gives error screen - user-interface

I have a login and an update profile screen after the login. here I am setting the user profile in the genesis method. I am facing weired issue. most of the time I get the below screen where I do have the information for the user. the specific column is gender where it was called on null is the error.
//store user data
_user = new UserModel(
id: data['collection']['userData']['id'].toString(),
name: data['collection']['userData']['name'],
email: data['collection']['userData']['email'],
phone: data['collection']['userData']['phone_number'].toString(),
avatar: data['collection']['userData']['avatar'],
age: data['collection']['userData']['age'].toString(),
gender: data['collection']['userData']['gender'].toUpperCase().toString() ?? 'MALE',
totalscore: 100,
// totalscore: data['collection']['userData']['total_sessions_count'],
totaldays: data['collection']['userData']['total_session_by_days_count'],
);
and above is the code in genesis method which stores the data locally.
in user profile update screen code is as following:
Widget build(BuildContext context) {
final userProvider = Provider.of<Genesis>(context, listen: false);
_user = userProvider.user;
print('------------------------------------');
print(_user);
print('------------------------------------');
if(_firsTime){
setState(() {
_gender = _user.gender.toUpperCase() ?? _gender;
_nameController.text = _user.name;
_emailController.text = _user.email;
_ageController.text = _user.age;
_phoneController.text = _user.phone;
_avatar = _user.avatar ?? 'https://placehold.it/200x200';
_firsTime = false;
});
}
}
what is the issue here ?

You can try it
_gender = _user?.gender?.toUpperCase() ?? _gender;

From the error message, it is pretty clear that you are calling the 'gender' on null.
check whether your _user is null or not before accessing it's properties.

Related

Parse Cloud Code Setting Relation On User Class

I have an issue with not getting some cloud code to run in Parse. Currently, I pass an objectId of another user who I want to set a review for. In client side, I am saving the review, and capturing that object. I pass that as well up to cloud code. Both show up there, but I cannot figure out the right way to set the relation on this user and apply that review that was created. Code snip is below. Any help would be appreciated before I bang my head against a wall.
Parse.Cloud.define("addReview", async (request, response) => {
let { userObjId, reviewObj } = request.params;
const query = new Parse.Query(Parse.User);
//get the user object to post review of
try{
let object = await query.get(userObjId, {useMasterKey: true});
console.log(object);
console.log("running");
object.set('Reviews', new Parse.Object(reviewObj));
object.save(null, { useMasterKey: true })
return ("saved relation and updated reviews");
} catch (err){
throw new Error(err.message)
}
});
I assume
reviewObj is the review object, the user recently created.
and in your User class, you got a to-many-relation to Review class, named 'Reviews'.
First I'd suggest to name your user object user instead of object, to make it clearer what you're dealing with and make your code easier to understand.
Since you said, the review object is already successfully saved on server side, I'd recommend to transmit only the reviewId in your request.
To add an object to a relation, you first need to get the relation property of your user object:
const reviewsRelation = user.relation('Reviews');
Then to add the object to the relation just call:
reviewsRelation.add(user);
In total, your snippet should look like this:
Parse.Cloud.define("addReview", async (request, response) => {
let { userObjId, reviewObjId } = request.params;
const userQuery = new Parse.Query(Parse.User);
const reviewQuery = new Parse.Query(Parse.Review);
//get the user object to post review of
try{
let user = await userQuery.get(userObjId, {useMasterKey: true});
let review = await reviewQuery.get(reviewObjId, {useMasterKey: true});
console.log(user);
console.log("running");
const reviewsRelation = user.relation('Reviews');
reviewsRelation.add(review);
user.save(null, { useMasterKey: true })
return ("saved relation and updated reviews");
} catch (err){
throw new Error(err.message)
}
});

Roles added to the user does give false in IsInRole

I am trying to use [Authorize(Roles = "Administrator")]
But I always get "Access denied".
To test if i added the roles correct i added the following code in my controller:
var test=User.IsInRole("Administrator");
var user = await userManager.GetUserAsync(User);
var roles =await userManager.GetRolesAsync(user);
rolesOfUser = roles.ToList();
Have I added the role wrong?
Why does IsInRole always return false? is suggesting that the user is not signin or completed all authentication process. If the is the case how do i do that?
Seeding data:
public async Task SeedAsync()
{
context.Database.EnsureCreated();
if (await roleManager.RoleExistsAsync("Administrator") == false)
{
await roleManager.CreateAsync(new IdentityRole("Administrator"));
}
var user = await userManager.FindByEmailAsync("Jakob.Madsen#********.com");
if (user == null)
{
user = new IdentityUser()
{
UserName = "Jakob.Madsen#*********.com",
PhoneNumber = "*********",
Email = "Jakob.Madsen#*********.com",
};
var result = await userManager.CreateAsync(user, "*********");
if (result == IdentityResult.Success)
{
userManager.AddToRoleAsync(user, "Administrator").Wait();
}
else
{
throw new InvalidOperationException("Could not create Administrator");
}
}
var resultRoles = await userManager.GetRolesAsync(user);
if (resultRoles.Contains("Administrator") == false)
{
userManager.AddToRoleAsync(user, "Administrator").Wait();
}
}
Update:
I follow this ASP .Net Core Identity Role Claims not adding to User as suggested.
And it now works.
The IsInRole method and [Authorize(Roles="Administrator")] attribute check whether an identity that this claims principal possesses contains a claim of type ClaimsIdentity.RoleClaimType(http://schemas.microsoft.com/ws/2008/06/identity/claims/role) where the value of the claim is equal to the value specified by the role parameter.
So to summarize, if you call IsInRole, by default the assumption is that your claims representing roles have the type mentioned above – otherwise the role check will not succeed. You can confirm that by listing the claims :
var claims = User.Claims.ToList();
You haven't provide how you seed the roles , but you can find a lot of code samples :
ASP.NET Core 2.0: Getting Started With Identity And Role Management
.NET Core 2.1 Use Role Management
Also don't forget to logout and login again to see the desired behavior .

Sequelize callback before save() is finished

here is my code:
//Models definition
var User = sequelize.define('user', ...);
var Address = sequelize.define('address', ...);
var Club = sequelize.define('club', ...);
//Club scopes
scopes: {
withUser: {
include: [
{ model: User }
]
},
//Models associations
User.hasOne(Address);
Club.hasOne(User);
Club.hasOne(Address);
//Main
//Create address
var addressToCreate = {};
if(body.address) addressToCreate.address = body.address;
if(body.city) addressToCreate.city = body.city;
if(body.zipCode) addressToCreate.zipCode = body.zipCode;
//Get user from db
var user = await User.findByPk(body.user);
var clubToCreate = { name: body.name, phone: body.phone };
//Persist Address in db
return Address.create(addressToCreate)
.then(address => {
//Persist club in db
return Club.create(clubToCreate)
.then(club => {
//Associate User and Address to Club
club.setAddress(address);
club.setUser(user);
//Save club with associated models
return club.save()
})
.then(club => Club.scope('withUser').findByPk(club.id))
.then(club => { console.log(club); return club; })
})
In my db, table address contains userId and clubId and table user contains clubId;
This code seems to work to create and associate models. But the final club displayed by console.log shows user: null
However, in db there is the good row in table user with the good foreign key who reference the club id
My logs show that the request select (from Club.findByPk) is done before the update (from club.save). Like .then is executed before promise is resolved
Sry for my bad english, hope someone can help
You are using async/await but mixing it up with the older promise style based on your code that fetches Users. Below is a copy of your code in async/await style, although you may not need to refetch the club object, etc, so continue to debug.
const address = await Address.create(addressToCreate);
let club = await Club.create(clubToCreate);
console.log('created club', club);
club.setAddress(address);
club.setUser(user);
await club.save();
console.log('saved club', club);
club = await Club.scope('withUser').findByPk(club.id);
console.log('reloaded club', club);
return club;

I can't login with WebSecurity.Login and I get WebSecurity.CurrentUserId as -1.

I am trying to register a user and place his order in same action for unregistered users. Please see problematic part of my code below. I get WebSecurity.CurrentUserId as -1 here. Therefore I cant find users and add user info to order. What is wrong here. It should be Id of newly registered user. Thanks for your helps.
WebSecurity.CreateUserAndAccount(UpperEmail, user.Password, new { user.Password, user.PasswordConfirm, user.Email, user.Name }, false);
int userId = db.Users.FirstOrDefault(u => u.Email == user.Email).Id;
if (!Roles.RoleExists("User"))
Roles.CreateRole("User");
Roles.AddUserToRole(UpperEmail, "User");
WebSecurity.Login(UpperEmail, user.Password);
neworder.user = db.Users.Find(WebSecurity.CurrentUserId);
neworder.UserId = WebSecurity.CurrentUserId;
neworder.PaymentStatus = PaymentStatus.Onaylandi;I

Modifying Parse.User object before FIRST save

I'm working on an app and I need some changes to be made on new users registering during certain periods.
I've added a variable which I will change manually, and a check if that value is true or false.
This is my current code:
Parse.Cloud.beforeSave(Parse.User, function(request, status)
{
console.log("********************************************");
Parse.Cloud.useMasterKey();
var special = true;
if(special)
{
request.object.set("points", 1000);
request.object.set("role/objectid", "PZHTquGti0");
}else{
request.object.set("points", 0);
request.object.set("role/objectid", "TQyjIY59oL");
}
console.log("********************************************");
status.success("Job finished successfully!");
}); // end of Parse.define
This code errors out with "Uncaught Error: change must be passed a Parse.Object" and I've been looking through the documentation to find out how to change a value of a subclass of the User object, but have found none.
Also, this code will also run when updating a user, which I don't want it to do.
Any help is highly appreciated!
First of all for running the code on first save (insert), you can use request.object.isNew()
As the role column is a pointer, you should set an object & not the id string directly.
So create a new dummy object and assign the id to it.
Parse.Cloud.beforeSave(Parse.User, function(request, status)
{
console.log("********************************************");
Parse.Cloud.useMasterKey();
if(request.object.isNew()){ // Object Insert
var Role = Parse.Object.extend("_Role");
var role = new Role();
var special = true;
if(special)
{
request.object.set("points", 1000);
role.id = "PZHTquGti0";
request.object.set("role", role);
}else{
request.object.set("points", 0);
role.id = "TQyjIY59oL";
request.object.set("role", role);
}
}
else{ // Object Update
//Do nothing
}
console.log("********************************************");
status.success("Job finished successfully!");
}); // end of Parse.define

Resources