/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;


import models.AppUser;
import play.Logger;
import play.mvc.Before;
import play.mvc.Http;

public class Security extends Secure.Security {

    public static boolean check(String profile) {
        return AppUser.find("byUserName", connected()).<AppUser>first().isAdmin;
        //return false;
    }



    @SuppressWarnings("Contract")
    public static boolean authenticate(String email, String password) {

        //authenticating lowercase email
        email = email.toLowerCase();
        Logger.info("Authenticating appuser");
        String remoteAddress = request.remoteAddress;
        Logger.info("XHeader : " + request.headers.toString());
        Http.Header header = request.headers.get("x-forwarded-for");
        String token = request.params.get("token");
        if (header != null) {
            remoteAddress = header.value();
        }
        Logger.info("Authenticating. Failed count: " + (play.cache.Cache.get("failed:" + remoteAddress) == null ? 0 : play.cache.Cache.get("failed:" + remoteAddress)));
        if (play.cache.Cache.get("failed:" + remoteAddress) != null && (Long) play.cache.Cache.get("failed:" + remoteAddress) > 3) {
            Logger.info("Too many failed logins from " + remoteAddress + ". Waiting for 5 seconds");
            play.cache.Cache.set("failed:" + remoteAddress, (long) 0);
            suspend(5000);
        }
        if (AppUser.connect(email, password)) {
            play.cache.Cache.delete("failed:" + remoteAddress);
            return true;
        } else if (token != null) {
            Logger.info("Token found : " + token);
            return false;
        } else {
            if (play.cache.Cache.get("failed:" + remoteAddress) == null) {
                play.cache.Cache.set("failed:" + remoteAddress, (long) 0);
            }
            play.cache.Cache.incr("failed:" + remoteAddress);
            Logger.info(remoteAddress + " failed logins: " + play.cache.Cache.get("failed:" + remoteAddress));
            return false;
        }

    }

    static void onAuthenticated() {
        AppUser user = AppUser.find("select au from AppUser au where UPPER(au.userName)=:username").setParameter("username", Security.connected().toUpperCase()).first();
        Logger.info("Authenticated : " + user.userName);
        Logger.info("Authenticated : " + user.userName + " on " + request.host);
        Logger.info("onAuthenticated");
        Application.index();


    }

    static void onDisconnected() {
        Application.index();
    }

    public static String connected() {
        return Secure.Security.connected();
    }


}
