Validating Individual Fields with AJAX - Where to put the logic? - validation

I have a form that, when you enter text into a field and tab off, a jQuery event is triggered to validate that field by calling the relevant controller action. For example, I have an AccountController and a ValidateField action. When the user tabs off of the Username field, it will send a request to /Account/ValidateField. I will then return a JSON result back based on the validation.
Ok, so let's say I want to validate a Username field. I want to check that enough characters were used, that the username isn't already in use, and that the characters used are allowed. Two of these are easy. However, I need access to the database to check if the username already exists.
Where would I put this logic? In the Service layer?

In a world where absolutely no business logic replication takes place:
The minimum length of a name and checking validity of charaters sounds like domain logic, so that should be in the domain. Your ajax call would call the service layer which would in turn call the domain and validate.
Checking the username isn't already in use accesess the persistance layer, so I think this would be more likely to live in the service layer. The service layer could just query the repository for Users with the specified name, and if any are returned, it is invalid.
In a world where we actually care about performance:
The checking of username uniqueness probably does require a trip to the service layer to access the database. But as for the other two, this could be done in the UI to save a trip to the service layer, but would then need to be replicated in the domain. This is advocated by Udi Dahan:
Command Query Responsibility Segregation
He suggests UI validation, and then replicate it in the domain, but don't bother giving a helpful message from the domain because theoretically the only people who are likey to get that far will be hackers.

Related

Password Validation / Requirements with Parse on the Cloud

The typical process of creating a a new Parse user does not allow for server-side validation or any sort of input requirements. These can be implemented on the client-side but can be easily circumvented by anyone willing to try.
So how would someone provide a Sign Up where the fields are checked against different requirements (defined by regex) in cloud code?
Two possibilities I see immediately:
An extra method that takes in all inputs as parameters, checks against regex, on success continues to Parse.User.signup() then returns session key and assigns it to the device that just signed up.
Parse.Cloud.beforeSave(...) before the user is saved you check the fields, and reject if it doesn't pass a test.
Problems I see with each:
EVERYONE with my AppID and a client ID can call this method. Since the checks are being done server side there's need for additional filtering client-side which can be overwritten; an adversary could flood my Parse app with requests or bloated inputs. Also you are then sending the user's password over the network.
The password is encrypted upon user creation(setting password), according to documentation I've read. Everything but the password can be checked against a regex.

asp.net mvc 3 - sending an email and getting the return for validation a task (registration, form validation...)

I am having a register form that user fill in, once the form fill in, the registration is postponed till the user recieve an email to check that his email is ok, then when he reply the email, the registration is fully proceed.
I would like also the process to be automatic, without the need for the user to entered any number ect, just the need for him to click on the email to confirm, and automatic on my side too.
I want the process to be available to some others task than the registration process as well if possible.
Do I need to do all way check/123456 with the 123456 generated or is there a better way to do, a component, nuget that can do the job ? you experiences return would be helpful
thanks
You appear to be on the right track.
I do a similar thing quite often. It isn't generic since I do not need it but you can change that quite easily.
Once a user registers I send an activation e-mail that contains a link that when clicked navigates to something such as http://domain/member/activate/id where the id is a GUID. That is all I need. I look up the member id and activate it. Chances of someone guessing a new member's id are rather slim and even if they do it is very far from a train smash.
From what I can tell you need something more generic and a bit more security. You could always create some key (like a new GUID) that you store along with the user and then the activation calls: http://domain/member/activate/id?key={the guid}. You could even encrypt the key. But that is up to you.
For something that can be re-used and is more generic you could create an activation component that contains a list of activation ids. But to then activate a specific type of entity (such as user registration or form validation) you would need to have a way to perform that on the back-end. For example, when you call http://domain/activation/activate/id internally is looks up the id and gets the type. The activation request is, of course, created when, e.g., your user registers. You would probably want to store some expiry/timeout since a user may never activate.
For each type you could have an activation mechanism on the relevant controller: member/activate/key or formvalidation/activate/key. So when you activation controller receives a request to activate it has a list of routes conigured per type and the navigates to the relevant route to perform the 'actual' activation.
Another option is to have an in-process component perform activation e.g.: an IActivator interface implemented by a MemberActivator or FormValdationActivator and then have an IActivatorProvider implementation that gives you the relevant provider based on a type (.NET Type or a string type you provider --- that's up to you).
You could even pass an ActivationRequestCommand along to a service bus endpoint if you are so inclined.
So you have many options. HTH
If you are a developer I suggest you at least try to start with the code... then ask again if you get stuck providing a sample of what you've done.
What you are looking to do is basically use a temporary url that posts to a page to complete the registration...

Validate/Change Password via REST API

I want to change a user password via a REST API. This is not a forgotten or reset password function, but a logged in user wanting to change their password.
The form requires the current password, the new password, and a confirmation for the new password. However, I want to validate each form field as the user fills it out. This is trivial for newPassword and confirmNewPassword (client side), but not for currentPassword. Currently performing update to the User object via PUT /users/:id. If a password parameter is passed, I check for the currentPassword parameter and ensure it is correct prior to saving. However, for validation, I'm unsure of the best approach.
I also have a POST /users/validate - not sure if this is best either. This validates a User object for both create and update, but only validates fields that belong to the User object (email, username, password). currentPassword isn't one of these. Wondering how to handle this. Some things I've considered:
POST /users/check_password,
POST /users/validate (adding in validation for currentPassword if that parameter is passed, and check that currentPassword matches the users existing password) and
POST /users/:id/validate (separate validation for existing user, requiring currentPassword).
Any thoughts or advice would be greatly appreciated. My first application that only exposes functionality via REST API.
I'll start by pointing out that authentication is often handled outside of a REST model. When a user provides their credentials, they are not providing a REpresentation of their account object's STate (REST); nor is the response they receive such a representation. Because the user account resource state does not include both 'current' and 'new' passwords, the provision of both a 'current' and a 'new' password in a request can never truly fit under the REST model, but professionals often describe a 'continuum' of RESTfulness, with some APIs being completely RESTful and others falling between RPC (Remote Procedure Call) and REST.
It's not uncommon to have a RESTful component of an API that handles the serving of data models, and a more RPC component of an API that handles user accounts. You get to decide between the two. If your project includes super users that manage multiple user accounts, I would suggest trying to shoe-horn that into a REST API. If each user manages only their own account, I would suggest RPC.
If you've decided to use REST for account management, then you must choose an appropriate HTTP method (GET, POST, DELETE, HEADERS, etc). Clearly you require a method that will effect a change on the server (POST, PUT, DELETE, etc). In contrast to user orbfish's conclusion above, I'm going to say that PUT would be an appropriate method, under certain restrictions.
From RFC 2616, which formally defines our HTTP methods:
"Methods can also have the property of 'idempotence' in that (aside from error or expiration issues) the side-effects of N > 0 identical requests is the same as for a single request. The methods GET, HEAD, PUT and DELETE share this property. Also, the methods OPTIONS and TRACE SHOULD NOT have side effects, and so are inherently idempotent. "
Idempotency here means that if we make the same request n times in a row, the state of the server under the effects of the nth request will be the same as the state of the server under the effects of the first request. User orbfish correctly notes that if we make the request:
PUT /users/:id/account {current-password: 'a', new-password: 'b'}
and repeat it:
PUT /users/:id/account {current-password: 'a', new-password: 'b'}
that our first request should receive a response indicating success and our second request should receive a response indicating failure. However, the idempotency of PUT only requires that the state of the server is the same following both requests. And it is: after the first request the user's password is 'b' and after the second request the user's password is 'b'.
I mentioned restrictions above. You might want to lock a user out after m attempts to change a password unsuccessfully; this would provide security against brute-force password attacks. However, this would break the idempotency of the request: send a valid password request one time and you change your password, send it m more times and the server locks you out.
By specifying the PUT method, you are telling all clients that it's safe to send a request as many times as needed. If I as a client send a PUT request and our connection is interrupted such that I don't receive your response, I know that it is safe to send my PUT through again because it is idempotent: idempotency means that if you receive both requests it will be the same to your server as just receiving one. But if you're going to lock me out for an unsuccessful request, then it isn't safe to send a second request until I know whether you have received the first.
For this reason, you might consider PATCH or POST. I would suggest using PATCH. Whereas POST is described as either appending a new resource to a list or appending data to an existing resource, PATCH is described as a 'partial update' on a resource at a known URI. And unlike PUT, PATCH need not be idempotent.
I don't like /check_password or /validate because they're verbs; your first "update user" is better REST.
You can add the currentPassword to your User object as an unpersisted field, or as part of the Authentication header (username:password).
I would definitely change this from a PUT to a POST, though, because the same call with the same currentPassword cannot succeed twice (PUT is idempotent).
You are changing a property of the user resource (i.e., the password). If you use HTTP Basic for your authorization, you are already providing the current password, so there is no need to repeat it. I would simply PUT the entire user resource with the new password. Example:
PUT /users/fiddlerpianist HTTP/1.1
Content-Type: application/json
Authorization: Basic ZmlkZGxlcnBpYW5pc3Q6bXlub3Rzb2F3ZXNvbWVvbGRwYXNzd29yZA==
{
"password": "My awesome new password that no one will ever be able to guess!"
}
The other advantage of doing it this way is that you don't necessarily need to provide the old password, as long as you are a credentialed user that has access rights to modify the user resource. Maybe you're a customer support specialist who is never supposed to ask for the customer's old password but they are requesting a password change over the phone (after they've proven to you their identity and you've proven your identity to the system).
You want to avoid using a non-idempotent request in this case (such as PUT or PATCH), as that can lead to responses whose outcomes are uncertain (suppose the server returns a 500 for a non-idempotent request... you as the client have no idea what state the server left your resource in).
EDITED TO ADD: Note that, in a RESTful app, there is no concept of being "logged in." The communication from the client to the server is entirely stateless (it's the payload and method that communicates the state). Also, there really doesn't need to be a concept of validation the way you describe it, as a request to change the state of a resource can either be met with a 200 OK (if valid) or a 400 Bad Request (if invalid).
Another option is to create surrogate resources on user. If you're using HATEOAS you could link down to user/x/pwdchange from the user resource. And I want to clarify pwdchange is conceived as a noun/resource, not as a verb:
GET /user/jsmith/pwdchange List of password change requests (history)
POST /user/jsmith/pwdchange Create password change request, return id=1
GET /user/jsmith/pwdchange/1 Get password change resource, which would
include the outcome (success, failure, etc)
So, in short, I'm creating a resource named 'pwdchange' that is fully compliant with a REST view of the problem domain.
You might think about why you need to validate the current password as soon as it's entered. I've not seen a site do that. Second, it's perfectly fine to have a service that just validates something. Its called being practical verse beating yourself up trying to be RESTFul

Business rule validators and command handler in CQRS

I am new to CQRS and I am tying to make sense of business rule validation within the write side (domain). I know that client side validation should be done in terms of valid date (required field, string length, valid email, etc) and business rule/business domain related validation should be done in domain side. Actually, same client side validation rules should also be applied to command in the domain since we don't trust the users.
So, we have a valid command (AddEmailToCustomer) and the command handler is invoked on the command. Here is my approach to validation.
Create instances of two command validators in the command handler.
First one validates the command data same as client side validation (required field, valid email, etc.)
Second validator validates the data based on logic within the second validator. Something like "is this customer active", or what ever. I know the changing email doesn't fit here but it is not important. Important thing is there is a business validation here.
We look at the ValidationResult returned by the Validator.Validate(ICommand cmd) and we find out there are errors
We will not get a customer from repository to call on the UpdateEmail method on the AR. So what do we do at this point?
Do I throw and exception in the command handler and add these errors there?
Do I send the command to error queue or somewhere else?
Do I respond with something like Bus.Reply and return error code? If so, what do I do with the error messages?
How do I communicate these errors to the user? I know I can email them later but in a web scenario I can send a request id in the command (or use the message id), and poll for response with the request id and display the error messages to user.
Your guidance is appreciated.
Thanks
It's important to know that commands can be rejected after they are sent to the handler.
At the very least, you could encounter a concurrency violation that cannot be detected until the aggregate root is touched.
But also, the validation that can occur outside of the entity is simple validation. Not only string lengths, numeric ranges, regex matching, etc. but also validation that can be reasonably satisfied through a query or view, like uniqueness in a collection. It's important to remember that validation involving a materialized view is likely to be eventually consistent, which is another reason a command could be rejected from the aggregate, inside the command handler. That said, to preempt the situation, I often use read models to drive UI choices which only allow valid actions.
Validation that cannot occur outside an entity is your business logic validation. This validation is dependent upon the context in which it is run (see Udi Dahan's Clarified CQRS).
Business logic should not be in a separate validation service. It should be in your domain.
Also, I'm of the opinion that validation which occurs in the UI should be re-checked not in the command handler, but in the domain too. That validation is there to prevent corruption to the domain -- if it is not performed outside the domain then the domain is still subject to invalid parameters.
Using command handlers to duplicate this validation is only a convention. If no other front end is sending commands, then it is a useless duplicate. If there are multiple front ends, it is just one choice of where to place the then-necessary duplicate validation, and in those cases I prefer to handle it in the domain.
Lastly, you will need to bubble up commands rejected from within the handler. I accomplish this with exceptions as much as possible.

About software design: Where I must check parameters?

Imagine I have an application that request to the user a name, a category list. When user click on save button, application will save name and category to a database.
I have a layer that get name and category from UI. This layer check if there is a name (a string with length > 0). If this is correct, it will pass name a category to another layer. Note: category is a radiobutton list where one item is always selected.
On this second layer, application will select a suitable class to save name, depending on category.
On last layer, a class will save this name on a database. On this class I will check if name is empty or not.
My question is: where is the right place to check method's input parameters? on every layer? Maybe, I'm going to use these layers on others developments.
Is my example correct? Maybe, I can left validation on database layer and raise an exception to UI layer.
In general, in terms of the larger question about validating input that is ultimately persisted, it is best to:
Convert the input parameters to a
fully encapsulated business object as
soon as possible after you receive
it.
Validate early and fail fast then to
wait until you get to a lower layer
-- waste of resources, waste of time, possibly more complex (more things to
roll back).
Validate the business logic once and make that part of
your object instantiation process. (but note that validation of view logic and persistence logic may need to be done at the other layers and is separate from business logic)
Model how your object is persisted
using an ORM (e.g., Hibernate) so
that you could work purely at the
object level in memory and leave
persistence as an implementation
detail. Focus the business logic at
the object layer.
And in terms of method validation itself, I agree with Oded -- at every layer, and it should be done immediate upon method entry. Again, this is part of the fail fast methodology. But, as I noted above, this doesn't mean you validate business logic at every method (or every layer). I'm just referring to the basic practice of validating inputs (either by assertions or explicit checks and exceptions thrown).
where is the right place to check method's input parameters? on every layer?
Yes, on every layer. This is called defense in depth.
There are different reasons to do so on each layer:
UI/Client code: keep things responsive and avoid roundtrips when data is invalid
Business layer: Ensure business rules are kept
Data layer: Ensure that valid data is passed through
I disagree with the recommendation about every layer, all the time. It sounds too dogmatic to me.
All design represents a choice between functionality and cost. Your validation choices should reflect that as well.
I think your decisions should take into account the sharing and reuse of layers.
If the database is shared by more than one application, then the database cannot depend on every application validating properly. In that case, the database must validate to protect itself.
In this day and age of SQL injection attacks, I think binding and validating prior to reaching the persistence tier is a must. The schema should do what it must to ensure referential and business integrity (e.g. unique constraints on columns and required "not null"), but other validations should be done prior to hitting the database.
If the database is wholly owned by one and only one application, and there's a service that is the only gateway into the data, then validation can be done by the service. The cost of duplicating the validation on the database layer can be waived.
Likewise between the UI and the service layer.
Double validation on client and service tiers is common because the service is shared by many clients in a service oriented architecture. Today your service might be used by a browser based UI; suddenly there's a flock of mobile apps along side it that clamor for services, too. In that case the service absolutely must validate and bind each and every request.
No manufacturer polishes every surface to mirror quality. Sometimes a rough cast surface is permissible, because the benefit of grinding and polishing is negligible and the cost is too great.
Same with software.
I don't like dogmatic statements. It's better to understand the implications of your choices. Know the rules and when it's appropriate to break them.
If you're going for very loose coupling where other applications will also make use of these same layers, then I would recommend doing input checking at every step. Since each class/method should have no knowledge of expectation of the other classes/methods which ran before them in the stack, each one should enforce its requirements individually.
If the UI requires that a value be in the text box when the button is clicked, it should validate accordingly.
If the business logic requires that a name never be null/empty, it shouldn't allow a null/empty value to be placed in that property.
If the data layer has a constraint on that field requiring that a value be present, it should check that a value is present before trying to persist the data.

Resources