Search in sources :

Example 6 with OLATAuthManager

use of org.olat.login.auth.OLATAuthManager 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 7 with OLATAuthManager

use of org.olat.login.auth.OLATAuthManager in project openolat by klemens.

the class UserAuthenticationWebService method changePassword.

/**
 * Change the password of a user.
 *
 * @response.representation.200.doc The password successfully changed
 * @response.representation.304.doc The password was not changed
 * @response.representation.401.doc The roles of the authenticated user are not sufficient
 * @response.representation.404.doc The identity or the authentication not found
 * @param username The username of the user to change the password
 * @param newPassword The new password
 * @param request The HTTP request
 * @return <code>Response</code> object. The operation status (success or fail)
 */
@POST
@Path("password")
public Response changePassword(@PathParam("username") String username, @FormParam("newPassword") String newPassword, @Context HttpServletRequest request) {
    if (!isAdmin(request)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }
    Identity doer = getIdentity(request);
    if (doer == null) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }
    BaseSecurity baseSecurity = BaseSecurityManager.getInstance();
    Identity identity = baseSecurity.findIdentityByName(username);
    if (identity == null) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    }
    OLATAuthManager authManager = CoreSpringFactory.getImpl(OLATAuthManager.class);
    boolean ok = authManager.changePassword(doer, identity, newPassword);
    return (ok ? Response.ok() : Response.notModified()).build();
}
Also used : OLATAuthManager(org.olat.login.auth.OLATAuthManager) RestSecurityHelper.getIdentity(org.olat.restapi.security.RestSecurityHelper.getIdentity) Identity(org.olat.core.id.Identity) BaseSecurity(org.olat.basesecurity.BaseSecurity) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 8 with OLATAuthManager

use of org.olat.login.auth.OLATAuthManager 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);
        }
    }
}
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)

Aggregations

Identity (org.olat.core.id.Identity)8 OLATAuthManager (org.olat.login.auth.OLATAuthManager)8 UserRequest (org.olat.core.gui.UserRequest)6 UserRequestImpl (org.olat.core.gui.UserRequestImpl)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 StringTokenizer (java.util.StringTokenizer)2 POST (javax.ws.rs.POST)2 Path (javax.ws.rs.Path)2 BaseSecurity (org.olat.basesecurity.BaseSecurity)2 ChiefController (org.olat.core.gui.control.ChiefController)2 UserSession (org.olat.core.util.UserSession)2 RestSecurityHelper.getIdentity (org.olat.restapi.security.RestSecurityHelper.getIdentity)2