001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2024 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.webconsole.rbac;
020
021import java.util.stream.Collectors;
022import org.jgrapes.core.Channel;
023import org.jgrapes.core.Component;
024import org.jgrapes.core.annotation.Handler;
025import org.jgrapes.webconsole.base.ConsoleRole;
026import org.jgrapes.webconsole.base.ConsoleUser;
027import org.jgrapes.webconsole.base.events.UserAuthenticated;
028import org.jgrapes.webconsole.base.events.UserLoggedOut;
029
030/**
031 * A component that writes user authentication and log out events to the log.
032 */
033public class UserLogger extends Component {
034
035    /**
036     * Instantiates a new user logger.
037     *
038     * @param componentChannel the component channel
039     */
040    public UserLogger(Channel componentChannel) {
041        super(componentChannel);
042    }
043
044    /**
045     * User authenticated.
046     *
047     * @param event the event
048     */
049    @Handler
050    public void userAuthenticated(UserAuthenticated event) {
051        var user = event.subject().getPrincipals(ConsoleUser.class).stream()
052            .findFirst().map(ConsoleUser::toString).orElse("(no user)");
053        var roles = event.subject().getPrincipals(ConsoleRole.class).stream()
054            .map(ConsoleRole::toString).collect(Collectors.joining(", "));
055        logger.info(() -> "User " + user + " authenticated with roles " + roles
056            + " by " + event.by().stream().collect(Collectors.joining(", ")));
057    }
058
059    /**
060     * User logged out.
061     *
062     * @param event the event
063     */
064    @Handler
065    public void userLoggedOut(UserLoggedOut event) {
066        var user = event.subject().getPrincipals(ConsoleUser.class).stream()
067            .findFirst().map(ConsoleUser::toString).orElse("(no user)");
068        logger.info(() -> "User " + user + " logged out");
069    }
070
071}