ASP.NET Get Username for Logged-In User - asp.net

I have a class named Store which happens to have a property named User.
This User can later log-in into the application.
The Problem:
What I attempt is to create a list of the Stores based on the User that is currently logged-in
Example of Store table: Last column Usuario a.k.a. User
What I have tried:
var Tiendas = await _context.Stores
.Where(t => t.Usuario= User.Identity.Name.ToString()).ToListAsync();
Is it a close attempt? I'm getting an error:
Can't convert the type string into bool.

var Tiendas = await _context.Stores
.Where(t => t.Usuario == User.Identity.Name).ToListAsync();
Change your t.Usuario = User.Identity.Name.ToString() to t.Usuario == User.Identity.Name
You're using an assignment operator when you should be using a comparison operator. Also you can remove the .ToString() since User.Identity.Name is a string already.

Related

how to store a value from database to a global variable and use it everywhere we need it

I don't know if this is the way to ask this, also I want to achieve this without state management.
so here's the code that getting user is from firebase
final docUsers = FirebaseFirestore.instance.collection('users').doc();
final userObject = Users(
id: docUsers.id,
name: userName,
email: emailAdress,
password: password,
);
await docUsers.set(userObject.toJson());
userID = docUsers.id;
userID = docUsers.id; the user id is the global variable here, so I assigned the value to the global variable when the id received. but when it using its shows the value is null, how to achieve this without statemanagement (I meant bloc, provider and like many others. not the "state management").
so how can I achieve that?
Could you show how and when your value is NULL?
But this might help:
class MyGlobalVariables {
static String userId = '123';
}
MyGlobalVariables.userId = 'abc';
print( MyGlobalVariables.userId ); // = abc
It looks like you want to create entries for new users of your App in the database. If this is the case, one would want to use Firebase Authentication for dealing with that:
https://firebase.google.com/docs/auth/

GitKit Client - Uploaded users cannot connect

We have an existing user database with SHA1-encoded passwords. We upload them to the Google Federated Database (through the GitKitClient java lib), but then these uploaded users can't log in The verifyPassword always returns "Incorrect password" ! The call to the uploadUsers looks like gitkitClient.uploadUsers('SHA1', new byte[0], gitkitUsers)
(We must provide an empty byte array as second param (hash key), since we get NPEs if we provide a null value)
The method that creates the GitkitUsers that are in the list is as follows:
private GitkitUser createGitkitUserFromUser(User user) {
GitkitUser gitkitUser = new GitkitUser()
gitkitUser.email = user.email
gitkitUser.localId = getLocalId(user)
gitkitUser.name = user.displayName
gitkitUser.hash = user.password?.bytes
if (user.pictureFileName) {
gitkitUser.photoUrl = user.getPictureUrl()
}
return gitkitUser
}
We see no way to further investigate. Did someone successfully use it ?
Make sure that the hashKey you use in setPassword() is the same one used in uploadUsers().
I am using the php SDK so I can't share code for you, but when I did NOT use the same hashKey for both places, I had the same problem.

ASP Identity - AddToRoleAsync

I have a problem using the Microsoft AddToRoleAsync() function.
For usernames where there is a hyphen in them I cannot get it to work successfully. For example:
var user = new ApplicationUser();
var email = "name-surname#company.com";
user = await userManager.FindByEmailAsync(email);
await userManager.AddToRoleAsync(user.Id, "Admin");
I don't get an error thrown, the user just doesn't get added to the role and an entry never appears in the AspNetUserRoles.
However, as soon as I remove the hyphen in the email / username the AddToRoleAsync() works perfectly, which seems strange as this function takes an Id and role name.
We have the same value for both the email and username field.
Can anyone help ?

ASP.NET MVC4 Get email of logged user

I am making asp.net mvc4 web application. I wrote contact form function in my controller which sends feedback from users. I am using System.Net.Mail class.
I am using Simplemembership and I extended UserProfile with string Email property.
How to get logged in user Email? I want to include it it sended message, so I Could answer.
I tried to use:
var em = from m in db.UserProfiles.Where(a => a.UserName.Contains(User.Identity.Name)) select m.Email;
string email = em.ToString();
but in the sent mail I have:
SELECT
[Extent1].[Email] AS [Email]
FROM [dbo].[UserProfile] AS [Extent1]
WHERE [Extent1].[UserName] LIKE #p__linq__0 ESCAPE N'~'
To retrieve a single entry of the database, you have to select the first row returned with the First() method:
string email = db.UserProfiles
.Where(a => a.UserName.Contains(User.Identity.Name))
.First().Email;
Hope it helps !
You already have the correct answer, so I am just throwing this up here for future searchers to see the shorter syntax.
string email = db.UserProfiles
.FirstOrDefault(a => a.UserName.Contains(User.Identity.Name)).Email;
However in your scenario, I would be concerned about User1 receiving emails intended for User11. To prevent this, you need to be more specific in your query
string email = db.UserProfiles
.FirstOrDefault(a => a.UserName == User.Identity.Name).Email;

Storing DotNetOpenAuth information and user info retrieval

This question is a bit of a structural/design question as I'm having trouble working out the best way to perform the task.
In my MVC app, I am using DotNetOpenAuth (3.4) as my login information provider and just using the standard FormsAuthentication for cookies etc.
The current user table in the DB has:
UserId (PK, uniqueidentifier)
OpenIdIdentifier (nvarchar(255))
OpenIdDisplay (nvarchar(255))
Displayname (nvarchar(50))
Email (nvarchar(50))
PhoneNumber (nvarchar(50))
As the UserId is the clear identifier for a user (they should be able to change their OpenId provider at a later date), it is the key that other tables link to (for a user).
This is the current code, that on a successfull authentication, creates a temporary user and redirects to Create Action.
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false);
var users = new UserRepository();
if (!users.IsOpenIdAssociated(response.ClaimedIdentifier))
{
var newUser = new DueDate.Models.User();
newUser.OpenIdIdentifer = response.ClaimedIdentifier;
newUser.OpenIdDisplay = response.FriendlyIdentifierForDisplay;
TempData["newUser"] = newUser;
return this.RedirectToAction("Create");
}
And now for the crux of the question:
Is the response.ClaimedIdentifier the correct piece of information to be storing against a user?
Is FormAuthentication.SetAuthCookie the preferred way to forms authentication? Or is there a better way?
When I call SetAuthCookie, there is no data relating to the user except for the ClaimedIdentifier. If I'm consistently referring to their UserId, is a better idea to create the user, then store that UserId in the cookie instead of the ClaimedIdentifier?
If I'm using that UserId in a number of places, how do I either retrieve it from the cookie, or store it somewhere else more logical/useful?
A bit long winded but I've been having trouble trying to work out the best way to do this/
1.Is the response.ClaimedIdentifier the correct piece of information to be storing against a user?
Yes. And make sure the column you store it in the database with is case sensitive. Here is a table schema that demonstrates how to make sure it is case sensitive. This comes out of the DotNetOpenAuth project template's database schema. The "CS" bit of the specified collation stand for Case Sensitive.
CREATE TABLE [dbo].[AuthenticationToken] (
[AuthenticationTokenId] INT IDENTITY (1, 1) NOT NULL,
[UserId] INT NOT NULL,
[OpenIdClaimedIdentifier] NVARCHAR (250) COLLATE SQL_Latin1_General_CP1_CS_AS NOT NULL,
[OpenIdFriendlyIdentifier] NVARCHAR (250) NULL,
[CreatedOn] DATETIME NOT NULL,
[LastUsed] DATETIME NOT NULL,
[UsageCount] INT NOT NULL
);
2.Is FormAuthentication.SetAuthCookie the preferred way to forms authentication? Or is there a better way?
For MVC apps it definitely is, since you still can return your preferred ActionResult from the method.
3.When I call SetAuthCookie, there is no data relating to the user except for the ClaimedIdentifier. If I'm consistently referring to their UserId, is a better idea to create the user, then store that UserId in the cookie instead of the ClaimedIdentifier?
That sounds like personal preference. But I would typically go with user_id, since it might result in a faster database lookup every time an HTTP request comes in that requires you to look up any user information.
4.If I'm using that UserId in a number of places, how do I either retrieve it from the cookie, or store it somewhere else more logical/useful?
FormsAuthentication does provide a way to store more information in its encrypted cookie than just username, but it is harder than you'd expect to use it. This snippet comes out of DotNetOpenAuth's web SSO RP sample:
const int TimeoutInMinutes = 100; // TODO: look up the right value from the web.config file
var ticket = new FormsAuthenticationTicket(
2, // magic number used by FormsAuth
response.ClaimedIdentifier, // username
DateTime.Now,
DateTime.Now.AddMinutes(TimeoutInMinutes),
false, // "remember me"
"your extra data goes here");
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
Response.SetCookie(cookie);
Response.Redirect(Request.QueryString["ReturnUrl"] ?? FormsAuthentication.DefaultUrl);
Then you can get at that extra data in a future HTTP request with this:
var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null) {
var ticket = FormsAuthentication.Decrypt(cookie.Value);
if (!string.IsNullOrEmpty(ticket.UserData)) {
// do something cool with the extra data here
}
}

Resources