package com.its.web.security;

import com.google.common.hash.Hashing;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.nio.charset.StandardCharsets;

@Slf4j
public class WebPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence charSequence) {
        if (charSequence == null) {
            throw new IllegalArgumentException("Encode Password Cannot be null");
        }
        return Hashing.sha256().hashString(charSequence, StandardCharsets.UTF_8).toString();
//        return charSequence.toString();
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        if (charSequence == null) {
            throw new IllegalArgumentException("rawPassword cannot be null");
        }

        if (s == null || s.length() == 0) {
            log.warn("Empty encoded password");
            return false;
        }
        // 사용자가 입력한 비밀번호는 암호화가 되어있지 않기 때문에 암호화를 한 후
        // 데이터베이스의 비밀번호와 비교해야 함.
        String rawEncodedPassword = this.encode(charSequence);

        return StringUtils.equals(rawEncodedPassword, s);
    }
}
