Newer
Older
CactusServer / src / main / java / cactusServer / models / Accounts.java
y-ota on 24 May 2018 2 KB Accounts修正
package cactusServer.models;

import javax.inject.Singleton;

import cactusServer.entities.*;
import cactusServer.utils.RandomStringGenerator;

import java.net.URI;
import java.util.*;

@Singleton
public class Accounts {
	private static Accounts theInstance = null;
	private ArrayList<Account> accounts = new ArrayList<>(10000);
	private HashSet<String> userIDSet = new HashSet<>(10000);
	private HashSet<String> uniqueIDSet = new HashSet<>(10000);
	private Session session;

	private Accounts() {

	}

	public static Accounts getInstance() {
		if (theInstance == null) {
			theInstance = new Accounts();
		}
		return theInstance;
	}

	public Session createAcount(String userID, String userName, String userPass) {
		if (!userIDSet.add(userID))
			return null;
		String uniqueID = RandomStringGenerator.generateUniqueString(12, RandomStringGenerator.ALPHA_NUMERIC,
				uniqueIDSet);
		uniqueIDSet.add(uniqueID);
		Account newAccount = new Account(userID, userName, userPass, uniqueID);
		accounts.add(newAccount);
		session = new Session(newAccount, URI.create("/CactusServer/rest/accounts/" + uniqueID));

		return session;
	}

	public Account getAccountToken(String token) {
		Account editAccount;
		for (int i = 0; i < accounts.size(); i++) {
			editAccount = accounts.get(i);
			if (editAccount.getToken().equals(token)) {
				return editAccount;
			}
		}
		return null;
	}

	public Account getAccountByID(String userID) {
		Account editAccount;
		for (int i = 0; i < accounts.size(); i++) {
			editAccount = accounts.get(i);
			if (editAccount.getId().equals(userID)) {
				return editAccount;
			}
		}
		return null;
	}

	public Account getAccountByName(String userName) {
		Account editAccount;
		for (int i = 0; i < accounts.size(); i++) {
			editAccount = accounts.get(i);
			if (editAccount.getName().equals(userName)) {
				return editAccount;
			}
		}
		return null;
	}

	public Account getAccountByuniqueID(String uniqueID) {
		Account editAccount;
		for (int i = 0; i < accounts.size(); i++) {
			editAccount = accounts.get(i);
			if (editAccount.getUniqueID().equals(uniqueID)) {
				return editAccount;
			}
		}
		return null;
	}

	public Session loginAccount(String userID, String userPass) {
		if (getAccountByID(userID).getPass().equals(userPass)) {
			Accounts.getInstance().getAccountByID(userID).setLogin(true);
			Accounts.getInstance().getAccountByID(userID).formToken();
			session = new Session(Accounts.getInstance().getAccountByID(userID), URI.create(
					"/CactusServer/rest/accounts/" + Accounts.getInstance().getAccountByID(userID).getUniqueID()));
			return session;
		} else {
			return null;
		}
	}

	public String logoutAccount(String token) {
		Accounts.getInstance().getAccountToken(token).setLogin(false);
		return "";
	}

}