Sobes.tech
Junior — Middle

How can a security mechanism be implemented to manage user sessions so that users can terminate their sessions themselves?

sobes.tech AI

Answer from AI

To manage user sessions with the ability to terminate sessions independently, the following mechanism can be implemented:

  1. Upon authentication, a unique session identifier (e.g., UUID) is created and stored in the database along with user information, creation time, and last activity.
  2. The client receives a token associated with this session (e.g., JWT with sessionId or a regular session identifier).
  3. To terminate a session, the user sends a request to the server specifying the session they want to end.
  4. The server marks the session as inactive or deletes it from the database.
  5. With each request, the server checks whether the session is active.

This approach allows the user to see a list of their active sessions (e.g., on different devices) and to terminate unnecessary ones.

Example code in Java (simplified):

class Session {
    String sessionId;
    String userId;
    LocalDateTime createdAt;
    boolean active;
}

// Terminate session
public void logoutSession(String userId, String sessionId) {
    Session session = sessionRepository.findByUserIdAndSessionId(userId, sessionId);
    if (session != null) {
        session.setActive(false);
        sessionRepository.save(session);
    }
}