MVC AspNetUser get registered User ID - asp.net-mvc

I am trying to do the following: I would like to get the registered user ID by receiving the user mail and checking if that mail all ready exists in AspnetUsers table. If it does then get the User ID else create a new user. I have started by doing the following:
if (UserManager.FindByEmail(model.Email) != null)
{
// get user Id
// Update person table
}else
//create a new user
{
but I can not get the user ID.

I resolved my issue by doing the following:
if (UserManager.FindByEmail(model.Email) != null)
{
var registedUserID = context.AspNetUsers.FirstOrDefault(x => x.Email == model.Email);
string id= registedUserID.Id; // Now my id is equal to UserMembership Id
}
I got the AspNetUsers where mail equals the mail I recieved then I could get that User Id.

The FindByEmail() should return an ApplicationUser object to you. Just assign it to a local variable and retrieve the Id.
var user = UserManager.FindByEmail(model.Email);
if (user != null)
{
// get user Id
var userId = user.Id;
// Update person table
}
else
//create a new user
{
}

Related

Casting back query results stored in session for Custom Authorization

I have the following table
Permissions Table
On login, I am getting the values of ProductEdit, ProductView, ProductDelete for that logged in user and storing them in session to be used later for custom authorization on some actions within the project. This is achived with the following code (note var permissionJoin)
if (usr != null)
{
Session["OperatorId"] = usr.OperatorId.ToString();
Session["Username"] = usr.Username.ToString();
Session["GroupId"] = usr.GroupId.ToString();
var permissionsJoin = from up in db.UserPermissions
join op in db.Operators
on up.GroupId equals usr.GroupId
select new UserPermissionData
{ UserGroupId = up.GroupId, P_Edit = up.ProductEdit, P_Create = up.ProductCreate, P_Delete = up.ProductDelete };
Session["ProductPermission"] = permissionsJoin.ToList<UserPermissionData>();
return RedirectToAction("LoggedIn");
}
I am using a named class [UserPermissionData - that has the four properties I need] to store these values. The results are getting stored in the session fine.
Now onto my authorization class were I need to extract those values and check - if the user has the permission for a particular. I have the following code
public class AuthorizeProductEdit : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//lets get the session values of the current user's permissions
var userP = (UserPermissionData)HttpContext.Current.Session["ProductPermission"];
var editProduct = userP.P_Edit;
if (editProduct.ToString() == "Y")
{
return true;
}
else
{
return false;
}
}
}
at the point of clicking an edit action for the logged in user I am getting an "Unable to cast object of type" error [see image]
Error Image
How can I cast back that query to be able to use if for checking my permissions.
You store in Session is a List<UserPermissionData> so you must cast session value to List<UserPermissionData>
var userP = HttpContext.Current.Session["ProductPermission"] as List<UserPermissionData>;
if (userP == null) return false;
return userP.Any(x => x.P_Edit.ToString() == "Y");

Doing db.find with non primary key

So what im trying to do is im trying to get an user from my database where the email im trying to find matches an email in my database. If i had the id instead of the email i could just do an db.user.find(id) but i only have the email so im trying to use where but without success.
this is my code
// POST: api/User_Agendapunt1
[ResponseType(typeof(User))]
public IHttpActionResult PostUser_Agendapunt(User user1)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
User user = db.User.Where(o => o.Email== user1.Email);
var user_dagpunten = from s in db.User_agendapunt
where s.UserId == user.IdUser
select s;
return Ok(user_dagpunten.ToList());
}
EDIT1:
User user= db.User.Where(x=> x.Email==user1.Email).FirstOrDefault();
if(user !=null)
{
// do your stuff
}
else{
//return no user exist with given email
}
Hope this solves your issue ...

Duplicate users added to database

I try to add a new value to my database. UserPassword and RePassword must have the same value and a user with UserName must not already exist in the database.
public User NewUser(int HotelID, string UserName, string UserPassword, string RePassword, string FullName, string Email, bool Active, bool MasterUser)
{
User user = new User();
user.HotelID = HotelID;
user.UserName = UserName;
user.UserPassword = UserPassword;
user.FullName = FullName;
user.Email = Email;
user.IsActiveq = Active;
user.IsMaster = MasterUser;
var cekUser = (from c in _UserRepository.All()
where c.HotelID == HotelID
select c.UserName).ToList();
if (UserPassword == RePassword)
{
foreach (string cek in cekUser)
{
var x = cek;
if (UserName != x)
{
_UserRepository.Add(user);
}
}
}
_UserRepository.CommitChanges();
return user;
}
Every time I run my code a new line is added to the database, although a user with the supplied user name already exists in the database.
Why does this happen? Which part of my code is wrong?
I think your code should be something like this:
if (UserPassword == RePassword)
{
// Also I thinks you should finish whether user existed logic in database
// but for now, let's follow your original logic
var existedUsers = (from c in _UserRepository.All()
where c.HotelID == HotelID
select c.UserName).ToList();
if (!existedUsers.Any(u => u == UserName))
{
_UserRepository.Add(user);
_UserRepository.CommitChanges();
}
}
You have your logic wrong. If there is more than one user in a given hotel, your code will be adding more users for all users with names different from UserName.
bool found = false;
foreach(string cek in cekUser)
{
if ( UserName == cek)
{
found = true;
break;
}
}
if (!found)
_UserRepository.Add(user);
Just offering an alternate idea.
If you have access to the database, the best approach will be to make the Username field UNIQUE. That way, even if you get your code wrong, a duplicate insert will fail. Then you capture that fail gracefully in your Repository, and Bob's your uncle.

mvc entity framework many to many user and role insert

I have an mvc project with database first entityframework. In Project I have 3 tables.
Users >>> UsersInRoles <<< Roles with many to many relationship.
and my CreateUser codes below;
public bool CreateUser(string email, string password, string birthday,string firstname,string lastname)
{
bool result;
var dogumgunu = Convert.ToDateTime(birthday);
var sifre = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "sha1");
var confirmation = CreateConfirmationToken(email);
try
{
var user = new User
{
UserName = email,
Password = sifre,
UserJoinDate = DateTime.Now,
UserBirthDay = dogumgunu,
UserConfirmationToken = confirmation,
UserID = Guid.NewGuid(),
MemberFirstName = firstname,
MemberLastName = lastname
};
var role = new Role
{
RoleName = "Client"
};
user.Roles.Add(role); //problem is here!!!!!!!!!
_bb.Users.AddObject(user);
_bb.SaveChanges();
result = true;
}
catch (Exception)
{
result = false;
}
return result;
}
In this code I am new user creating. And I am adding a role. But This code include a new Role in Roles table. I dont want to this. I want to just add UsersInRoles table a new user. What is wrong? Thanks for reply.
Swap these two lines:
_bb.Users.AddObject(user);
user.Roles.Add(role);
because AddObject converts the whole object graph to the Added state. If you add the role afterwards, its state will remain Unchanged.
And you should fetch the role from the database first or create a Role object that only has an existing RoleId. (A so called stub entity).
So in stead of new Role you could do
var role = _bb.Roles.Single(r => r.RoleName == "Client");

MVC4: Getting Active Directory User Guid

Once a user is logged into a Windows-Authentication site, how do I get their Active Directoy user guid from the User.
Eg in an Action:
ViewBag.Message = User.Identity.GUID????
You should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find the current user
UserPrincipal user = UserPrincipal.Current;
if(user != null)
{
// get guid
var userGuid = user.Guid;
}
The new S.DS.AM makes it really easy to play around with users and groups in AD!
string userName = user.Identity.Name.Split('\\')[1];
using (var oRoot = new DirectoryEntry(ConfigurationManager.AppSettings["LDAPDomain"], null, null, AuthenticationTypes.Secure))
{
using (var deSearch = new DirectorySearcher(oRoot))
{
deSearch.Filter = string.Format("(&(sAMAccountName={0}))", userName);
SearchResult searchResult = deSearch.FindOne();
if (searchResult != null)
{
DirectoryEntry de = searchResult.GetDirectoryEntry();
}
}
}

Resources