DS-Lab / src / main / java / dslab / authentication / AuthenticationService.java
AuthenticationService.java
Raw
package dslab.authentication;

import dslab.routing.Address;

import java.util.Collection;
import java.util.logging.Logger;

/**
 * Contains logic related to DMAP user authentication
 */
public class AuthenticationService {

    private final ThreadLocal<User> loggedInUser = new ThreadLocal<>();

    private static final Logger LOG = Logger.getLogger(AuthenticationService.class.getSimpleName());
    private final Collection<User> users;

    public AuthenticationService(Collection<User> users) {
        this.users = users;
    }

    public User login(String username, String password) throws AuthenticationException {

        if (loggedInUser.get() != null)
            throw new AuthenticationException("Log out first");

        loggedInUser.set(
                users.stream()
                        .filter(user -> user.getUsername().equals(username))
                        .filter(user -> user.getPassword().equals(password))
                        .findAny()
                        .orElseThrow(() -> new AuthenticationException("Invalid credentials")));

        return loggedInUser.get();
    }

    public User getLoggedInUser() {
        return loggedInUser.get();
    }

    @SuppressWarnings("BooleanMethodIsAlwaysInverted")
    public boolean isLoggedIn() {
        return loggedInUser.get() != null;
    }

    public void logout() throws AuthenticationException {
        if (!isLoggedIn()) throw new AuthenticationException("Not logged in");
        logoutIfLoggedIn();
    }

    /**
     * @return true when there is a user with the given address on this machine
     */
    public boolean knows(Address address) {
        return users.stream().map(User::getAddress).anyMatch(a -> a.equals(address));
    }

    public void logoutIfLoggedIn() {
        if (isLoggedIn()) {
            LOG.info("Logging out " + loggedInUser.get());
            loggedInUser.remove();
        }
    }

    public Collection<User> getUsers() {
        return users;
    }
}