package nuclibook.entity_utils;

import com.j256.ormlite.support.ConnectionSource;
import nuclibook.constants.P;
import nuclibook.models.CannotHashPasswordException;
import nuclibook.models.Staff;
import nuclibook.server.SqlServerConnection;
import spark.Response;
import spark.Session;

public class SecurityUtils {

	private SecurityUtils() {
		// prevent instantiation
	}

	private static void setUser(Session session, Staff user) {
		session.attribute("user", user);
	}

	private static Staff getUser(Session session) {
		return session.attribute("user");
	}

	public static Staff attemptLogin(Session session, String username, String password) {
		// set up server connection
		ConnectionSource conn = SqlServerConnection.acquireConnection();
		if (conn != null) {
			try {
				// search for user
				Staff staff = StaffUtils.getStaffByUsername(username);
				if (staff != null) {
					// check their password
					if (staff.checkPassword(password)) {
						// correct login!
						setUser(session, staff);
						return staff;
					}
				}
			} catch (CannotHashPasswordException e) {
				// fail
			}
		}
		return null;
	}

	public static boolean checkLoggedIn(Session session) {
		return getUser(session) != null;
	}

	public static void destroyLogin(Session session) {
		session.invalidate();
	}

	public static Staff getCurrentUser(Session session) {
		return getUser(session);
	}

	public static boolean requirePermission(Staff user, P p, Response response) {
		if (user == null || !user.hasPermission(p)) {
			try {
				response.redirect("/access-denied");
			} catch (IllegalStateException e) {
				// already redirecting
			}
			return false;
		}
		return true;
	}

	public static String validateNewPassword(Staff user, String password) throws CannotHashPasswordException {
		if (password.length() < 6) {
			return "Password must be at least 6 characters long.";
		} else if (user.isInLastPasswords(password)) {
			return "Password must not be the same as the last few passwords.";
		}

		return null;
	}

}

@@ -76,16 +76,46 @@
 Source;%0A
+import nuclibook.constants.C;%0A
 import n
@@ -976,24 +976,25 @@
 assword)) %7B%0A
+%0A
 %09%09%09%09%09%09// cor
@@ -1036,16 +1036,103 @@
 staff);%0A
+%0A%09%09%09%09%09%09// set session timeout%0A%09%09%09%09%09%09session.maxInactiveInterval(C.AUTOMATIC_TIMEOUT);%0A%0A
 %09%09%09%09%09%09re

Add backend timeout