Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package davidhorak.authentication;
- import davidhorak.Config;
- import java.io.*;
- import java.util.ArrayList;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- /**
- * Trida pro prihlasovani uzivatele
- */
- public class Authenticator {
- private static ThreadLocal<Authenticator> instance = new ThreadLocal<>();
- public static Authenticator getInstance() {
- if(instance.get() == null){
- instance.set(new Authenticator());
- }
- return instance.get();
- }
- private String USER_FILE_URL = Config.getInstance().getUserFileUrl();
- private ArrayList<User> users = new ArrayList<>();
- private User currentUser = null;
- /**
- * Vrati aktualne prihlaseneho uzivatele
- */
- public User getCurrentUser() {
- return currentUser;
- }
- private Authenticator(){ }
- /**
- * Nacte uzivatele ze souboru
- * @throws IOException
- */
- public void load() throws IOException {
- FileInputStream file = new FileInputStream(USER_FILE_URL);
- BufferedReader reader = new BufferedReader(new InputStreamReader(file));
- String line;
- while((line = reader.readLine()) != null){
- Pattern p = Pattern.compile("^(\\w+):(\\w+)$");
- Matcher matcher = p.matcher(line);
- if(matcher.find()){
- String name = matcher.group(1);
- String password = matcher.group(2);
- users.add(new User(name, password));
- }
- }
- reader.close();
- file.close();
- }
- /**
- * Zapta se uzivatele na jmeno a heslo.
- * Pokud se data shoduji prihlasi uzivatele, pokud ne zeptase uzivatele znovu
- * @param inputStream InputStream ze socketu pro pro komunikaci s klientem
- * @param outputStream OutputStream ze socketu pro pro komunikaci s klientem
- * @throws IOException
- */
- public void authenticate(InputStream inputStream, OutputStream outputStream) throws IOException{
- PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream), true);
- BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
- while(currentUser == null){
- writer.println("Jmeno: ");
- String name = reader.readLine();
- writer.println("Heslo: ");
- String password = reader.readLine();
- for(User user : users){
- if(user.match(name, password)){
- currentUser = user;
- writer.println("Uspesne prihlasen");
- return;
- }
- }
- writer.println("Nespravne jmeno nebo heslo");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement