use of org.olat.core.gui.UserRequestImpl in project OpenOLAT by OpenOLAT.
the class RestApiLoginFilter method upgradeIpAuthentication.
private void upgradeIpAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
UserSessionManager sessionManager = CoreSpringFactory.getImpl(UserSessionManager.class);
UserSession usess = sessionManager.getUserSessionIfAlreadySet(request);
if (usess == null) {
usess = sessionManager.getUserSession(request.getSession(true));
}
if (usess.getIdentity() == null) {
usess.setRoles(new Roles(false, false, false, false, false, false, false));
String remoteAddr = request.getRemoteAddr();
SessionInfo sinfo = new SessionInfo(new Long(-1), "REST", request.getSession());
sinfo.setFirstname("REST");
sinfo.setLastname(remoteAddr);
sinfo.setFromIP(remoteAddr);
sinfo.setFromFQN(remoteAddr);
try {
InetAddress[] iaddr = InetAddress.getAllByName(request.getRemoteAddr());
if (iaddr.length > 0)
sinfo.setFromFQN(iaddr[0].getHostName());
} catch (UnknownHostException e) {
// ok, already set IP as FQDN
}
sinfo.setAuthProvider("IP");
sinfo.setUserAgent(request.getHeader("User-Agent"));
sinfo.setSecure(request.isSecure());
sinfo.setREST(true);
sinfo.setWebModeFromUreq(null);
// set session info for this session
usess.setSessionInfo(sinfo);
}
UserRequest ureq = null;
try {
// upon creation URL is checked for
String requestURI = request.getRequestURI();
ureq = new UserRequestImpl(requestURI, request, response);
ureq.getUserSession().putEntryInNonClearedStore(RestSecurityHelper.SYSTEM_MARKER, Boolean.TRUE);
} catch (NumberFormatException nfe) {
response.sendError(401);
return;
}
request.setAttribute(RestSecurityHelper.SEC_USER_REQUEST, ureq);
}
use of org.olat.core.gui.UserRequestImpl in project OpenOLAT by OpenOLAT.
the class RestApiLoginFilter method followToken.
private void followToken(String token, HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpSession session = request.getSession(true);
session.setMaxInactiveInterval(TOKEN_BASED_SESSION_TIMEOUT);
UserSession uress = CoreSpringFactory.getImpl(UserSessionManager.class).getUserSession(session);
if (uress != null) {
UserRequest ureq = null;
try {
// upon creation URL is checked for
String requestURI = request.getRequestURI();
ureq = new UserRequestImpl(requestURI, request, response);
} catch (Exception e) {
response.sendError(500);
return;
}
request.setAttribute(RestSecurityHelper.SEC_USER_REQUEST, ureq);
RestSecurityBean securityBean = (RestSecurityBean) CoreSpringFactory.getBean(RestSecurityBean.class);
Identity identity = securityBean.getIdentity(token);
int loginStatus = AuthHelper.doHeadlessLogin(identity, BaseSecurityModule.getDefaultAuthProviderIdentifier(), ureq, true);
if (loginStatus == AuthHelper.LOGIN_OK) {
String renewedToken = securityBean.renewToken(token);
if (renewedToken != null) {
response.setHeader(RestSecurityHelper.SEC_TOKEN, renewedToken);
synchronized (uress) {
chain.doFilter(request, response);
}
} else
response.sendError(401);
} else
response.sendError(401);
} else
response.sendError(401);
}
use of org.olat.core.gui.UserRequestImpl in project OpenOLAT by OpenOLAT.
the class ShibbolethDispatcher method execute.
/**
* Main method called by OpenOLATServlet.
* This processess all shibboleth requests.
*
* @param req
* @param resp
* @param uriPrefix
*/
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) {
if (translator == null) {
translator = Util.createPackageTranslator(ShibbolethDispatcher.class, I18nModule.getDefaultLocale());
}
if (!shibbolethModule.isEnableShibbolethLogins()) {
throw new OLATSecurityException("Got shibboleth request but shibboleth is not enabled");
}
String uriPrefix = DispatcherModule.getLegacyUriPrefix(req);
Map<String, String> attributesMap = getShibbolethAttributesFromRequest(req);
ShibbolethAttributes shibbolethAttriutes = CoreSpringFactory.getImpl(ShibbolethAttributes.class);
shibbolethAttriutes.init(attributesMap);
String uid = shibbolethAttriutes.getUID();
if (uid == null) {
handleException(new ShibbolethException(ShibbolethException.UNIQUE_ID_NOT_FOUND, "Unable to get unique identifier for subject. Make sure you are listed in the metadata.xml file and your resources your are trying to access are available and your are allowed to see them. (Resourceregistry). "), req, resp, translator);
return;
}
if (!authorization(req, resp, shibbolethAttriutes)) {
return;
}
UserRequest ureq = null;
try {
// upon creation URL is checked for
ureq = new UserRequestImpl(uriPrefix, req, resp);
} catch (NumberFormatException nfe) {
// a 404 message must be shown -> e.g. robots correct their links.
if (log.isDebug()) {
log.debug("Bad Request " + req.getPathInfo());
}
DispatcherModule.sendBadRequest(req.getPathInfo(), resp);
return;
}
Authentication auth = securityManager.findAuthenticationByAuthusername(uid, PROVIDER_SHIB);
if (auth == null) {
// no matching authentication...
ShibbolethRegistrationController.putShibAttributes(req, shibbolethAttriutes);
ShibbolethRegistrationController.putShibUniqueID(req, uid);
redirectToShibbolethRegistration(resp);
return;
}
if (ureq.getUserSession() != null) {
// re-init the activity logger
ThreadLocalUserActivityLoggerInstaller.initUserActivityLogger(req);
}
int loginStatus = AuthHelper.doLogin(auth.getIdentity(), ShibbolethDispatcher.PROVIDER_SHIB, ureq);
if (loginStatus != AuthHelper.LOGIN_OK) {
if (loginStatus == AuthHelper.LOGIN_NOTAVAILABLE) {
DispatcherModule.redirectToServiceNotAvailable(resp);
} else {
// error, redirect to login screen
DispatcherModule.redirectToDefaultDispatcher(resp);
}
return;
}
// Successful login
Identity authenticationedIdentity = ureq.getIdentity();
userDeletionManager.setIdentityAsActiv(authenticationedIdentity);
shibbolethManager.syncUser(authenticationedIdentity, shibbolethAttriutes);
ureq.getUserSession().getIdentityEnvironment().addAttributes(shibbolethModule.getAttributeTranslator().translateAttributesMap(shibbolethAttriutes.toMap()));
MediaResource mr = ureq.getDispatchResult().getResultingMediaResource();
if (mr instanceof RedirectMediaResource) {
RedirectMediaResource rmr = (RedirectMediaResource) mr;
rmr.prepare(resp);
} else {
// error, redirect to login screen
DispatcherModule.redirectToDefaultDispatcher(resp);
}
}
use of org.olat.core.gui.UserRequestImpl in project OpenOLAT by OpenOLAT.
the class DMZDispatcher method execute.
/**
* Main method called by OpenOLATServlet. This processess all requests for
* users who are not authenticated.
*
* @param request
* @param response
* @param uriPrefix
*/
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
if (rejectRequest(request, response)) {
return;
}
UserRequest ureq = null;
String uriPrefix = DispatcherModule.getLegacyUriPrefix(request);
try {
// upon creation URL is checked for
ureq = new UserRequestImpl(uriPrefix, request, response);
} catch (NumberFormatException nfe) {
// a 404 message must be shown -> e.g. robots correct their links.
if (log.isDebug()) {
log.debug("Bad Request " + request.getPathInfo());
}
DispatcherModule.sendBadRequest(request.getPathInfo(), response);
return;
}
try {
// find out about which subdispatcher is meant
// e.g. got here because of /dmz/...
// maybe something like /dmz/registration/
//
// add the context path to align with uriPrefix e.g. /olat/dmz/
String pathInfo = request.getContextPath() + request.getPathInfo();
ChiefControllerCreator subPathccc = null;
// if /olat/dmz/
boolean dmzOnly = pathInfo.equals(uriPrefix);
if (!dmzOnly) {
int sl = pathInfo.indexOf('/', uriPrefix.length());
String sub;
if (sl > 1) {
// e.g. something like /registration/ or /pwchange/
sub = pathInfo.substring(uriPrefix.length() - 1, sl + 1);
} else {
// e.g. something like /info.html from (/dmz/info.html)
sub = pathInfo;
}
// chief controller creator for sub path, e.g.
subPathccc = dmzServicesByPath.get(sub);
if (subPathccc != null) {
UserSession usess = ureq.getUserSession();
Windows ws = Windows.getWindows(usess);
synchronized (ws) {
// o_clusterOK by:fj per user session
ChiefController occ = subPathccc.createChiefController(ureq);
Window window = occ.getWindow();
window.setUriPrefix(uriPrefix);
ws.registerWindow(window);
window.dispatchRequest(ureq, true);
return;
}
}
}
// else a /olat/dmz/ request
UserSession usess = ureq.getUserSession();
Windows ws = Windows.getWindows(usess);
// and make it useless under heavily load or 2 concurrent requests
synchronized (usess) {
// o_clusterOK by:fj per user session
Window window;
boolean windowHere = ws.isExisting(uriPrefix, ureq.getWindowID());
boolean validDispatchUri = ureq.isValidDispatchURI();
if (validDispatchUri && !windowHere) {
// probably valid framework link from previous user && new Session(no window):
// when a previous user logged off, and 30min later (when the httpsession is invalidated), the next user clicks e.g. on
// the log-in link in the -same- browser window ->
// -> there is no window -> create a new one
window = null;
CoreSpringFactory.getImpl(UserSessionManager.class).signOffAndClear(usess);
usess.setLocale(LocaleNegotiator.getPreferedLocale(ureq));
// update locale infos
I18nManager.updateLocaleInfoToThread(usess);
// request new windows since it is a new usersession, the old one was purged
ws = Windows.getWindows(usess);
} else if (validDispatchUri) {
window = ws.getWindow(ureq);
} else if (dmzOnly) {
// e.g. /dmz/ -> start screen, clear previous session data
window = null;
CoreSpringFactory.getImpl(UserSessionManager.class).signOffAndClear(usess);
usess.setLocale(LocaleNegotiator.getPreferedLocale(ureq));
// update locale infos
I18nManager.updateLocaleInfoToThread(usess);
OAuthLoginModule oauthModule = CoreSpringFactory.getImpl(OAuthLoginModule.class);
if (canRedirectConfigurableOAuth(request, response, oauthModule)) {
return;
} else if (canRedirectOAuth(request, oauthModule)) {
OAuthSPI oauthSpi = oauthModule.getRootProvider();
HttpSession session = request.getSession();
OAuthResource.redirect(oauthSpi, response, session);
return;
}
// request new windows since it is a new usersession, the old one was purged
ws = Windows.getWindows(usess);
} else {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
if (window == null) {
// no window found, -> start a new WorkFlow/Controller and obtain the window
// main controller which also implements the windowcontroller for pagestatus and modal dialogs
Object wSettings = usess.getEntry(WINDOW_SETTINGS);
ChiefController occ = chiefControllerCreator.createChiefController(ureq);
window = occ.getWindow();
window.setUriPrefix(uriPrefix);
ws.registerWindow(window);
String businessPath = (String) usess.removeEntryFromNonClearedStore(DMZDISPATCHER_BUSINESSPATH);
if (businessPath != null) {
List<ContextEntry> ces = BusinessControlFactory.getInstance().createCEListFromString(businessPath);
window.getDTabs().activate(ureq, null, ces);
}
// apply the settings forward
usess.putEntryInNonClearedStore(WINDOW_SETTINGS, wSettings);
}
window.dispatchRequest(ureq);
}
} catch (InvalidRequestParameterException e) {
try {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
} catch (IOException e1) {
log.error("An exception occured while handling the invalid request parameter exception...", e1);
}
} catch (Throwable th) {
try {
ChiefController msgcc = MsgFactory.createMessageChiefController(ureq, th);
// the controller's window must be failsafe also
msgcc.getWindow().dispatchRequest(ureq, true);
// do not dispatch (render only), since this is a new Window created as
// a result of another window's click.
} catch (Throwable t) {
log.error("An exception occured while handling the exception...", t);
}
}
}
use of org.olat.core.gui.UserRequestImpl in project OpenOLAT by OpenOLAT.
the class RESTDispatcher method execute.
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
//
// create a ContextEntries String which can be used to create a BusinessControl -> move to
//
String uriPrefix = DispatcherModule.getLegacyUriPrefix(request);
final String origUri = request.getRequestURI();
String encodedRestPart = origUri.substring(uriPrefix.length());
String restPart = encodedRestPart;
try {
restPart = URLDecoder.decode(encodedRestPart, "UTF8");
} catch (UnsupportedEncodingException e) {
log.error("Unsupported encoding", e);
}
String[] split = restPart.split("/");
if (split.length % 2 != 0) {
// assert(split.length % 2 == 0);
// The URL is not a valid business path
DispatcherModule.sendBadRequest(origUri, response);
log.warn("URL is not valid: " + restPart);
return;
}
String businessPath = BusinessControlFactory.getInstance().formatFromSplittedURI(split);
if (log.isDebug()) {
log.debug("REQUEST URI: " + origUri);
log.debug("REQUEST PREFIX " + restPart);
log.debug("calc buspath " + businessPath);
}
// check if the businesspath is valid
try {
BusinessControl bc = BusinessControlFactory.getInstance().createFromString(businessPath);
if (!bc.hasContextEntry()) {
// The URL is not a valid business path
DispatcherModule.sendBadRequest(origUri, response);
return;
}
} catch (Exception e) {
DispatcherModule.sendBadRequest(origUri, response);
log.warn("Error with business path: " + origUri, e);
return;
}
//
// create the olat ureq and get an associated main window to spawn the "tab"
//
UserSession usess = CoreSpringFactory.getImpl(UserSessionManager.class).getUserSession(request);
if (usess != null) {
ThreadLocalUserActivityLoggerInstaller.initUserActivityLogger(request);
}
UserRequest ureq = null;
try {
// upon creation URL is checked for
ureq = new UserRequestImpl(uriPrefix, request, response);
} catch (NumberFormatException nfe) {
// a 404 message must be shown -> e.g. robots correct their links.
if (log.isDebug()) {
log.debug("Bad Request " + request.getPathInfo());
}
DispatcherModule.sendBadRequest(request.getPathInfo(), response);
return;
}
// XX:GUIInterna.setLoadPerformanceMode(ureq);
// Do auto-authenticate if url contains a X-OLAT-TOKEN Single-Sign-On REST-Token
String xOlatToken = ureq.getParameter(RestSecurityHelper.SEC_TOKEN);
if (xOlatToken != null) {
// Lookup identity that is associated with this token
RestSecurityBean securityBean = (RestSecurityBean) CoreSpringFactory.getBean(RestSecurityBean.class);
Identity restIdentity = securityBean.getIdentity(xOlatToken);
//
if (log.isDebug()) {
if (restIdentity == null)
log.debug("Found SSO token " + RestSecurityHelper.SEC_TOKEN + " in url, but token is not bound to an identity");
else
log.debug("Found SSO token " + RestSecurityHelper.SEC_TOKEN + " in url which is bound to identity::" + restIdentity.getName());
}
//
if (restIdentity != null) {
// after the REST dispatcher finishes. No need to change it here.
if (!usess.isAuthenticated() || !restIdentity.equalsByPersistableKey(usess.getIdentity())) {
// Re-authenticate user session for this user and start a fresh
// standard OLAT session
int loginStatus = AuthHelper.doLogin(restIdentity, RestSecurityHelper.SEC_TOKEN, ureq);
if (loginStatus == AuthHelper.LOGIN_OK) {
// fxdiff: FXOLAT-268 update last login date and register active user
UserDeletionManager.getInstance().setIdentityAsActiv(restIdentity);
} else {
// error, redirect to login screen
DispatcherModule.redirectToDefaultDispatcher(response);
}
} else if (Windows.getWindows(usess).getChiefController() == null) {
// Session is already available, but no main window (Head-less REST
// session). Only create the base chief controller and the window
Window currentWindow = AuthHelper.createAuthHome(ureq).getWindow();
// the user is authenticated successfully with a security token, we can set the authenticated path
currentWindow.setUriPrefix(WebappHelper.getServletContextPath() + DispatcherModule.PATH_AUTHENTICATED);
Windows ws = Windows.getWindows(ureq);
ws.registerWindow(currentWindow);
// no need to call setIdentityAsActive as this was already done by RestApiLoginFilter...
}
}
}
boolean auth = usess.isAuthenticated();
if (auth) {
if (Windows.getWindows(usess).getChiefController() == null) {
// Session is already available, but no main window (Head-less REST
// session). Only create the base chief controller and the window
setBusinessPathInUserSession(usess, businessPath, ureq.getParameter(WINDOW_SETTINGS));
AuthHelper.createAuthHome(ureq);
String url = getRedirectToURL(usess) + ";jsessionid=" + usess.getSessionInfo().getSession().getId();
DispatcherModule.redirectTo(response, url);
} else {
// redirect to the authenticated dispatcher which support REST url
String url = WebappHelper.getServletContextPath() + DispatcherModule.PATH_AUTHENTICATED + encodedRestPart;
DispatcherModule.redirectTo(response, url);
}
} else {
// prepare for redirect
LoginModule loginModule = CoreSpringFactory.getImpl(LoginModule.class);
setBusinessPathInUserSession(usess, businessPath, ureq.getParameter(WINDOW_SETTINGS));
String invitationAccess = ureq.getParameter(AuthenticatedDispatcher.INVITATION);
if (invitationAccess != null && loginModule.isInvitationEnabled()) {
// try to log in as anonymous
// use the language from the lang paramter if available, otherwhise use the system default locale
Locale guestLoc = getLang(ureq);
int loginStatus = AuthHelper.doInvitationLogin(invitationAccess, ureq, guestLoc);
if (loginStatus == AuthHelper.LOGIN_OK) {
Identity invite = usess.getIdentity();
// fxdiff: FXOLAT-268 update last login date and register active user
UserDeletionManager.getInstance().setIdentityAsActiv(invite);
// logged in as invited user, continue
String url = getRedirectToURL(usess);
DispatcherModule.redirectTo(response, url);
} else if (loginStatus == AuthHelper.LOGIN_NOTAVAILABLE) {
DispatcherModule.redirectToServiceNotAvailable(response);
} else {
// error, redirect to login screen
DispatcherModule.redirectToDefaultDispatcher(response);
}
} else {
String guestAccess = ureq.getParameter(AuthenticatedDispatcher.GUEST);
if (guestAccess == null || !loginModule.isGuestLoginLinksEnabled()) {
DispatcherModule.redirectToDefaultDispatcher(response);
return;
} else if (guestAccess.equals(AuthenticatedDispatcher.TRUE)) {
// try to log in as anonymous
// use the language from the lang paramter if available, otherwhise use the system default locale
Locale guestLoc = getLang(ureq);
int loginStatus = AuthHelper.doAnonymousLogin(ureq, guestLoc);
if (loginStatus == AuthHelper.LOGIN_OK) {
// logged in as anonymous user, continue
String url = getRedirectToURL(usess);
DispatcherModule.redirectTo(response, url);
} else if (loginStatus == AuthHelper.LOGIN_NOTAVAILABLE) {
DispatcherModule.redirectToServiceNotAvailable(response);
} else {
// error, redirect to login screen
DispatcherModule.redirectToDefaultDispatcher(response);
}
}
}
}
}
Aggregations