import logging

from orangescape.model.server.UserAuthentication import UserAuthentication
from orangescape.model.server.util.ServerUtil import _get_class
from appconfig import AUTHENTICATION
from orangescape.model.server.Context import getApplication

def authenticate(controller):
    import urllib
    authInstance = _get_class(AUTHENTICATION)()
    userSurrogateId=authInstance.doPreRequest(controller)
    if userSurrogateId:
        return userSurrogateId;
    else:
        currentUrl=urllib.quote(controller.request.path+"?"+controller.request.query_string)
        if not currentUrl.__contains__('/signin'):
            controller.redirect('/'+getApplication().getSheetId()+'/1/signin?forward='+currentUrl,True)
        else:
            controller.redirect('/'+getApplication().getSheetId()+'/1/signin')

def userLoginAuth(session,emailid):
    userinitialization=UserAuthentication(session,emailid)
    return userinitialization.authenticateUser()