use of org.olat.core.gui.UserRequestImpl in project openolat by klemens.
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 klemens.
the class ShibbolethDispatcher method handleException.
/**
* It first tries to catch the frequent SAMLExceptions and to ask the user to login again.
* It basically lets the user to login again without getting a RedScreen if one of the most
* frequent shibboleth error occurs. Else a RedScreen is the last option.
* @param e
* @param req
* @param resp
*/
private void handleException(Throwable e, HttpServletRequest req, HttpServletResponse resp, Translator transl) {
UserRequest ureq = new UserRequestImpl(ShibbolethDispatcher.PATH_SHIBBOLETH, req, resp);
if (e instanceof ShibbolethException) {
String userMsg = "";
int errorCode = ((ShibbolethException) e).getErrorCode();
switch(errorCode) {
case ShibbolethException.GENERAL_SAML_ERROR:
userMsg = transl.translate("error.shibboleth.generic");
break;
case ShibbolethException.UNIQUE_ID_NOT_FOUND:
userMsg = transl.translate("error.unqueid.notfound");
break;
default:
userMsg = transl.translate("error.shibboleth.generic");
break;
}
showMessage(ureq, "org.opensaml.SAMLException: " + e.getMessage(), e, userMsg, ((ShibbolethException) e).getContactPersonEmail());
return;
} else {
try {
ChiefController msgcc = MsgFactory.createMessageChiefController(ureq, new OLATRuntimeException("Error processing Shibboleth request: " + e.getMessage(), e), false);
msgcc.getWindow().dispatchRequest(ureq, true);
} catch (Throwable t) {
log.error("We're fucked up....", t);
}
}
}
use of org.olat.core.gui.UserRequestImpl in project openolat by klemens.
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);
}
}
}
}
}
use of org.olat.core.gui.UserRequestImpl in project openolat by klemens.
the class RemoteLoginformDispatcher method execute.
/**
* Tries to login the user with the parameters from the POST request and
* redirects to the home screen in case of success. In case of failure,
* redirects to the login screen.
*
* @param request
* @param response
* @param uriPrefix
*/
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
UserRequest ureq = null;
try {
String uriPrefix = DispatcherModule.getLegacyUriPrefix(request);
ureq = new UserRequestImpl(uriPrefix, request, response);
if (!request.getMethod().equals(METHOD_POST)) {
log.warn("Wrong HTTP method, only POST allowed, but current method::" + request.getMethod());
DispatcherModule.redirectToDefaultDispatcher(response);
return;
}
String userName = ureq.getParameter(PARAM_USERNAME);
if (!StringHelper.containsNonWhitespace(userName)) {
log.warn("Missing username parameter, use '" + PARAM_USERNAME + "' to submit the login name");
DispatcherModule.redirectToDefaultDispatcher(response);
return;
}
String pwd = ureq.getParameter(PARAM_PASSWORD);
if (!StringHelper.containsNonWhitespace(pwd)) {
log.warn("Missing password parameter, use '" + PARAM_PASSWORD + "' to submit the password");
DispatcherModule.redirectToDefaultDispatcher(response);
return;
}
// Authenticate user
OLATAuthManager olatAuthenticationSpi = CoreSpringFactory.getImpl(OLATAuthManager.class);
Identity identity = olatAuthenticationSpi.authenticate(null, userName, pwd);
if (identity == null) {
log.info("Could not authenticate user '" + userName + "', wrong password or user name");
// redirect to OLAT loginscreen, add error parameter so that the loginform can mark itself as errorfull
String loginUrl = WebappHelper.getServletContextPath() + DispatcherModule.getPathDefault() + "?" + OLATAuthenticationController.PARAM_LOGINERROR + "=true";
DispatcherModule.redirectTo(response, loginUrl);
return;
}
UserSession usess = ureq.getUserSession();
// re-init the activity logger to pass the user session and identity
ThreadLocalUserActivityLoggerInstaller.initUserActivityLogger(request);
// sync over the UserSession Instance to prevent double logins
synchronized (usess) {
// Login user, set up everything
int loginStatus = AuthHelper.doLogin(identity, BaseSecurityModule.getDefaultAuthProviderIdentifier(), ureq);
if (loginStatus == AuthHelper.LOGIN_OK) {
// redirect to authenticated environment
UserDeletionManager.getInstance().setIdentityAsActiv(identity);
final String origUri = request.getRequestURI();
String restPart = origUri.substring(uriPrefix.length());
if (request.getParameter("redirect") != null) {
// redirect parameter like: /olat/url/RepositoryEntry/917504/CourseNode/81254724902921
String redirect = request.getParameter("redirect");
DispatcherModule.redirectTo(response, redirect);
} else if (StringHelper.containsNonWhitespace(restPart)) {
// redirect like: http://www.frentix.com/olat/remotelogin/RepositoryEntry/917504/CourseNode/81254724902921
try {
restPart = URLDecoder.decode(restPart, "UTF8");
} catch (UnsupportedEncodingException e) {
log.error("Unsupported encoding", e);
}
String[] split = restPart.split("/");
assert (split.length % 2 == 0);
String businessPath = "";
for (int i = 0; i < split.length; i = i + 2) {
String key = split[i];
if (key != null && key.startsWith("path=")) {
key = key.replace("~~", "/");
}
String value = split[i + 1];
businessPath += "[" + key + ":" + value + "]";
}
// UserSession usess = UserSession.getUserSession(request);
usess.putEntryInNonClearedStore(AuthenticatedDispatcher.AUTHDISPATCHER_BUSINESSPATH, businessPath);
String url = getRedirectToURL(usess);
DispatcherModule.redirectTo(response, url);
} else {
// redirect
ServletUtil.serveResource(request, response, ureq.getDispatchResult().getResultingMediaResource());
}
} else if (loginStatus == AuthHelper.LOGIN_NOTAVAILABLE) {
DispatcherModule.redirectToServiceNotAvailable(response);
} else {
// error, redirect to login screen
DispatcherModule.redirectToDefaultDispatcher(response);
}
}
} 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("Sorry, can't handle this remote login request....", t);
}
}
}
use of org.olat.core.gui.UserRequestImpl in project openolat by klemens.
the class OAuthDispatcher method execute.
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uri = request.getRequestURI();
try {
uri = URLDecoder.decode(uri, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AssertException("UTF-8 encoding not supported!!!!");
}
String uriPrefix = DispatcherModule.getLegacyUriPrefix(request);
uri = uri.substring(uriPrefix.length());
UserRequest ureq = null;
try {
// upon creation URL is checked for
ureq = new UserRequestImpl(uriPrefix, request, response);
} catch (NumberFormatException nfe) {
if (log.isDebug()) {
log.debug("Bad Request " + request.getPathInfo());
}
DispatcherModule.sendBadRequest(request.getPathInfo(), response);
return;
}
String error = request.getParameter("error");
if (null != error) {
error(ureq, translateOauthError(ureq, error));
return;
}
String problem = request.getParameter("oauth_problem");
if (problem != null && "token_rejected".equals(problem.trim())) {
error(ureq, translateOauthError(ureq, error));
return;
}
try {
HttpSession sess = request.getSession();
// OAuth 2.0 hasn't any request token
Token requestToken = (Token) sess.getAttribute(OAuthConstants.REQUEST_TOKEN);
OAuthService service = (OAuthService) sess.getAttribute(OAuthConstants.OAUTH_SERVICE);
OAuthSPI provider = (OAuthSPI) sess.getAttribute(OAuthConstants.OAUTH_SPI);
Token accessToken;
if (provider == null) {
log.audit("OAuth Login failed, no provider in request");
DispatcherModule.redirectToDefaultDispatcher(response);
return;
} else if (provider.isImplicitWorkflow()) {
String idToken = ureq.getParameter("id_token");
if (idToken == null) {
redirectImplicitWorkflow(ureq);
return;
} else {
Verifier verifier = OpenIDVerifier.create(ureq, sess);
accessToken = service.getAccessToken(requestToken, verifier);
}
} else {
String requestVerifier = request.getParameter("oauth_verifier");
if (requestVerifier == null) {
// OAuth 2.0 as a code
requestVerifier = request.getParameter("code");
}
accessToken = service.getAccessToken(requestToken, new Verifier(requestVerifier));
}
OAuthUser infos = provider.getUser(service, accessToken);
if (infos == null || !StringHelper.containsNonWhitespace(infos.getId())) {
error(ureq, translate(ureq, "error.no.id"));
log.error("OAuth Login failed, no infos extracted from access token: " + accessToken);
return;
}
OAuthRegistration registration = new OAuthRegistration(provider.getProviderName(), infos);
login(infos, registration);
if (provider instanceof OAuthUserCreator) {
Identity newIdentity;
OAuthUserCreator userCreator = (OAuthUserCreator) provider;
if (registration.getIdentity() == null) {
newIdentity = userCreator.createUser(infos);
} else {
newIdentity = userCreator.updateUser(infos, registration.getIdentity());
}
if (newIdentity != null) {
registration.setIdentity(newIdentity);
}
}
if (registration.getIdentity() == null) {
if (CoreSpringFactory.getImpl(OAuthLoginModule.class).isAllowUserCreation()) {
register(request, response, registration);
} else {
error(ureq, translate(ureq, "error.account.creation"));
log.error("OAuth Login ok but the user has not an account on OpenOLAT: " + infos);
}
} else {
if (ureq.getUserSession() != null) {
// re-init the activity logger
ThreadLocalUserActivityLoggerInstaller.initUserActivityLogger(request);
}
Identity identity = registration.getIdentity();
int loginStatus = AuthHelper.doLogin(identity, provider.getProviderName(), ureq);
if (loginStatus != AuthHelper.LOGIN_OK) {
if (loginStatus == AuthHelper.LOGIN_NOTAVAILABLE) {
DispatcherModule.redirectToServiceNotAvailable(response);
} else {
// error, redirect to login screen
DispatcherModule.redirectToDefaultDispatcher(response);
}
} else {
// update last login date and register active user
UserDeletionManager.getInstance().setIdentityAsActiv(identity);
MediaResource mr = ureq.getDispatchResult().getResultingMediaResource();
if (mr instanceof RedirectMediaResource) {
RedirectMediaResource rmr = (RedirectMediaResource) mr;
rmr.prepare(response);
} else {
// error, redirect to login screen
DispatcherModule.redirectToDefaultDispatcher(response);
}
}
}
} catch (Exception e) {
log.error("Unexpected error", e);
error(ureq, translate(ureq, "error.generic"));
}
}
Aggregations