package com.telephoners.krakyournet.ctf.repositories;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.telephoners.krakyournet.ctf.beans.User;
import io.dropwizard.auth.basic.BasicCredentials;
import org.apache.commons.codec.binary.Hex;
import org.mongodb.morphia.Datastore;

import java.security.MessageDigest;

@Singleton
public class UsersRepository extends Repository<User>
{
    private MessageDigest messageDigest;

    @Inject
    public UsersRepository(Datastore datastore, final @Named("messageDigest") MessageDigest messageDigest)
    {
        super(datastore);
        this.messageDigest = messageDigest;
    }

    public User getUserByName(String username)
    {
        return datastore.createQuery(User.class)
                .field("name").equal(username)
                .get();
    }

    public User authenticateUser(BasicCredentials basicCredentials)
    {
        return datastore.createQuery(User.class)
                .field("name").equal(basicCredentials.getUsername())
                .field("password").equal(Hex.encodeHexString(messageDigest.digest(basicCredentials.getPassword().getBytes())))
                .get();
    }
}
