Using Lists that give permissions - c#

I'm trying to write this code for my project but it doesn't seem to work.
As you can see from the code, the last else statement won't work. I have a class Admin and it has 3 properties, Username, Password, and Permitted. I created a List with default values and granted some usernames permission while granting some no permission. From the else statement, I'm trying to match if the Permitted value is true then that user has permission, and vice versa, however even if the user has no permission is still grants him access. Any idea why?
List<Admin> result = FrmMain.AdminL.FindAll(adm => adm.UserName == txtUsername.Text);
if (result.Count == 0)
{
MessageBox.Show("Username is incorrect");
}
// Note to miss : I couldnt find a way to link the password with a specific user
List<Admin> result2 = FrmMain.AdminL.FindAll(adm => adm.PassWord == txtPassword.Text);
if (result2.Count == 0)
{
MessageBox.Show("Password is incorrect");
}
else
{
List<Admin> permission = FrmMain.AdminL.FindAll(adm => adm.Permitted == true);
if (result.Count > 0)
{
MessageBox.Show("User has been authenticated");
FrmAdminCP f1 = new FrmAdminCP();
f1.ShowDialog();
}
else
{
MessageBox.Show("Im sorry, you do not have permission to access the control panel");
}

You need to combine your predicates into a single search using &&.
List<Admin> result = FrmMain.AdminL.FindAll(adm =>
adm.UserName == txtUsername.Text &&
adm.PassWord == txtPassword.Text &&
adm.Permitted == true);
if (result2.Count == 1)
{
// authenticated with access
}
or two steps
List<Admin> result = FrmMain.AdminL.FindAll(adm =>
adm.UserName == txtUsername.Text &&
adm.PassWord == txtPassword.Text);
if (result.Count == 1)
{
// authenticated
}
else
{
// not authenticated
}
List<Admin> result = FrmMain.AdminL.FindAll(adm =>
adm.UserName == txtUsername.Text &&
adm.Permitted == true);
if (result.Count == 1)
{
// username is permitted to access
}
Update:
I'm assuming FrmMain.AdminL is a List<Admin>.
Admin singleResult = FrmMain.AdminL.Find(adm =>
adm.UserName == txtUsername.Text);
if(singleResult == null)
{
MsgBox("No User found");
return; // exit the subroutine you're in
}
if(singleResult.PassWord != txtPassword.Text)
{
MsgBox("Wrong Password");
return; // exit the subroutine you're in
}
if(singleResult.Permitted == false)
{
MsgBox("Not authorized")
return;
}

Related

How to display the message of login account deleted(soft delete)

I developed function to delete users (soft deletion), ie stays in the database and does not show in the list. When I enter the login and password of the deleted account, it have to show a message as this login is deleted.
how to achieve this and thanks
user.controller.cs:
[Route("api/Users/Login")]
[ResponseType(typeof(object))]
public async Task<object> accountLogin(string name, string password)
{
string pwd = Encrypt(password);
Users account = new Users();
var query = from c in db.Users
where c.userlogin == name && c.password == pwd
select c;
account = query.FirstOrDefault();
string message = "";
if (account == null)
{
message += "404";
}
else if (account .IsActive == 1)
{
message += "400";
}
else if ((account .IsActive != 0) && (account .IsActive != 1)) // this condition of account deleted -- or account .IsActive == 2
{
message += "500";
}
else
{
message = JsonConvert.SerializeObject(account);
}
return new { a = message };
}
and this login.controller.js:
$scope.login = function () {
$scope.loading = true;
authService.login($scope.userlogin)
.then(function done(response) {
console.log(response);
if (response.a == '400') {
$scope.error = 'account disabled';
$scope.loading = false;
}
else if (response.a == '500') {
$scope.error = 'this login is deleted';
$scope.loading = false;
}
else if (response != '404') {
console.log("bbb");
$location.url('Dashboard');
}
else {
console.log("login or password incorrect");
$scope.error = 'login or password incorrect';
$scope.loading = false;
}
},
function fail(err) {
$scope.error = 'Problem in connextion ! contact administrateur';
console.log(err);
}
);
}

Address on IIS Change After Login on My Application

I need to know, why my address changes automatically when I publish to IIS.
This is the address that shows the login page:
localhost/Travel
After login my address changes to
localhost/Admin/Index.aspx = > this shows error page not found
So I add Travel before /Admin
localhost/Travel/Admin/Index.aspx = > OK
My question is why is Travel gone after I login?
This my login code :
if (txtuname.Value == DU.Username && txtpass.Value == DU.Password && DU.Role == "User")
{
Session["Username"] = DU.Username;
Session["Nama"] = DU.Nama;
Response.Redirect("Index.aspx");
}
else if (txtuname.Value == DU.Username && txtpass.Value == DU.Password && DU.Role == "Admin")
{
Session["Username"] = DU.Username;
Session["Nama"] = DU.Nama;
Response.Redirect("../Admin/Index.aspx"); = > my login page in User/Login.aspx
}
else
{
ShowMessage("Password/Username Salah !");
}

C# Unable to load registry values in LocalMachine

I am writing an application that loads parameters from the registry. Here is the code I use to load it:
public bool getRegValues() //get values used for the SQL Connection etc
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Company\Application\NightJob\", RegistryKeyPermissionCheck.ReadWriteSubTree))
{
if (key != null)
{
this.serverName = key.GetValue("SQLserver").ToString();
this.timeout = key.GetValue("timeout").ToString();
this.Database = key.GetValue("database").ToString();
this.logTable = key.GetValue("table_log").ToString();
this.budgetTable = key.GetValue("table_budget").ToString();
this.personsTable = key.GetValue("table_persons").ToString();
this.tempTable = key.GetValue("table_temp").ToString();
this.cashiersDB = key.GetValue("cashiersDB").ToString();
this.customersTbl = key.GetValue("cashiersCustomersTable").ToString();
key.SetValue("version", version);
if (this.serverName == null || this.timeout == null || this.Database == null || this.logTable == null
|| this.budgetTable == null || this.personsTable == null || this.tempTable == null)
{
Console.WriteLine("One of the values could not be loaded.");
return false;
}
}
else
{
Console.WriteLine("Key is null.");
return false;
}
return true;
}
}
When I run the code on my workstation everything is perfect. When I do it on the server it returns false and writes "Key is null.".
When I compile the code using Registry.CurrentUser instead of Registry.LocalMachine it returns true (Of course the values in the different locations are identical).
What is wrong? I am domain admin and have also given myself explicitly full control permissions to the Key HKEY_LOCAL_MACHINE\SOFTWARE\Company\Application\NightJob\
Any ideas?
If you are using .Net 4 try this using:
using(RegistryKey SoftwareKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(#"SOFTWARE\Company\Application\NightJob\", RegistryKeyPermissionCheck.ReadWriteSubTree))

Can I Query multiple properties using session.Query?

I want to query one more property of the "User" entity.
Basically I need to know, is it possible to extend the below statement to include something like this..
user = session.Query<User>().SingleOrDefault(u => u.Username.ToLower() == identity.ToLower()) && (u => u.Email == email);
I know thats not correct but you get the idea, I want to check the user email as well as the username.
This is the current code..
public static bool IsDuplicateIdentity(string identity, string email, Type type)
{
using(ISession session = NHibernateHelper.SessionFactory().OpenSession())
using (ITransaction tx = session.BeginTransaction())
{
User user = null;
// the entity type is checked and then DB is queried to see if an object with that name and email exists
if (type.BaseType == typeof(User))
{
user = session.Query<User>().SingleOrDefault(u => u.Username.ToLower() == identity.ToLower());
}
tx.Commit();
if (user != null)
{
return true;
}
else
{
return false;
}
}
}
Please note this is an ASP.net MVC 3 application.
Can't you just do this?:
user = session.Query<User>()
.SingleOrDefault(u =>
u.Username.ToLower() == identity.ToLower()
&& u.Email == email);
Sure:
user = session.Query<User>()
.SingleOrDefault(u => u.Username.ToLower() == identity.ToLower()
&& u.Email == email);
Yes, you can combine them and you almost got it right. Try it like this:
user = session.Query<User>().SingleOrDefault(u => u.Username.ToLower() == identity.ToLower() && u.Email == email);
You can write the below code
user = session.Query<User>()
.where(u => u.Username.ToLower() == identity.ToLower() && u.Email == email).SingleOrDefault();

Check Nulls in Lambda

We have the following code to check if the given username and password exists in database:
public User GetUserByUserNameAndPassword(string userName, string userPassword)
{
using (var context = DataObjectFactory.CreateContext())
{
return Mapper.Map(context.UserEntities.Single(u => u.UserName == userName && u.UserPassword == userPassword));
}
}
If we have the username and password in database this works fine but throws an error if username or password is wrong and no records found.
This might be simple but as I am new to lambda could not get get it right.
How can I change the lambda query so we can handle nulls?
Thanks
Use SingleOrDefault, which will return only one record or null if none exists.
return Mapper.Map(context.UserEntities.SingleOrDefault(u => u.UserName == userName && u.UserPassword == userPassword));
Later you can check:
User returnedObject = GetUserByUserNameAndPassword(username,password)
if(returnedObject == null)
{
//User doesn't exist
}
Remember Single/SingleOrDefault will throw an exception if multiple records exist against the criteria.
You should change from Single to SingleOrDefault, it returns null when no data match
context.UserEntities.SingleOrDefault(u => u.UserName == userName &&
u.UserPassword == userPassword)
.Any() will return true if a matching record is found or false if no record is found.
So a slight modifcation to you existing code will work.
public User GetUserByUserNameAndPassword(string userName, string userPassword)
{
using (var context = DataObjectFactory.CreateContext())
{
if (context.UserEntities.Any(u => u.UserName == userName && u.UserPassword == userPassword))
{
return Mapper.Map(context.UserEntities.Single(u => u.UserName == userName && u.UserPassword == userPassword));
}
else
{
//Deal with no user here through chosen method
}
}
}
Make use of FirstOrDefault or SingleOrDefualt and check for null like as below
var user =context.UserEntities.SingleOrDefault(u => u.UserName == userName
&&
u.UserPassword == userPassword);
if(user!=null)
{
//do code
}
Use SingleOrDefault and check for Null prior to calling Map
public User GetUserByUserNameAndPassword(string userName, string userPassword)
{
using (var context = DataObjectFactory.CreateContext())
{
var user = context.UserEntities.SingleOrDefault(u => u.UserName == userName && u.UserPassword == userPassword);
return user !=null ? Mapper.Map(user) : null;
}
}

Categories