Search in sources :

Example 21 with UserRequestImpl

use of org.olat.core.gui.UserRequestImpl in project OpenOLAT by OpenOLAT.

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);
        }
    }
}
Also used : UserSession(org.olat.core.util.UserSession) OLATAuthManager(org.olat.login.auth.OLATAuthManager) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ChiefController(org.olat.core.gui.control.ChiefController) Identity(org.olat.core.id.Identity) UserRequest(org.olat.core.gui.UserRequest) UserRequestImpl(org.olat.core.gui.UserRequestImpl)

Example 22 with UserRequestImpl

use of org.olat.core.gui.UserRequestImpl in project openolat by klemens.

the class RestApiLoginFilter method followSession.

private void followSession(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    UserSession uress = CoreSpringFactory.getImpl(UserSessionManager.class).getUserSessionIfAlreadySet(request);
    if (uress != null && uress.isAuthenticated()) {
        UserRequest ureq = null;
        try {
            // upon creation URL is checked for
            String requestURI = request.getRequestURI();
            ureq = new UserRequestImpl(requestURI, request, response);
        } catch (NumberFormatException nfe) {
            response.sendError(401);
            return;
        }
        request.setAttribute(RestSecurityHelper.SEC_USER_REQUEST, ureq);
        synchronized (uress) {
            chain.doFilter(request, response);
        }
    } else {
        response.sendError(401);
    }
}
Also used : UserSessionManager(org.olat.core.util.session.UserSessionManager) UserSession(org.olat.core.util.UserSession) UserRequest(org.olat.core.gui.UserRequest) UserRequestImpl(org.olat.core.gui.UserRequestImpl)

Example 23 with UserRequestImpl

use of org.olat.core.gui.UserRequestImpl in project openolat by klemens.

the class RestApiLoginFilter method isBasicAuthenticated.

private boolean isBasicAuthenticated(HttpServletRequest request, HttpServletResponse response, String requestURI) {
    String authHeader = request.getHeader("Authorization");
    if (authHeader != null) {
        StringTokenizer st = new StringTokenizer(authHeader);
        if (st.hasMoreTokens()) {
            String basic = st.nextToken();
            // We only handle HTTP Basic authentication
            if (basic.equalsIgnoreCase("Basic")) {
                String credentials = st.nextToken();
                String userPass = StringHelper.decodeBase64(credentials);
                // The decoded string is in the form "userID:password".
                int p = userPass.indexOf(":");
                if (p != -1) {
                    String username = userPass.substring(0, p);
                    String password = userPass.substring(p + 1);
                    OLATAuthManager olatAuthenticationSpi = CoreSpringFactory.getImpl(OLATAuthManager.class);
                    Identity identity = olatAuthenticationSpi.authenticate(null, username, password);
                    if (identity == null) {
                        return false;
                    }
                    UserRequest ureq = null;
                    try {
                        // upon creation URL is checked for
                        ureq = new UserRequestImpl(requestURI, request, response);
                    } catch (NumberFormatException nfe) {
                        return false;
                    }
                    request.setAttribute(RestSecurityHelper.SEC_USER_REQUEST, ureq);
                    int loginStatus = AuthHelper.doHeadlessLogin(identity, BaseSecurityModule.getDefaultAuthProviderIdentifier(), ureq, true);
                    if (loginStatus == AuthHelper.LOGIN_OK) {
                        UserDeletionManager.getInstance().setIdentityAsActiv(identity);
                        // Forge a new security token
                        RestSecurityBean securityBean = CoreSpringFactory.getImpl(RestSecurityBean.class);
                        String token = securityBean.generateToken(identity, request.getSession());
                        response.setHeader(RestSecurityHelper.SEC_TOKEN, token);
                    }
                    return true;
                }
            }
        }
    }
    return false;
}
Also used : StringTokenizer(java.util.StringTokenizer) OLATAuthManager(org.olat.login.auth.OLATAuthManager) Identity(org.olat.core.id.Identity) UserRequest(org.olat.core.gui.UserRequest) UserRequestImpl(org.olat.core.gui.UserRequestImpl)

Example 24 with UserRequestImpl

use of org.olat.core.gui.UserRequestImpl in project openolat by klemens.

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);
}
Also used : UserSessionManager(org.olat.core.util.session.UserSessionManager) UnknownHostException(java.net.UnknownHostException) UserSession(org.olat.core.util.UserSession) SessionInfo(org.olat.core.util.SessionInfo) Roles(org.olat.core.id.Roles) InetAddress(java.net.InetAddress) UserRequest(org.olat.core.gui.UserRequest) UserRequestImpl(org.olat.core.gui.UserRequestImpl)

Example 25 with UserRequestImpl

use of org.olat.core.gui.UserRequestImpl in project openolat by klemens.

the class RestApiLoginFilter method followWithoutAuthentication.

private void followWithoutAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    UserSession uress = CoreSpringFactory.getImpl(UserSessionManager.class).getUserSessionIfAlreadySet(request);
    if (uress != null && uress.isAuthenticated()) {
        // is authenticated by session cookie, follow its current session
        followSession(request, response, chain);
        return;
    }
    String token = request.getHeader(RestSecurityHelper.SEC_TOKEN);
    RestSecurityBean securityBean = (RestSecurityBean) CoreSpringFactory.getBean(RestSecurityBean.class);
    if (StringHelper.containsNonWhitespace(token) && securityBean.isTokenRegistrated(token, request.getSession(true))) {
        // is authenticated by token, follow its current token
        followToken(token, request, response, chain);
        return;
    }
    // fxdiff FXOLAT-113: business path in DMZ
    UserRequest ureq = null;
    try {
        // upon creation URL is checked for
        String requestURI = request.getRequestURI();
        ureq = new UserRequestImpl(requestURI, request, response);
    } catch (NumberFormatException nfe) {
        response.sendError(401);
        return;
    }
    request.setAttribute(RestSecurityHelper.SEC_USER_REQUEST, ureq);
    // no authentication, but no authentication needed, go further
    chain.doFilter(request, response);
}
Also used : UserSessionManager(org.olat.core.util.session.UserSessionManager) UserSession(org.olat.core.util.UserSession) UserRequest(org.olat.core.gui.UserRequest) UserRequestImpl(org.olat.core.gui.UserRequestImpl)

Aggregations

UserRequest (org.olat.core.gui.UserRequest)30 UserRequestImpl (org.olat.core.gui.UserRequestImpl)30 UserSession (org.olat.core.util.UserSession)16 UserSessionManager (org.olat.core.util.session.UserSessionManager)14 Identity (org.olat.core.id.Identity)12 IOException (java.io.IOException)10 ChiefController (org.olat.core.gui.control.ChiefController)10 HttpSession (javax.servlet.http.HttpSession)8 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 UnknownHostException (java.net.UnknownHostException)4 Locale (java.util.Locale)4 ServletException (javax.servlet.ServletException)4 Windows (org.olat.core.gui.Windows)4 Window (org.olat.core.gui.components.Window)4 InvalidRequestParameterException (org.olat.core.gui.components.form.flexible.impl.InvalidRequestParameterException)4 MediaResource (org.olat.core.gui.media.MediaResource)4 RedirectMediaResource (org.olat.core.gui.media.RedirectMediaResource)4 SessionInfo (org.olat.core.util.SessionInfo)4 LoginModule (org.olat.login.LoginModule)4 OLATAuthManager (org.olat.login.auth.OLATAuthManager)4