Search code examples
authenticationdomain-driven-designcqrs

Are login/register commands or queries in CQRS


So for the login, since it doesn't really make anything new in the database but rather just returns if we've logged in, and possibly some user data, should it be a command or query?

And as for the register, since it creates a new user, should it be a command then? What if i want to return the users data or a jwt?

Should i run my commands and once the client receives a response run a query right after them?


Solution

  • As with most design related questions, I’d answer this one with ‘it depends’. I have seen both solutions implemented in different situations.

    The main question you’d need to ask is whether you consider a user logging in as a state change of the system or not. Note that whether it changes state in de database isn’t relevant. The system is more than the database.

    Log in as a command

    For some systems, it’s important to know which users had been logged in and when, from where, etc. One example I had seen was a medical system that needed to record which doctor logged in when and where, and which medical records had been accessed. Also, logging in on one machine would stop tbe session on another. A reliable trace of these actions was essential to the application. As such, log in was implemented as a command which generated events that were stored in the Event Store. Projections kept the current logged in state for each user.

    Log in as a query

    Most systems I have seen, however, simple beed to know whether any given credentials can ve mapped to a user account. If that is the case, a token is generated containing the ‘proof’ of authentication. The system itself doesn’t really care who is logged in. It’s just that each request needs to be validated by checking the ‘proof’. In this case, logging in is a query.