Fluent NHibernate - mapping portions of a single table into multiple classes with a few shared fields - nhibernate

I have a situation where a User table has lots of information about a user (first name, last name, email, etc) in addition to credential data (username, password, prior passwords, etc). Normally I would separate Authentication from Personalization, but this table is long established and I can't do that.
It bothers me to have 1 user object with all this data in it that is being passed around my application. I instead want to split this out into two objects: User and UserCredentials. User can be freely passed around my application without leaking any of the passwords, while UserCredentials will be used only in my services backend for validating and authenticate a user.
That seems simple enough. However, some fields need to be shared across both these objects. Will this cause issues with nhibernate when one of my objects is updated? For instance if a username change takes place and both have the username in the object, will both objects be updated?

If User and UserCredentials represent two views of the same entity, do not create two classes for them. It'll only lead to pain.
Alternatives:
Use a component to expose the "public" part of the entity and pass that
Use a DTO to contain exactly the fields you need and pass that

Related

How should I deal with multiple data objects that connect together in a UI Automation Framework

I'm creating an automation framework. The test cases are separated from the pages that they interact with. I'm also dealing with multiple different data objects. As the framework has gotten more complex, we realized that we have to determine the best way to read this data, add to it, change it, reset it, etc...
Example:
You can have multiple User objects.
A User object can have multiple Group objects, single Email field.
A Group object can have a single Name field, multiple Invited User objects, Member User objects. -An Invited User and Member User are User objects, but can not have their own groups-
So, if a User creates a Group, invites multiple Users, and some of those Invited Users convert to Member Users... would we:
A) Have the test case pass in a User, Group, and Invited User objects to a page class that creates it. Then the page class adds the Invited User object to the Group object, and the Group object to the User object. Then the test case only needs to pass around the User object when it wants to convert some of those Invited Users to Member Users and eventually do cleanup after the test is done.
B) Have the test case pass in a User, Group, and Invited User object to a page class that creates it. Then the test case would pass in a Group object and Invited User object to a page class to convert them into Member Users. Then the test case would need to keep those relationships straight when moving through the test and doing cleanup.
C) Have the test case create the objects, but only pass specific fields needed for the operation of the method it is calling. Create Group would need Name. Invite User would need Email, etc... The test case would then need to update the objects and keep the relationship between them (as either a single object, or multiple objects).
Last thing... If C is the best option, at what point do you stop passing in specific fields of the object and just provide the object as a whole?
Each test can be decomposed into a number of steps. Some steps automate the web browser. Others insert data to the database, or query the database in order to make assertions. The challenge is to organize these "steps" as methods in one or more classes. An individual test should just call these methods.
The internals for these methods can use selenium page objects, repositories, entity objects — whatever is necessary to perform the test. A sample test could look something like this (you didn't specify a programming language, so I used C#):
Given.User.Create("Johnny", "Testerson"); // insert user into database
Given.User.LogIn("Johnny", "Testerson"); // use page object to log in
// Use page objects to create group
When.Group.Create(name: "Test group",
invites: new [] { "a#example.com", "b#example.com" });
// Query database, make assertions
Then.Group.InvitesShouldBeSent(group: "Test group",
recipients: new [] { "a#example.com", "b#example.com" });

How to manage multiple user types in IdentityServer4 using AspNet Identity?

What is the best way to store your user information per client? I have several applications which all use the same IdentityServer instance for authenticating. ASP.NET Identity shows how to extend a user by inheriting from IdentityUser.
public class CustomUser : IdentityUser
{
public Int32 CompanyId { get; set; }
}
However, I have applications that have mutually exclusive user information(eg. other applications don't need CompanyId and have properties the the CustomUser's application doesn't need.).
One way would just to create a single type containing all the properties for both. There could be a problem when a property overlaps where both applications need CompanyIds for different companies, not to mention that every column would always be queried every time a lookup was done, so this doesn't seem right. The other option is that I could just create a UserData table in the client applications and query from there as needed which is probably what I have to do since I don't think there is a better option.
If anyone knows a better way let me know.
If would be perfect if UserManager allowed for registration with multiple custom user types and you could get different subsets of data based your choice while each query was optimized for only the data it needed. Then you could put an SQL index per type and maybe even user TPH in entity framework to organize the information.
Unless diving too deep into too app-specific stuff, it looks like a normal user profile.It contains a number of claims describing the user. Let's consider only user specific, not application specific. For instance there are age, country, postal address, gender, whatever. And some apps need only age and country to restrict some content, while the others need postal address or email.Authorization request can contain a set of claims and scops to fulfill these requirements.All above is just about user information, not access rules, and all above is already in the protocol.
Regarding more app-specific... why not to store such stuff more close to the apps and link by user id...

REST API optional path elements

I am in the process of designing a new API and am trying to make it as simple as possible. For the intended system most API consumers will be referencing objects that belong to them alone however a few other accounts will "own" objects in other peoples accounts. The questions is whether account becomes a required part of the path or an optional inclusion for these special super-accounts.
Here is an example spec and works fine in the single user context (Account ID "basic1"):
# return person "s4t4s2" for account "basic1"
GET /v1/person/s4t4s2
# return team "g3a35a" for account "basic1"
GET /v1/team/g3a35a
For super-accounts they have their own objects where the above implementation works, however they also require access to the properties of accounts they effectively own (Account ID "super1"):
# return person "s4t4s2" for account "super1"
GET /v1/person/s4t4s2
# get team "g399a2" for account "super1"
GET /v1/team/g399a2
# return person "s4t4s2" for account "basic1"
GET /v1/accounts/basic1/person/s4t4s2
Because most of my consumers will be dealing with the single account view is it best practice to use the second format for all accounts or is it entirely valid to use both formats with automatic scoping via authentication credientials when the account is omitted?
If I understand correctly, those are the same "person" resources, but they have multiple URIs? I would probably prefer having one URI for a single instance of a resource. Even if it has different "views". Different views can still be solved by either having different media-types, or just filling out fields differently on the same media-type depending on the user's permissions.
The advantage of having a single URI for a single instance is that it can be bookmarked, cached, etc. For example if a user's team/account view changes, it can't reuse its links to persons because the URIs change. I think that is not a good design.
If my understanding is wrong, and /v1/accounts/basic1/person/s4t4s2 is not the same person as /v1/person/s4t4s2 then disregard my comment. :)

MVC 4 : Passing around user group data

I am in the process of rewriting my PHP website in ASP.NET and writing the membership system.
I understand I can extend MembershipUser to add member specific properties but how can I pass around boolean group information such as Use Search, Edit Posts etc which are not user specific? Is there a framework item I am missing or should I just create a super object to pass this and other settings around?
Essentially what I want it an efficient way to access the users group properties in my controllers.
Apart from extending the MembershipProvider, you can also extend RoleProvider. RoleProvider is in charge of checking to which group a user belongs to, registering new roles, adding user to role(s), etc. To work with roles you will use Roles class which contains a lot of static methods.
In addition to this, each time you hit a Controller, you can query HttpContext.User property which implements IPrincipal. This property has method IsInRole that is used to communicate with RoleProvider to obtain information if a user is in specific group or not.
Also, in order to allow access to controllers or actions you can use Authorization attribute and list specific roles that have access to the controller.
The roles can be stored in a cookie (to cache them) or you can implement Application_AuthenticateRequest in global.asax and initialize GenericPrincipal manually. This object is passed over to HttpContext.User. The constructor of this object accepts an array of roles that are queried with IsInRole method.
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
// Check if user is authenticated
if (HttpContext.User != null)
{
// Extract roles from a cookie if you used FormsAuthentication
// or read them from a cookie or from some other cached location
// Split roles into array of strings
var roles = listOfRoles.ToArray(); // If it is stored in a List<string>.
var identity = HttpContext.User.Identity;
var principal = new GenericPrincipal(identity, roles);
HttpContext.User = principal;
}
}
The above code is not tested. I wrote it from top of my mind. It should give you a pretty good picture how to cache roles and to use them in the most efficient way.
UPDATE: In case that you need more advanced options where each role can have one or more functionality like your "Use search", "Can do something", "Can do that", I would implement the following security logic:
Users
Roles (users belong to roles)
AccessRight (Role can have one or more access right).
UsersRoles table would be for adding users to specific roles.
RolesAccessRights table is where you define specific rights to each role.
User never talks to Functionality. (BTW, this naming convention is just an example, you will follow your naming conventions).
At my last work this is how we implemented the Audit system (it was Web Forms based). However, in MVC you could override AuthorizationAttribute to check user's role and to check if Role has defined access rights. Considering that you have specific security requirement, you would have to use this attribute on every action where you see the need and necessity.
If you plan to implement this logic, forget about Membership, MembershipUser and Roles. Honestly, I don't use these classes any more. I have my own custom security that I implement and which I used in the last 4 projects without any need for update or modification.
UPDATE 2: The security solution that we used was based on custom MembershipProvider and RoleProvider. Thinking about it now, it was a mistake to rely on that because access to AccessLevel table had to be mapped via Entity Framework. Therefore we had to ways to query our security tables.
My suggestion to you would be to ignore Membership- and Role-related classes completely. The first reason is that you would avoid bothering yourself with unnecessary methods and properties when you override the providers. There would be too many methods with throw new NotSupportedException() in the method body.
Suggested implementation
You will need the following tables:
Users - (You need at least three columns UserId, UserName, Password). If you want to hash the password, you might have to store salt as well. Other columns like FirstName, LastName, etc. I would suggest you to store in a different table and link it with UserId. As for UserId type it's up to you whether you would use int or Guid.
Roles - (You need at least two columns RoleId, RoleName). Again, as with UserId, it is up to you which data type you want to use.
UsersRoles - Store UserId and RoleId. You might want to store properties such as whether the role IsActive which is a bit value.
AccessRights - This is where you would store a key of your access right. In your case that is like UseSearch, EditPosts, DeletePosts, etc. Here you should use at least three columns AccessRightId, AccessRightKey and AccessRightDescription. This description field will turn to be pretty valuable if you have a lot of access right keys.
RolesAccessRights - This is where you define to which role you have added specific access rights. Also have IsActive bit value in order to disable the specific access right to a role.
In MVC you would override AuthorizationAttribute. In this attribute you would specify a list of access rights that have access to controller and/or actions. How you plan to do this is entirely up to you, but I would create an enum with a list of values that are the same as AccessRightsKeys. That way you can use strongly typed access rights instead of string based list. For more information about implementing custom authorization attribute have a look at the references list.
Inside of this attribute, you would read User ID and retrieve the roles. Compare the AccessRightsKeys that you specified against the roles (RolesAccessRights table) to see if the role has access right and whether the rule is active.
As for the solution based implementation I would implement Security service layer which communicates with Security-based repository and unit of work solutions. Because you are using MySQL I don't know which ORM you can use or would you have to rely on ADO.NET with OLEDB providers for MySQL.
My usual approach is a top-down approach. I implement from the high up (like Presentation layer) and go down towards data access layer. That way at the end I have only those methods which I really use and there is no redundancy.
Well, I hope this gives you some picture on how to this. As for time it takes, you can do this in about 8-10 hours.
Reference:
Implementing a Role Provider
Roles Class
How to: Create a Custom AuthorizationAttribute

Redis newbie - equivalent approach to mysql table

I'm new to Redis and was hoping for a "best practice" solution to implementing the equivalent of a "users" table in a mysql database, for handling users in a web app.
Would I create a users SET in Redis? Or a users database with a SET for each user?
My standard setup for users is a serialized object in a standard key u:userid - this object gets retrieved on each request, and there is never any need to access only one of the properties.
You could also use a hash rather than json for the user properties, but my setup includes everything getting used as strongly typed objects and redis running on a different server from the client, so using json makes it easier to use generic deserialization and minimizes any latency issues.
In addition to the user object itself, you will need an index for any fields you need to use to find a user - for example to allow a user to log in with email address you will need a key e:email => userid. A hash will also work here - the important thing is that you need something that is O(1) to get from an email to a user object.
Sometimes parts of the user data should have their own keys - for example a followers list is a perfect match to a redis set, so is best stored in that form.
It really depends on what you'd want to do with the Users within your application. Another option would be to have each user be it's own hash, where they keys are properties (fields) for each user (firstName, lastName, etc). You could use a key that you increment as the ID generator for inserting, and potentially another set that you use to hold all of the user IDs.