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

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

Related

Set strapi permission to specific collection data

I am planning in developing a large structure for a client and I am looking into using Strapi to manage the content and the APIs.
Before even digging deeper I would like to ask if anyone know if there is an existing plugin to set limitations to the collections data.
For example, I create a collection called restaurant where I am going to have 1 field: name. Then I create 2 restaurants named "The Optimist" & "The Negative"
After, I create 2 more user for my back end: Maria & Julia.
Is there any existing way to set Maria to only be able to edit "The optimist" & Julia to only edit "The Negative"?
Explaination
Well there is a way to limit users from performing specific actions on the entire collection directly out of the box, but limiting to specific entries needs customization in controller.
I would recommend you to go through Users, Roles & Permissions guide from the Strapiv4 documentation for better understanding.
Attaching a snapshot below you give you a brief idea. As you can see, generic actions like create, update, delete etc. can be permitted only to specific roles, which in turn can be assigned to the users of your choice.
# Image showing permissions being assigned to a role
# Image showing role being assigned to a user
Solution
Coming to your question on limiting users to specific entries, you can easily achieve this by writing custom code that checks for the entry id and the role that's trying to update the restaurant. Check the snippet below:
// src/api/resto/controllers/resto.js
"use strict";
/**
* resto controller
*/
const { createCoreController } = require("#strapi/strapi").factories;
module.exports = createCoreController("api::resto.resto", ({ strapi }) => ({
async update(ctx) {
const { id } = ctx.params;
const { role } = ctx.state.user;
// if you don't want to hard code the ids, you can do a findOne for the id and do a check on the resto name.
// Assuming id 4 corresponds to entry "The optimist"
// Assuming id 5 corresponds to entry "The Negative"
if ((id === 4 && role.name !== "Role Maria") || (id === 5 && role.name !== "Role Julia")) {
return ctx.badRequest("You are not allowed to update this entry", {
id: id,
role: role.name,
});
}
const entity = await strapi
.service("api::resto.resto")
.update(id, { data: ctx.request.body });
const response = await super.findOne(ctx);
// const sanitizedEntity = await this.sanitizeOutput(response, ctx);
// return this.transformResponse(sanitizedEntity);
return response;
},
}));

getter called on null in flutter gives error screen

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.

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 .

Associate user when created with an existing Account

I have a code that checks an inquery database a for user,
If the user does not exist, then the code will create a new user in Contact,
Here is only part of the code:
newcontact = [SELECT Id, FirstName FROM Contact WHERE Contact.Email =inquery.email__c];
if(newcontact.size() == 0) {
Account[] aa = [SELECT Id FROM Account WHERE Name = :inquery.Institution__c];
contact = new Contact();
contact.FirstName = inquery.First_Name__c;
contact.LastName = inquery.Last_Name__c;
contact.Email = inquery.email__c;
contact.AccountId = aa.Id;
try {
insert contact; // inserts the new record into the database
} catch (DMLException e) {
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error creating new contact'));
return null;
}
I am trying to associate that user with an existing Account?
But the following line gives me an error:
contact.AccountId = aa.Id;
Which is
Initial term of field expression must be a concrete SObject: LIST<Account> at line
And aa.size() returns 1, as it should,
Because the account exists,
Can someone please tell me what wrong?
Thanks
This line contact.AccountId = aa.get(0).Id; will fail if your query returns 0 rows. Make sure to wrap your code within a if (aa.size() > 0) clause to ensure proper execution in all cases.
Ok I fixed it, as follows:
contact.AccountId = aa.get(0).Id;
Best

Remove First Name, Last Name and confirm password fields in account create page

I searched a lot to remove required fields like first name, Last name and confirm passwordfields in account create page.
So far i renamed required value from 1 to 0 from the table eav_attribute
After this i hided first name, Last Name, Confirm Password from register.phtml
But still i'm getting
The first name cannot be empty, The Last name cannot be empty, etc,..
Did any one know how to do this ?
Please give me a idea to solve this..
You have to change two more files:
Change /js/prototype/validation.js and comment out the following lines:
['validate-cpassword', 'Please make sure your passwords match.', function(v) {
var conf = $('confirmation') ? $('confirmation') : $$('.validate-cpassword')[0];
var pass = false;
if ($('password')) {
pass = $('password');
}
var passwordElements = $$('.validate-password');
for (var i = 0; i < passwordElements.size(); i++) {
var passwordElement = passwordElements[i];
if (passwordElement.up('form').id == conf.up('form').id) {
pass = passwordElement;
}
}
if ($$('.validate-admin-password').size()) {
pass = $$('.validate-admin-password')[0];
}
return (pass.value == conf.value);
}],
After that, you also have to change the Magento Customer Core model. There are two types of validation: through the front-end javascript and in the backend Customer model.
Rewrite the model with your own customer module. Then copy the validate() public function. And comment out the following lines:
$confirmation = $this->getConfirmation();
if ($password != $confirmation) {
$errors[] = Mage::helper('customer')->__('Please make sure your passwords match.');
}

Resources