Get user email, from user table - asp.net-mvc

In my ASP.MVC site user have additional field email, so now i want to reset password by sending token to email address like this:
var token = WebSecurity.GeneratePasswordResetToken(model.Pesel);
var userID = WebSecurity.GetUserIdFromPasswordResetToken(token);
var callbackUrl = Url.Action("ResetPassword", "Account", new { UserId = userID, code = token }, protocol: Request.Url.Scheme);
But the problem is how can I get email address that I have added to User table?
It will be nice to create method like:
WebSecurity.GetUserIdFromEmailResetToken

Why don't you? Such as
public UserEmailTable GetUserIdFromEmailResetToken(int userEmailId)
{
return _db.UserEmail.Where(s => s.UserEmailId == userEmailId)
}
this allows you to get the user email by Id.

Related

UserManager.CheckPasswordAsync(curUser, password) Is always false

.net 6, Identity Core, using emails for usernames, MVC
The user is created in code with
var user = new DBModels.ApplicationUser
{
UserName = "Valid Email",
Email = "Valid Email",
Approved = true,
LockoutEnabled = false,
PhoneNumber = "(123) 456-7890",
FirstName = "John",
LastName = "Doe",
EmailConfirmed = true,
CreationDate = DateTime.Now,
RenewalDate = DateTime.Now.AddYears(50),
ScreenName = "John.Doe",
State = "AK",
Avatar = "/assets/user.png"
};
var userResult = _userManager.CreateAsync(user, "Password123!").Result;
var roleResult = _userManager.AddToRoleAsync(user, "Default").Result;
I know the email/password pair I'm trying to compare is valid because I can login to the web app just fine. I am trying to create an API controller for a mobile companion app and need to verify the email/password pair in the login method from the app. The API controller login method looks like:
public async Task<IActionResult> Login(string email, string password)
{
try
{
var curUser = await UserManager.FindByEmailAsync(email);
if (curUser != null)
{
var verifyPassword = await UserManager.CheckPasswordAsync(curUser, password);
if (verifyPassword) .....
No matter what I do, when trying to verify a password, the check is always false. I find the correct user just fine but the password comparison is always false. Any advice?
So sorry ... this works perfectly fine when you enter the actually correct password in your test code!

How to retrieve loginProvider name ASP.Net MVC Core for ExternalLoginConfirmation method

In the ExternalLoginConfirmation method of the AccountController.cs a new user will be created according to user = new ApplicationUser { UserName = model.Email, Email = model.Email }.
I want to create the new user prepending the login provider name in the UserName property:
user = new ApplicationUser { UserName = provider ?? model.Email + model.Email, Email = model.Email };
My idea is to try to do like that:
var loginProviders = _signInManager.GetExternalAuthenticationSchemes().ToList();
var provider = loginProviders[index].DisplayName.ToString();
How can I select index to return the used loginProvider?
Unfortunately var provider = loginProviders.DisplayName.ToString(); does not work.
For Authentication I'm using
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
});
app.UseGoogleAuthentication(new GoogleOptions()
{
ClientId = Configuration["Authentication:Google:ClientId"],
ClientSecret = Configuration["Authentication:Google:ClientSecret"]
});
app.UseMicrosoftAccountAuthentication(new MicrosoftAccountOptions()
{
ClientId = Configuration["Authentication:Microsoft:ClientId"],
ClientSecret = Configuration["Authentication:Microsoft:ClientSecret"]
});
app.UseFacebookAuthentication(new FacebookOptions()
{
AppId = Configuration["Authentication:Facebook:AppId"],
AppSecret = Configuration["Authentication:Facebook:AppSecret"]
});
While testing my web site I use my credential.
Letting UserName = model.Email, Email = model.Email turns out to give an error.
I can use the same Email, by setting up
services.AddIdentity<ApplicationUser, IdentityRole>(opts => {
opts.User.RequireUniqueEmail = false;
})
But I can not have the same UserName
Any idea?
Thanks a lot.
In the meantime I've found the solution.
In the method
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
you can get the information about the user from the external login provider by calling
var info = await _signInManager.GetExternalLoginInfoAsync();
You can then add a new user by simply prepending info.LoginProvider in the UserName field like that
var user = new ApplicationUser { UserName = info.LoginProvider + model.Email, Email = model.Email };
Doing that you can use your credentials (you email address) to test multiple login provides avoiding conflics while trying to insert in the dbo.AspNetUsers identical UserName fields.
Hope it helps!

Get a user id by the userName in mvc Identity

I need to get all the users list of a specific role and their IDs.
I have searched a lot to get a userId with the user name but i didn't get one.
All of them are saying how to get the logged/current user id.
public ActionResult getAllAMUsers()
{
var AMUserList = Roles.GetUsersInRole("Account Manager");
var userList = new List<UserViewModel>(); // property userID & userName
foreach(var item in AMUserList)
{
string userID = User.Identity.getUserID(item); // method like this
userList.add(new UserViewModel{
userName = item,
userID = userID
})
}
return View(userList);
}
Try this;
var users = Roles.GetUsersInRole("Account Manager").Select(Membership.GetUser).ToList()

How to send email to registered user (MVC)

My problem is this one, I have users that are registered in a basic MVC 5 application, when they register they provide email address and a username.
In the application userA can see what userB created (ie a product or whatever), what I want to do is that for userA to "contact" userB by clicking on a button, however userA will not see the email address of userB, the application will send the mail on its behalf (sendgrid).
My pain points are :
1 - once userA click the button, a small issue is how open a new page where he can type its subject and message without loosing the username of userB
2 - how can I retrieve the email address of userB ? I can't find a way to retrieve the email address of the user
Thank you in advance !
I wrote a method for sending email via SendGrid:
public static string SendEmail(string SendTo, string MessageBody, string subject)
{
try
{
string FromEmail = "your app's email";
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
mailMessage.From = (new System.Net.Mail.MailAddress(FromEmail.Trim()));
mailMessage.To.Add(new System.Net.Mail.MailAddress(SendTo.Trim()));
mailMessage.Priority = System.Net.Mail.MailPriority.Normal;
mailMessage.IsBodyHtml = false;
mailMessage.Subject = subject;
mailMessage.Body = MessageBody.Trim();
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
smtpClient.Send(mailMessage);
return ("Message Sent");
}
catch (System.Net.Mail.SmtpException smtpExc)
{
//Log error information on which email failed.
return ("SMTP Error");
}
catch (Exception ex)
{
//Log general errors
return ("Error");
}
}
To keep Username to another page just pass the information to the controller.#Html.ActionLink("Send Email", "Controller Name", new { username = "userB" })
public virtual ActionResult SendMessage(string username)
{
ViewBag.usename = username;
return View();
}
To get the email from a user name use: from the answer in this question
var user = UserManager.FindByName("the username here");
var email = user.email;

Can I use the Configuration.Seed method to an an initial ApplicationUser to an MVC database?

I know that we can initialise the database when doing a Entity Framework migration using the Seed method, as below.
protected override void Seed(CraigSheppardSoftware.Models.ApplicationDbContext context)
{
context.Users.AddOrUpdate(p => p.UserName,
new ApplicationUser { FullName = "System Admin", UserName="CssOp", UserRole = UserType.SystemAdmin,
LandlinePhone=new ComplexDataTypes.PhoneNumber(), MobilePhone= new ComplexDataTypes.PhoneNumber()
} );
context.SaveChanges();
}
The problem is that the when I try to use that user to login with, I can't as I dont know what the password is.
There is no password field on the database. I notice that there is a PasswordHash field and suspect that this is an encrypted password. How do I create a password hash ?
Use UserManager to create / update the user.
var manager = new UserManager<ApplicationUser>(
new UserStore<ApplicationUser>(context));
var user = manager.Find("CssOp", "ThePassword");
if (user == null)
{
user = new ApplicationUser { UserName = "CssOp", Email = "email#mail.com" };
manager.Create(user, "ThePassword");
}
else
{
user.Email = "newemail#mail.com";
manager.Update(user);
}

Resources