package stroom.security.impl;

import stroom.event.logging.rs.api.AutoLogged;
import stroom.event.logging.rs.api.AutoLogged.OperationType;
import stroom.security.api.UserIdentity;
import stroom.security.impl.session.SessionListResponse;
import stroom.security.impl.session.SessionListService;
import stroom.security.impl.session.UserIdentitySessionUtil;
import stroom.security.openid.api.OpenId;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Optional;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@AutoLogged(OperationType.MANUALLY_LOGGED)
public class SessionResourceImpl implements SessionResource {

    private static final Logger LOGGER = LoggerFactory.getLogger(SessionResourceImpl.class);

    private final AuthenticationEventLog eventLog;
    private final SessionListService sessionListService;
    private final OpenIdManager openIdManager;

    @Inject
    public SessionResourceImpl(final AuthenticationEventLog eventLog,
                               final SessionListService sessionListService,
                               final OpenIdManager openIdManager) {
        this.eventLog = eventLog;
        this.sessionListService = sessionListService;
        this.openIdManager = openIdManager;
    }

    @Override
    public SessionLoginResponse login(final HttpServletRequest request, final String referrer) {
        String redirectUri = null;
        try {
            LOGGER.info("Logging in session for '{}'", referrer);

            final Optional<UserIdentity> userIdentity = openIdManager.loginWithRequestToken(request);
            if (userIdentity.isEmpty()) {
                // If the session doesn't have a user ref then attempt login.
                final Map<String, String> paramMap = UrlUtils.createParamMap(referrer);
                final String code = paramMap.get(OpenId.CODE);
                final String stateId = paramMap.get(OpenId.STATE);
                final String postAuthRedirectUri = OpenId.removeReservedParams(referrer);
                redirectUri = openIdManager.redirect(request, code, stateId, postAuthRedirectUri);
            }

            if (redirectUri == null) {
                redirectUri = OpenId.removeReservedParams(referrer);
            }

            return new SessionLoginResponse(userIdentity.isPresent(), redirectUri);

        } catch (final RuntimeException e) {
            LOGGER.error(e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public Boolean logout(final String authSessionId) {
        LOGGER.info("Logging out session {}", authSessionId);

        // TODO : We need to lookup the auth session in our user sessions

        final HttpSession session = SessionMap.getSession(authSessionId);
        final Optional<UserIdentity> userIdentity = UserIdentitySessionUtil.get(session);
        if (session != null) {
            // Invalidate the current user session
            session.invalidate();
        }
        userIdentity.ifPresent(ui -> {
            // Create an event for logout
            eventLog.logoff(ui.getId());
        });

        return Boolean.TRUE;
    }

    @Override
    @AutoLogged(OperationType.VIEW)
    public SessionListResponse list(final String nodeName) {
        LOGGER.debug("list({}) called", nodeName);
        if (nodeName != null) {
            return sessionListService.listSessions(nodeName);
        } else {
            return sessionListService.listSessions();
        }
    }

}

@@ -525,16 +525,46 @@
 Inject;%0A
+import javax.inject.Provider;%0A
 import j
@@ -855,24 +855,33 @@
 ivate final 
+Provider%3C
 Authenticati
@@ -882,32 +882,33 @@
 ticationEventLog
+%3E
  eventLog;%0A    p
@@ -916,24 +916,33 @@
 ivate final 
+Provider%3C
 SessionListS
@@ -939,32 +939,33 @@
 ssionListService
+%3E
  sessionListServ
@@ -983,24 +983,33 @@
 ivate final 
+Provider%3C
 OpenIdManage
@@ -1001,32 +1001,33 @@
 er%3COpenIdManager
+%3E
  openIdManager;%0A
@@ -1076,16 +1076,25 @@
 l(final 
+Provider%3C
 Authenti
@@ -1107,16 +1107,17 @@
 EventLog
+%3E
  eventLo
@@ -1156,16 +1156,25 @@
   final 
+Provider%3C
 SessionL
@@ -1183,16 +1183,17 @@
 tService
+%3E
  session
@@ -1242,16 +1242,25 @@
   final 
+Provider%3C
 OpenIdMa
@@ -1264,16 +1264,17 @@
 dManager
+%3E
  openIdM
@@ -1719,16 +1719,22 @@
 Manager.
+get().
 loginWit
@@ -2229,16 +2229,22 @@
 Manager.
+get().
 redirect
@@ -3241,16 +3241,22 @@
 ventLog.
+get().
 logoff(u
@@ -3540,32 +3540,38 @@
 sionListService.
+get().
 listSessions(nod
@@ -3633,16 +3633,22 @@
 Service.
+get().
 listSess

Apply REST resource stds to SessionResourceImpl