/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package de.uhilger.httpserver.auth.realm; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * * test=testRolle * ulrich=testRolle,andereRolle * * @author Ulrich Hilger * @version 1, 03.06.2021 */ public class SimpleRealm implements Realm { public static final String LIST_INDICATOR = "="; public static final String ROLE_SEPARATOR = ","; public static final String COMMENT_INDICATOR = "#"; private String name; private Map users; private Map userRoles; public SimpleRealm() { users = new HashMap<>(); userRoles = new HashMap<>(); } public void setName(String name) { this.name = name; } public void readFromFile(File file) throws IOException { BufferedReader r = new BufferedReader(new FileReader(file)); String line = r.readLine(); while(line != null) { parse(line); line = r.readLine(); } r.close(); } private void parse(String line) { if(!line.startsWith(COMMENT_INDICATOR)) { String[] teile = line.split(LIST_INDICATOR); String[] rollen = teile[1].split(ROLE_SEPARATOR); String userId = teile[0]; User user = new User(); user.setName(userId); user.setPassword(rollen[0]); ArrayList rollenListe = new ArrayList(); for(int i = 1; i < rollen.length; i++) { rollenListe.add(rollen[i]); } users.put(userId, user); userRoles.put(userId, rollenListe); } } /* ------------ Realm implementation -------------- */ @Override public boolean isValid(String userId, String kennwort) { Object o = users.get(userId); if(o instanceof User) { User user = (User) o; return user.getPassword().equals(kennwort); } else { return false; } } @Override public boolean hasRole(String userId, String rollenId) { Object o = userRoles.get(userId); if(o instanceof List) { List roles = (List) o; return roles.contains(rollenId); } else { return false; } } @Override public String getName() { return name; } }