/*
 * Copyright 2015 floragunn UG (haftungsbeschränkt)
 * 
 * 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 com.floragunn.searchguard.user;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public final class AuthCredentials {

    private final String username;
    private byte[] password;
    private Object nativeCredentials;
    private final Set<String> backendRoles = new HashSet<String>();
    private boolean complete;
    private final int internalPasswordHash;

    public AuthCredentials(final String username, final Object nativeCredentials) {
        this(username, null, nativeCredentials);
        
        if (nativeCredentials == null) {
            throw new IllegalArgumentException("nativeCredentials must not be null or empty");
        }
    }

    public AuthCredentials(final String username, final byte[] password) {
        this(username, password, null);
        
        if (password == null || password.length == 0) {
            throw new IllegalArgumentException("password must not be null or empty");
        }
    }

    public AuthCredentials(final String username, String... backendRoles) {
        this(username, null, null, backendRoles);
    }
    
    public AuthCredentials(final AuthCredentials creds) {
        this(creds.username, creds.password, creds.nativeCredentials);
    }

    private AuthCredentials(final String username, byte[] password, Object nativeCredentials, String... backendRoles) {
        super();

        if (username == null || username.isEmpty()) {
            throw new IllegalArgumentException("username must not be null or empty");
        }

        this.username = username;
        // make defensive copy
        this.password = password == null ? null : Arrays.copyOf(password, password.length);
        internalPasswordHash = Arrays.hashCode(this.password);
        password = null;
        this.nativeCredentials = nativeCredentials;
        nativeCredentials = null;
        
        if(backendRoles != null && backendRoles.length > 0) {
            this.backendRoles.addAll(Arrays.asList(backendRoles));
        }
    }

    public void clearSecrets() {
        if (password != null) {
            Arrays.fill(password, (byte) '\0');
            password = null;
        }

        nativeCredentials = null;
    }

    public String getUsername() {
        return username;
    }

    public byte[] getPassword() {
        // make defensive copy
        return password == null ? null : Arrays.copyOf(password, password.length);
    }

    public Object getNativeCredentials() {
        return nativeCredentials;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + internalPasswordHash;
        result = prime * result + ((username == null) ? 0 : username.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        AuthCredentials other = (AuthCredentials) obj;
        if (internalPasswordHash != other.internalPasswordHash)
            return false;
        if (username == null) {
            if (other.username != null)
                return false;
        } else if (!username.equals(other.username))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "AuthCredentials [username=" + username + ", password empty=" + (password == null) + ", nativeCredentials empty="
                + (nativeCredentials == null) + ",backendRoles="+backendRoles+"]";
    }

    public Set<String> getBackendRoles() {
        return new HashSet<String>(backendRoles);
    }

    public boolean isComplete() {
        return complete;
    }

    public AuthCredentials markComplete() {
        this.complete = true;
        return this;
    }
}

@@ -674,107 +674,310 @@
 ava.
-util.Arrays;%0Aimport java.util.HashSet;%0Aimport java.util.Set;%0A%0Apublic final class AuthCredentials %7B%0A
+security.MessageDigest;%0Aimport java.security.NoSuchAlgorithmException;%0Aimport java.util.Arrays;%0Aimport java.util.HashSet;%0Aimport java.util.Set;%0A%0Aimport org.elasticsearch.ElasticsearchSecurityException;%0A%0Apublic final class AuthCredentials %7B%0A%0A    private static final String DIGEST_ALGORITHM = %22SHA-256%22;
 %0A   
@@ -1191,19 +1191,22 @@
 e final 
-int
+byte%5B%5D
  interna
@@ -2530,63 +2530,535 @@
     
-internalPasswordHash = Arrays.hashCode(this.password);%0A
+%0A        if(this.password != null) %7B%0A            try %7B%0A                MessageDigest digester = MessageDigest.getInstance(DIGEST_ALGORITHM);%0A                internalPasswordHash = digester.digest(this.password);%0A            %7D catch (NoSuchAlgorithmException e) %7B%0A                throw new ElasticsearchSecurityException(%22Unable to digest password%22, e);%0A            %7D%0A        %7D else %7B%0A            internalPasswordHash = null;%0A        %7D%0A        %0A        if(password != null) %7B%0A            Arrays.fill(password, (byte) '%5C0');%0A    
     
@@ -3070,32 +3070,51 @@
 assword = null;%0A
+        %7D%0A        %0A
         this.nat
@@ -3874,24 +3874,32 @@
 hashCode() %7B
+        
 %0A        fin
@@ -3975,16 +3975,32 @@
 esult + 
+Arrays.hashCode(
 internal
@@ -4011,16 +4011,17 @@
 wordHash
+)
 ;%0A      
@@ -4415,16 +4415,31 @@
      if 
+(!Arrays.equals
 (interna
@@ -4451,19 +4451,17 @@
 wordHash
- !=
+,
  other.i
@@ -4480,16 +4480,17 @@
 ordHash)
+)
 %0A       

Replace unsafe Arrays.hash() method with SHA-256 hash to cope with #186 Full resolution of the issue will be done with merging #188 somewhat later.