How to use Where sentence to find username equal to ID in data base? - sql

How to do this:
var tmpUser = System.Web.HttpContext.Current.User.Identity;
This returns me what user is logged in, e.g. it returns, when I am login, the name of username, so Identity is e.g. daniel (username)
Now in some other form, I want to return the ID of this username, so I have start with this:
var db = new userDbEntities(); // this is my connection to Database
Then:
var connectedUser = from user in db.UserTable
select user
now here I need WHERE sentence, where I can check if USERNAME is equal to tmpUser, then return the ID of this user in UserTable.
Thanks for any ideas...

Assuming UserName is the column name in UserTable this way will work:
string tmpUser = System.Web.HttpContext.Current.User.Identity.Name;
using(var db = new userDbEntities())
{
var connectedUser = (from user in db.UserTable
where user.UserName == tmpUser
select user).FirstOrDefault();
}
or you can simply do using SingleOrDefault:
string tmpUser = System.Web.HttpContext.Current.User.Identity.Name;
using(var db = new userDbEntities())
{
var connectedUser = db.UserTable.SingleOrDefault(x=>x.UserName == tmpUser);
}

Related

How to make email case insensitive authentication in ASP.NET Core Web API login

Currently, when a user logs in to my application their email address should be all small letters but that shouldn't be the case, because in most applications whether you capitalize the whole email or the first letter of an email, it should still login.
How can I fix this bug in my application?
I tried changing the database column to be case insensitive but I can't because of the encryption of the data in my database.
My authentication code is like this:
public async Task<User> Login(string? email, string? password)
{
if (string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(email))
{
throw new ClientError("Email and password required.");
}
var user = await ValidateUser(email, password);
return user ?? throw new ClientError("Invalid email or password.");
}
private async Task<User?> ValidateUser(string email, string password)
{
var user = await _queries
.GetByEmail(email)
.FirstOrDefaultAsync();
if (user == null)
{
return null; // Email does not exist.
}
var passwordIsCorrect = _hashUtil.VerifyHashedPassword(
email: email,
password: password,
hash: user.Password
);
if (passwordIsCorrect)
{
return user;
}
return null;
}
Just
var user = await _queries
.GetByEmail(email.toLower())
.FirstOrDefaultAsync();
The {string}.toLower() method will convert all chars to lower case hence your database search will always compare lower case emails.
Don't forget to guarantee that when users register you use the same function in the email inputted to assure that the emails saved in database are always lower case as well.

How can I update attributes of user using UPN of that user , i am using "dn" of that particular user to update the attribute password

private static void modifyAttribute(String userName,LdapContext ctx,DirContext dircontxet,SearchControls searchControls) {
try {
NamingEnumeration<SearchResult> results = ctx.search("dc=germany,dc=pepsi,dc=jp", "uid=" + userName, searchControls);
String name ="uid=aman.sahu,cn=users,cn=accounts,dc=germany,dc=pepsi,dc=jp";
Attributes orig = ctx.getAttributes(name, new String[] { "gidNumber","cn" });
ModificationItem[] mods = new ModificationItem[2];
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("displayName", "Aman Kumar Sahu"));
mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("userPassword", "aman#8989"));
ctx.modifyAttributes(name, mods);
System.out.println("ATTRvalues"+ctx.getAttributes(name));
}
catch (NamingException n) {
n.printStackTrace();
}
}
I am updating user's attributes by using dn of that user but i want to update the attributes using UPN of that user
LDAP operations require that you reference an entry by its DN and only its DN.

Create User Role in mvc 4

Thanks in advance
I need to set Role in particular users depends on their Role. I had
try to goggled many websites but I did not get clear idea about this
Roles. I need to implement this Role concept in my mvc project.
Controller:-
[AllowAnonymous]
public ActionResult EditableUserDetails( )
{
if (!Roles.RoleExists("test"))
Roles.CreateRole("test");
var UserName = Session["UserName"].ToString();
Roles.AddUserToRole(UserName, "test");
var linq = (from db in EntityObj.Users
where db.IsActive == true
select new EditableUserDetails
{
UserId = db.UserId,
UserName = db.UserName,
Password = db.Password,
Category = db.Category
}).ToList();
var data = linq.ToList();
return View(data);
}
If I run this code I got this following error:-

WebMatrix display authenticated user information

I would like to display the first and last name of the authenticated user.
I know there is the "CurrentUserName" property of the "WebSecurity" class that will retrieve the current authenticated user, but how can I retrieve its first and last name ?
I tried querying the users table but I have always an error message regarding the line the SQL query (starting var UserData ...): incorrect syntax near ','
In the code section:
#{
// Initialize general page variables
var authenticatedUser = "";
var authenticatedUserFirstName = "";
var authenticatedUserLastName = "";
if (WebSecurity.IsAuthenticated) {
authenticatedUser = WebSecurity.CurrentUserName;
var db = Database.Open("MyDatabase");
var UserData = db.QuerySingle("SELECT (FirstName, LastName) FROM Users WHERE LOWER(Email) = LOWER(#0)", authenticatedUser);
authenticatedUserFirstName = UserData.FirstName;
authenticatedUserLastName = UserData.LastName;
}
}
In the markup section:
#if (WebSecurity.IsAuthenticated) {
<p>
Hello, <a class="username" href="~/Account/ChangePassword" title="Change password">#authenticatedUserFirstName #authenticatedUserLastName</a>!
Logout
</p>
...
Remove the brackets from around the FirstName, LastName fields in the SQL:
"SELECT FirstName, LastName FROM Users WHERE LOWER(Email) = LOWER(#0)"

SQL CLR stored procedure output

there is a simple class called User and List of its objects
public class User
{
public int ID;
public string UserName;
public string UserPassword;
}
...
List userList = new List();
Can i make this list of User objects as result of execution SLQ CLR stored procedure ?
e.g. i want to get this
ID UserName UserPassword
1 Ted SomePassword
2 Sam Password2
3 Bill dsdsd
[SqlProcedure]
public static void GetAllocations()
{
// what here ??
}
P.S. Please do not advice me to use Sql functions. It does not suit me because it does not support output parameters
P.S.2 i will be very appreciated for any help !
Try to create a virtual table with SqlDataRecord and send it over the Pipe property of SqlContext object:
[SqlProcedure]
public static void GetAllocations()
{
// define table structure
SqlDataRecord rec = new SqlDataRecord(new SqlMetaData[] {
new SqlMetaData("ID", SqlDbType.Int),
new SqlMetaData("UserName", SqlDbType.VarChar),
new SqlMetaData("UserPassword", SqlDbType.VarChar),
});
// start sending and tell the pipe to use the created record
SqlContext.Pipe.SendResultsStart(rec);
{
// send items step by step
foreach (User user in GetUsers())
{
int id = user.ID;
string userName = user.UserName;
string userPassword = user.UserPassword;
// set values
rec.SetSqlInt32(0, id);
rec.SetSqlString(1, userName);
rec.SetSqlString(2, userPassword);
// send new record/row
SqlContext.Pipe.SendResultsRow(rec);
}
}
SqlContext.Pipe.SendResultsEnd(); // finish sending
}