/*
 * Copyright 2017 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.keycloak.authentication;

import org.keycloak.TokenVerifier.Predicate;
import org.keycloak.authentication.authenticators.resetcred.ResetCredentialEmail;
import org.keycloak.common.VerificationException;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.events.EventBuilder;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.services.ErrorPage;
import org.keycloak.services.messages.Messages;
import org.keycloak.services.resources.LoginActionsServiceException;
import java.util.Objects;

/**
 * Additional checks for {@link ResetCredentialsActionToken}.
 *
 * @author hmlnarik
 */
public class ResetCredentialsActionTokenChecks implements Predicate<ResetCredentialsActionToken> {

    private final KeycloakSession session;

    private final RealmModel realm;

    private final EventBuilder event;

    public ResetCredentialsActionTokenChecks(KeycloakSession session, RealmModel realm, EventBuilder event) {
        this.session = session;
        this.realm = realm;
        this.event = event;
    }

    public boolean lastChangedTimestampMatches(ResetCredentialsActionToken t) throws VerificationException {
        // TODO:hmlnarik Update to use single-use cache
        UserModel m = session.users().getUserById(t.getSubject(), realm);
        Long lastChanged = m == null ? null : ResetCredentialEmail.getLastChangedTimestamp(session, realm, m);

        if (! Objects.equals(lastChanged, t.getLastChangedPasswordTimestamp())) {
            if (m != null) {
                event.detail(Details.USERNAME, m.getUsername());
            }
            event.user(t.getSubject()).error(Errors.EXPIRED_CODE);
            throw new LoginActionsServiceException(ErrorPage.error(session, Messages.INVALID_CODE));
        }

        return true;
    }

    @Override
    public boolean test(ResetCredentialsActionToken t) throws VerificationException {
        return lastChangedTimestampMatches(t);

    }

}
