How to deal with authenticated state in a SproutCo

2019-07-31 17:02发布

问题:

In a (now sort of deleted) question by Peter Kniestedt he was wondering where and how to set a timer to check for the authentication of the user.

His question is part of a larger question (which is the title of this question). Because I think it is important that this question is answered, I created a new question as a way to gather all the important information in one spot.

回答1:

This is a typical case for the use of statechart, and more specifically concurrent states.

If you didn't know already, SproutCore contains a very useful library called SC.Statechart, which is a way of dealing with application state in a way which is much more controllable than through the use of boolean properties, as it also acts like a responder as well as a controller.

In this case you'd want a statechart which in the root has two concurrent states: one to deal with the states around authentication, and one to deal with the rest of the application.

MyApp.statechart = SC.Statechart.create({
  rootState: SC.State.design({
    substatesAreConcurrent: true,
    AUTH: SC.State.design({
      initialSubstate: 'CHECKAUTH',
      CHECKAUTH: SC.State.design({
      }),
      LOGIN: SC.State.design({
      }),
      AUTHENTICATING: SC.State.design({
      }),
      AUTHENTICATED: SC.State.design({
      }),      
    }),
    APPMAIN: SC.State.design({
    })
  })
});

How is this supposed to work: When your app starts, it will go to two states at once, one being the APPMAIN state which is the state which deals with the application itself. The other is the AUTH state, which will immediately go to the initial substate CHECKAUTH, which checks whether the user has a valid session. If not, this state should go to the LOGIN state, which is responsible for showing a login screen. When the user then performs a login, the LOGIN state transitions to the AUTHENTICATING state, which does the server checking. If this the attempt is invalid or incorrect, the AUTHENTICATING state should transition to LOGIN, otherwise to AUTHENTICATED.

To answer the original question this question is based on: if you need a timer somewhere which regularly checks whether the authentication is still valid, it should be in the AUTHENTICATED state. If it would fail, you can immediately transition to the LOGIN state, to display the login screen.

Using the state chart like this prevents the user having to reload or quit the application in order to login again, and possibly lose data as a result. In short it makes a much better user experience.