I have done a fair amount of research on how to limit amount of users that can login into an application. Now I've seen people mentioning cookie-based checkups to see how many users are logged into the account but I haven't seen any implementation where I could see how that works exactly.
Besides that I'm wondering if there is already implemented solution of this in .NET MVC 5?
My final goal is following:
Only two users can login on one account
If third user logs in, the first one that logged in should be kicked out of the system automatically
Can someone help me out with this one ?
Best regards
This check sounds similar to Netflix check - you can login using only 5 devices.
But there is limitation on devices - hence different sessions in same login ID can be identified using IP addresses and device information in HTTP packet.
This is very nice code sample.
IsUserLoggedInElsewhere will check the logins from other places.
Instead of log everyone else out you will have to log out the first user based on login time whenever third user logs in using same account.
Please refer this article for more details about this.
public static bool IsYourLoginStillTrue(string userId, string sid)
{
CapWorxQuikCapContext context = new CapWorxQuikCapContext();
IEnumerable<Logins> logins = (from i in context.Logins
where i.LoggedIn == true &&
i.UserId == userId && i.SessionId == sid
select i).AsEnumerable();
return logins.Any();
}
public static bool IsUserLoggedOnElsewhere(string userId, string sid)
{
CapWorxQuikCapContext context = new CapWorxQuikCapContext();
IEnumerable<Logins> logins = (from i in context.Logins
where i.LoggedIn == true &&
i.UserId == userId && i.SessionId != sid
select i).AsEnumerable();
return logins.Any();
}
public static void LogEveryoneElseOut(string userId, string sid)
{
CapWorxQuikCapContext context = new CapWorxQuikCapContext();
IEnumerable<Logins> logins = (from i in context.Logins
where i.LoggedIn == true &&
i.UserId == userId &&
i.SessionId != sid // need to filter by user ID
select i).AsEnumerable();
foreach (Logins item in logins)
{
item.LoggedIn = false;
}
context.SaveChanges();
}
I think it can be done by one of two ways:
1 : by data base
-- Add a field in users table refer to login_status (Bool)- and Last_login_Time (Date)
-- Change login_status to (True) and Last_login_Time to dateTime.now
-- Before login get from Users table number of users with login_status true
-- if count less than two ..normal login
-- if count more than = 2 end session for user with earlier login time and set current user is logged..
2 - Also it can be done by using global variables in Global.asax and
Related
this is my code and I've set permissions so if a user id is 132 he/she will see button1, etc. The problem is that I have multiple of these permission throughout the webpage (for other functions) and if I need to add someone I have to change it in 5/6 places rather than one. Can I combine all the sessions into one master session? Also I dont want to create a table in the DB
else if (Session["UserId"].Equals("132") || (Session["UserId"].Equals("210"))
|| (Session["UserId"].Equals("41")) || (Session["UserId"].Equals("103"))
|| (Session["UserId"].Equals("404")) || (Session["UserId"].Equals("130"))
|| (Session["UserId"].Equals("92")) || (Session["UserId"].Equals("490"))
|| (Session["UserId"].Equals("172")))
{
//do something
}
I would create a seperate database table for permissions or add another row to the existing user-table with a boolean to check if the user is valid to see the button.
This is really too much just to check if a user is allowed to see the button or not.
You could also create a list with the userids and check if the current logged in user is in the list, then show the button.
Edit cause of comment to serve some code:
var allowedUserIds = new List<int> {1,2,3,4,5};
var currentUserId = Session["UserId"];
bool isInList = allowedUserIds.IndexOf(currentUserId) != -1;
if(isInList){
...
}
I have users table with generated LINQ-class with followed structure:
class User {
int Id;
string Login;
string Password;
string Mail;
...
Now I need to update specified columns (for ex. only Login and Password) and because I don't want to overwrite other fields, my code looks like this:
public User UpdateUser(int userId, User newUser)
{
User user = (from u in _context.Users
where u.Id == userId
select u).FirstOrDefault();
if (newUser.Login != default(string)) user.Login = newUser.Login;
if (newUser.Mail != default(string)) user.Mail = newUser.Mail;
if (newUser.Password != default(string)) user.Password = newUser.Password;
...
_context.SubmitChanges();
return user;
}
And call it like this:
var user = new User { Password = "123" };
UpdateUser(123, user);
For each field I need to write IF statement and I thinking that I doing something wrong. Also because I am using comparsion with default(string) I cannot set empty values to rows.
Please, tell me, what is right way to do this?
P.S.: Please, sorry for my bad English.
You are misusing LINQ 2 SQL. You shouldn't even have a generic UpdateUser method because you don't need it. If you want to write a certain field of an entity, just do it:
var user = GetUser(userId);
user.Password = "123";
And you're done. When you have made all changes to the object model, call SubmitChanges at the end. It is not necessary to call it after each mutation.
You are using LINQ 2 SQL as a CRUD repository but it is not meant to be one. It is meant to give you a live object model that you can treat like normal C# objects. In the end you synchronize with the database by calling SubmitChanges.
This is possible just with SubmitChanges:
This gets the user:
var user=context.User.Where(m=>m.id == "xyz").FirstOrDefault();
This updates the above user:
user.Password = "xyz";
context.User.SubmitChanges();
I think you are looking into the wrong way for optimization. An update command on single column isn't much different than on every other column than PK. Your validation logics might take more time to process than your optimized update command.
However if it is always the password that needs to be updated, you can do it this way :
public User ChangePassword(int userId, string password)
{
var user = new User() { Id = userId };
_context.Users.Attach(user);
user.Password = password;
_context.SaveChanges();
return user;
}
I have an ASP.NET WebForms application with a (EF) database.
Basically the two tables I'm concerned with are Users and Roles.
In Roles there's: Id (pk), UserId (fk), Type : String - which contains either Admin, User, Moderator, Publisher, etc.
In Users there's: Id (pk), Email, NameFirst, NameLast, Password, Username.
In designer I connected Users with Roles so that in Roles -> UserId == Id of User.
And now, after creating a class that inherits from RoleProvider, in function GetRolesForUser(string username) I want to get the enum of all the roles of a user whose id is that of the username.
So for instance if I get a user Agon, I want to be able to get an enum of all his roles for later use and also return them as string[] in said method.
So for after hours of head-numbing attempts I've been getting consistent errors. Not sure where to go from here:
public override string[] GetRolesForUser(string username)
{
using (SMEntities db = new SMEntities())
{
User user = db.Users.First(x => x.Username == username);
}
//throw new NotImplementedException();
}
I'm not sure where enums come into play really on this one, but how about the following:
using (SMEntities db = new SMEntities())
{
User user = db.Users.First(x => x.Username == username);
return user.Roles.Select(r => r.Type).ToArray();
}
How can I get the logged in user's UserId? I'm using the standard system generated AccountModel. I can get the username using:
User.Identity.Name
but I don't see the UserId field. I want to use the UserId as a foreign key for another table.
Try this:
using Microsoft.AspNet.Identity;
User.Identity.GetUserId();
That's how its done in the partial views for current MVC (MVC5/EF6/VS2013) templates.
Correct me if I'm wrong, because I've seen Aviatrix's answers a lot, but what happens if more than one user has the same name in the database?
I think you're looking for ProviderUserKey - Gets the user identifier from the membership data source for the user.
object id = Membership.GetUser().ProviderUserKey
Membership.GetUser() - Gets the information from the data source and updates the last-activity date/time stamp for the current logged-on membership user.
The best way to do so is to use the WebSecurty class
var memberId = WebSecurity.GetUserId(User.Identity.Name);
and don't forget to add [InitializeSimpleMembership] on top of your controller :)
Their are already very good answer but what i understood from your question is that you want to fetch data from database using id.so here is what you can do.
public List<ForeignkeyTable> RV()
{
var email = User.Identity.Name;
Usertable m = db.Uusertables.Where(x => x.user_Email == email).SingleOrDefault();
var id = m.user_Id;
var p = db.ForeignkeyTable.Where(x => x.user_fk_id == id).ToList();
return p;
}
This way you can return all the data from database of that id in foreignkey.
I'm adding onto my DNN module a check to exclude certain users from having to answer some questions when logging in. Instead of hard coding each individual role I'd like to instead just exclude anyone within a particular role group. That way if we have more roles in the future we can just add them into the role group if we want them to be excluded.
However, I don't know how you check if a user is in role group. I know how to check the role, but not the group if they are in one.
SOLUTION: Here's the code I put together based on the answers I got. Should work.
RoleGroupInfo RoleGrp = RoleController.GetRoleGroupByName(this.PortalId, "Role Group");
bool bShouldSkipQuestions = false;
if (RoleGrp != null)
{
Dictionary<string, RoleInfo> GroupChk = RoleGrp.Roles;
if (GroupChk.Count > 0)
{
foreach (var item in GroupChk.Values)
{
if (_user.IsInRole(item.RoleName))
{
bShouldSkipQuestions = true;
break;
}
}
}
}
Role groups aren't really intended to be used like that (they're intended just for end-user organization), so there isn't a direct way to check that. You'll want to get all of the roles in the group (RoleController.GetRolesByRoleGroup) and then check PortalSecurity.IsInRoles, passing in a comma-separated string of the role names.
Try this code:
var roleGroup = RoleController.GetRoleGroupByName(this.PortalId, "Role Group");
var shouldSkipQuestions = roleGroup != null
&& roleGroup.Roles.Keys.Any(role => _user.IsInRole(role));