User data getting swapped even without using sessions - asp.net mvc - c#

When multiple users are logged into the website, the last logged in users details are visible to all previously logged in users. This is causing serious vulnerability issue.
I'm not using any session variables in storing user data instead, Once the user logged into my website, i'm keeping his acc details in helper class file like below.
And in my all other pages, am using getting userdetails like UserData.userid, UserData.username etc...
public class UserData
{
public static int userid;
public static string username;
public static string useremail;
public int user_id
{
get { return userid; }
set { userid = value; }
}
public string user_name
{
get { return username; }
set { username = value; }
}
public string user_email
{
get { return useremail; }
set { useremail = value; }
}
}

You are declaring the fields of this class as static. This means that every instance of the class UserData will have the same values in these fields.
See here documentation about the static keyword and when you set these values you set the same values for every instance still around in your program.
You need to remove the static keyword, but given the fact that you don't really have any use for these fields you could remove them and simply change your class to use auto implemented properties instead
public class UserData
{
public int user_id {get;set;}
public string user_name {get;set;}
public string user_email {get;set;}
}

Related

Add identity UserId property into my domain entity

I have stucked with a problem to add UserId property from my ApplicationUser to domain Player entity.
This is my domain entity Player, where I have virtual ApplicationUserId property.
I had an idea to write UserId after I created User in UserService, but could't proceed because of protection level of setter. Should I change remove protection level or there is another approach to achive result?
Maybe I should create a method in domain like SetUserId where I will set private property with UserId came from IdentityServer.CreateUser? Does it good approach?
public class Player: MyEntity
{
public string UserName { get; private set; }
public virtual Guid ApplicationUserId { get; private set; }
private Player()
{ }
}
UserService.cs snippet where user is creating
public async Task<(AppSignInResult result, SignInData data)> CreateUser(string username, string password, string email, string country)
{
var user = new ApplicationUser() { UserName = username, Email = email};
var result = await _userManager.CreateAsync(user, password);
...
// here is call of mediatr command
var command = new CreatePlayerCommand(username, country);
var id = await _mediator.Send(command);
...
return ...
}
CreatePlayerCommand.Handle handler code
public async Task<int> Handle(CreatePlayerCommand request, CancellationToken cancellationToken)
{
var player = new Player(
request.userName);
_unitOfWork.Players.Add(player);
await _unitOfWork.SaveChanges();
return player.Id;
}
Why do you need to set Player.ApplicationUserId? You can generate it in the constructor or in DB. Why do you change the Id? If you access only from CreateUser command, you don't need it. Because the id is not coming from the client. You should generate automatically like that:
Player(string userName, ...)
{
ApplicationUserId = Guid.NewGuid();
UserName = userName;
...
}
I've created method in domain entity
private void SetUserId(Guid userId)
{
ApplicationUserId = userId;
}
And passing in CreatePlayerCommand and passing user id from _userManager.CreateAsync result. It works like desired.
Although there's no best idea for this sort of issue, this one could be designed like _buyerId in order class. Please see the link first.
_buyerId should be set in order class because it's a private field. Also, for persisting _buyerId by EF, for example, it could be configured in orderConfiguration.

How to save username in global variable asp

I have online exam system I want to save username in global variable or any other thing that just can save it.
I want this username for get and set data on SQL database.
I'm using a global variable in class but it replace in every login.
any way to save username foreach user?
public class GVar
{
public static string user
{
get; set;
}
public static string mail
{
get;
set;
}
public static string melli
{
get;
set;
}
public static bool go
{
get;
set;
}
public static System.Threading.Thread thread { get; set; }
}
Use Application or Session as the case may be.
Session variables are global but limited to current session (call it user for understanding).
Application variables are globally shared across all sessions.
So, following statements may be used to get/set variables at application level
Application["user"] = "abc"; //sets the value at application level
var user = Application["user"]; //gets the value stored at application level
Similarly, to make it global, but isolate at session level,
Session["user"] = "abc"; //sets the value at session level
var user = Session["user"]; //gets the value stored at session level
EDIT
For ease of use, I prefer implementing them as properties, somewhat like this:
Define the class with custom getter/setter properties, and add it to App_Code folder
public static class GVar
{
public static string user
{
get { return Session["GVar_User"]; }
set { Session["GVar_User"] = value; }
}
//...
}
Use it in your application, as you would normally do with any other property.
GVar.user = "abc"; //set value
var usr = GVar.user; //get value
You can save it on login like this:
Session["user"] = "gamesdl";
And then you can get the value during executing like this:
String username = (string)(Session["user"]);
You can use claims.
The claims are in identity. And you can config then in login action.

C# Class for UserData accross the whole Forms

i am trying to implement a windows desktop applicaiton c# VS 2010. To Application has a login form to ask the user to type his username and password. and the applicaiton checks them in the DB and returns the userdata (id, permissions, email, telephone) which are saved in DB.
Programmatically, when the login data is valid and correct, i create an instant from a class classed "clsUser" which provides the fields for the users.
and then fill the class with the data as normal and then open the main form and child forms after that.
My question is , how to access the class of user over the whole applicaiton (for example to check if he has the permission to access the Form or not). I tried different approaches like Calling string permission = FormLogin.clsUser.permission(); but its not fine .
thanks for your help or any suggestions !!
int id;
string fname;
string lname;
string uUsername;
public clsUser()
{ }
public int UserID
{
get { return id; }
set { id = value; }
}
public string FirstName
{
get { return fname; }
set { fname = value; }
}
public string LastName
{
get { return lname; }
set { lname = value; }
}
public string Username
{
get { return uUsername; }
set { uUsername = value; }
}
public override string ToString()
{
return base.ToString();
}
You can access to this object over the whole application by making it static:
public static class clsUser() { }
Now you can access its properties with:
string userPermission = clsUser.Permission;
You can set a property by:
clsUser.Permission = "Administrator";
You dont have to create a new Instance of a static class. You can access to it over the whole application by calling it with its class name (in your case clsUser) and the property name you want to access like above written.
Hope this is useful ;)
you can create a Global class using the singleton pattern. Inside that you can hold your actual User as a Property and access it via
var user = Global.Current.User;
var permission = Global.Current.User.Permission;
I found a topic for the singleton pattern here
Thread Safe C# Singleton Pattern

Getting IdConvention in RavenDB

Lets say we have a User class
public class User
{
public User() {
Created = DateTime.Now;
Tags = new List<string>();
}
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Created {get;set;}
public IEnumerable<string> Tags {get; private set;}
}
And one might want a user to have an id like [FirstName]/[LastName] so we register an IdConvention like this:
_documentStore
.Conventions
.RegisterIdConvention<User>(
(dbname, commands, user) => user.FirstName +"/" + user.LastName ));
Now lets say you created a new user with a new set of tags attached. You want to store it in RavenDB if the User does not exist. However, if the User does exist you don't want to overwrite the existing Object as you want to keep the initial Created date. Therefore you only update the Tags enumeration with the values of the newly created User.
You might do something like this:
public void AddOrUpdateUser(User newUser) {
using (var session = _documentStore.OpenSession())
{
var existingUser = session.Load<User>("myFirstname/myLastname")
if(user != null) {
existingUser.Tags = user.Tags;
}
else {
session.Store(newUser);
}
session.SaveChanges();
}
}
However, if for some reason I changed my IdConvention, I have had to update the code above as well. Is there a way to reference the IdConvention registered in order to calculate the id for the newUser Object. With this id value you could check wether an item exists or not rather than creating the Id by yourself.
After registering an id convention, the GenerateDocumentKey method will use that convention instead of the default hilo generation scheme.
It needs some parameters, which are easiest to get at if you first cast the IDocumentSession to a real DocumentSession.
var s = ((DocumentSession) session);
var key = s.Conventions.GenerateDocumentKey(s.DatabaseName,
s.DatabaseCommands,
yourEntity);

Creating and storing a session

I'm working on creating a session for a user login on my website. I can initialize the session and use its members just fine, but I also need a method within my session class that will store itself. I need to provide HttpSessionState as an input parameter, and then store it into an object like: Session["sessionName"]=this;.
Furthermore, when I want to retrieve the session, it won't yet be created, so it must be static. Then I need to return a new instance of my session class with the properties filled (username and companyID) out of the HttpSessionState.
How can this be done in my session class? What I've described above is from the research I've done that provides a particular solution to my problem, but since I'm new to using session, I don't quite understand it.
Thanks.
Snippet of my session class:
public class MySession : System.Web.UI.Page
{
private MySession()
{
Username = Business.User.labelUsername;
CompanyId = Business.User.labelCompanyId;
}
public static MySession Current
{
get
{
try
{
MySession session = (MySession)HttpContext.Current.Session["sessionName"];
if (session == null)
{
session = new MySession();
HttpContext.Current.Session["sessionName"]=session;
}
return session;
}
catch (NullReferenceException e)
{
Debug.WriteLine("NullReferenceException:");
Debug.WriteLine(e);
}
return null;
}
}
public string Username
{
get; set;
}
public string CompanyId
{
get; set;
}
}
You could try using a serialized "session info" object:
[Serializable]
public class SessionInfo
{
// Stuff to store in session
public string Name { get; set; }
public int Foo { get; set; }
private SessionInfo()
{
// Constructor, set any defaults here
Name = ""
Foo = 10;
}
public static SessionInfo Current
{
get
{
// Try get session info from session
var info = HttpContext.Current.Session["SessionInfo"] as SessionInfo;
// Not found in session, so create and store new session info
if (info == null)
{
info = new SessionInfo();
HttpContext.Current.Session["SessionInfo"] = info;
}
return info;
}
}
}
You can then use this from within your application like this:
SessionInfo.Current.Name = "Something Here";
SessionInfo.Current.Foo = 100;
The serialization/deserialization is all done within the SessionInfo object, and you get the benefit of type safe data.
What you are asking about is called serialization and deserialization.
Serialization is taking an object and converting it to a format, such as a string, that can be stored. Deserialization is the reverse of that action.
The "quick" way is to add the [Serializable] attribute to your class. However, without knowing the details of that class it's hard to say whether it is in fact easily serializable without a bit of work.
Here's a walkthrough: http://msdn.microsoft.com/en-us/library/vstudio/et91as27.aspx

Categories