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.
Related
I am making a login page and i saved the user's details and hashed password in the CUSTOMERS table, but i cant send the salt and the typed password i get from the database and the user to my method
var UserInput = db.CUSTOMERs.Where(b => b.EMAIL == cUSTOMER.EMAIL && b.PASSWORD == sha256(b.SALT+cUSTOMER.PASSWORD).ToString()).FirstOrDefault() ;
Hash method
static string sha256(string password)
{
System.Security.Cryptography.SHA256Managed crypt = new System.Security.Cryptography.SHA256Managed();
System.Text.StringBuilder hash = new System.Text.StringBuilder();
byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(password), 0, Encoding.UTF8.GetByteCount(password));
foreach (byte theByte in crypto)
{
hash.Append(theByte.ToString("x2"));
}
return hash.ToString();
}
You have the error because Linq To Entities hence Entity Framework can't be used to compose with function that can't be translated into SQL. So your custom method sha256 and ToString.Net method are the main causes.
To make it work you must first get the user by email then check that the user has his password hash equal to the genrated one.
So you need to rewrite your code like this:
var UserInput = db.CUSTOMERs.FirstOrDefault(b => b.EMAIL == cUSTOMER.EMAIL);
if(UserInput != null && UserInput.PASSWORD == sha256(UserInput.SALT+cUSTOMER.PASSWORD))
{
// The user email and password match
}
else
{
// The user not found or the password does not match
}
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");
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 ...
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");
I can get the user name as User.Identity.Name. How can I get a user's email address because it must be stored (there is a textbox for it in the registration form)?
if(User.Identity.IsAuthenticated)
{
someLabel.Text = Membership.GetUser().Email;
}
There are a lot of useful user properties resulting from the Membership.GetUser() function. It returns an object of type MembershipUser.
protected string GetEmailAddress()
{
MembershipUser currUser = null;
if (HttpContext.Current.User != null)
{
currUser = Membership.GetUser(true);
return currUser.Email;
}
return currUser.Email;
}
On MVC5, you can use the UserManager for that, like this:
string UserEmail = await UserManager.GetEmailAsync(User.Identity.GetUserId());
or if the information is coming from outside the page you can do like this.
string userName = Request.QueryString["username"];
TextBoxUserID.Text = Membership.GetUser(userName).Email;