Search in sources :

Example 36 with AssertException

use of org.olat.core.logging.AssertException in project OpenOLAT by OpenOLAT.

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"));
    }
}
Also used : AssertException(org.olat.core.logging.AssertException) HttpSession(javax.servlet.http.HttpSession) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Token(org.scribe.model.Token) OpenIDVerifier(org.olat.login.oauth.spi.OpenIDVerifier) Verifier(org.scribe.model.Verifier) AssertException(org.olat.core.logging.AssertException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) OAuthService(org.scribe.oauth.OAuthService) OAuthUser(org.olat.login.oauth.model.OAuthUser) OAuthRegistration(org.olat.login.oauth.model.OAuthRegistration) RedirectMediaResource(org.olat.core.gui.media.RedirectMediaResource) MediaResource(org.olat.core.gui.media.MediaResource) RedirectMediaResource(org.olat.core.gui.media.RedirectMediaResource) Identity(org.olat.core.id.Identity) UserRequest(org.olat.core.gui.UserRequest) UserRequestImpl(org.olat.core.gui.UserRequestImpl)

Example 37 with AssertException

use of org.olat.core.logging.AssertException in project OpenOLAT by OpenOLAT.

the class RepositoryManager method queryByOwner.

/**
 * Query by ownership, optionally limit by type.
 *
 * @param identity
 * @param limitType
 * @return Results
 */
public List<RepositoryEntry> queryByOwner(IdentityRef identity, String... limitTypes) {
    if (identity == null)
        throw new AssertException("identity can not be null!");
    StringBuilder sb = new StringBuilder(400);
    sb.append("select v from repositoryentry v ").append(" inner join fetch v.olatResource as res ").append(" inner join fetch v.statistics as statistics").append(" left join fetch v.lifecycle as lifecycle").append(" inner join v.groups as relGroup on relGroup.defaultGroup=true").append(" inner join relGroup.group as baseGroup").append(" inner join baseGroup.members as membership on membership.role='").append(GroupRoles.owner.name()).append("'").append(" where v.access>0 and membership.identity.key=:identityKey");
    if (limitTypes != null && limitTypes.length > 0) {
        sb.append(" and res.resName in (:types)");
    }
    TypedQuery<RepositoryEntry> query = dbInstance.getCurrentEntityManager().createQuery(sb.toString(), RepositoryEntry.class).setParameter("identityKey", identity.getKey());
    if (limitTypes != null && limitTypes.length > 0) {
        List<String> types = new ArrayList<String>();
        for (String type : limitTypes) {
            types.add(type);
        }
        query.setParameter("types", types);
    }
    return query.getResultList();
}
Also used : AssertException(org.olat.core.logging.AssertException) ArrayList(java.util.ArrayList)

Example 38 with AssertException

use of org.olat.core.logging.AssertException in project OpenOLAT by OpenOLAT.

the class RepositoryManager method lookupRepositoryEntryKey.

public Long lookupRepositoryEntryKey(OLATResourceable resourceable, boolean strict) {
    OLATResource ores = (resourceable instanceof OLATResource) ? (OLATResource) resourceable : OLATResourceManager.getInstance().findResourceable(resourceable);
    if (ores == null) {
        if (!strict)
            return null;
        throw new AssertException("Unable to fetch OLATResource for resourceable: " + resourceable.getResourceableTypeName() + ", " + resourceable.getResourceableId());
    }
    StringBuilder sb = new StringBuilder();
    sb.append("select v.key from ").append(RepositoryEntry.class.getName()).append(" v ").append(" where v.olatResource.key=:oreskey");
    List<Long> result = dbInstance.getCurrentEntityManager().createQuery(sb.toString(), Long.class).setParameter("oreskey", ores.getKey()).setHint("org.hibernate.cacheable", Boolean.TRUE).getResultList();
    int size = result.size();
    if (strict) {
        if (size != 1)
            throw new AssertException("Repository resourceable lookup returned zero or more than one result: " + size);
    } else {
        // not strict -> return null if zero entries found
        if (size > 1)
            throw new AssertException("Repository resourceable lookup returned more than one result: " + size);
        if (size == 0) {
            return null;
        }
    }
    return result.get(0);
}
Also used : AssertException(org.olat.core.logging.AssertException) OLATResource(org.olat.resource.OLATResource)

Example 39 with AssertException

use of org.olat.core.logging.AssertException in project OpenOLAT by OpenOLAT.

the class RepositoryManager method lookupRepositoryEntry.

/**
 * Lookup the repository entry which references the given olat resourceable.
 * @param resourceable
 * @param strict true: throws exception if not found, false: returns null if not found
 * @return the RepositorEntry or null if strict=false
 * @throws AssertException if the softkey could not be found (strict=true)
 */
public RepositoryEntry lookupRepositoryEntry(OLATResourceable resourceable, boolean strict) {
    OLATResource ores = (resourceable instanceof OLATResource) ? (OLATResource) resourceable : OLATResourceManager.getInstance().findResourceable(resourceable);
    if (ores == null) {
        if (!strict)
            return null;
        throw new AssertException("Unable to fetch OLATResource for resourceable: " + resourceable.getResourceableTypeName() + ", " + resourceable.getResourceableId());
    }
    StringBuilder sb = new StringBuilder();
    sb.append("select v from ").append(RepositoryEntry.class.getName()).append(" v ").append(" inner join fetch v.olatResource as ores").append(" inner join fetch v.statistics as statistics").append(" left join fetch v.lifecycle as lifecycle").append(" where ores.key = :oreskey");
    List<RepositoryEntry> result = dbInstance.getCurrentEntityManager().createQuery(sb.toString(), RepositoryEntry.class).setParameter("oreskey", ores.getKey()).getResultList();
    int size = result.size();
    if (strict) {
        if (size != 1)
            throw new AssertException("Repository resourceable lookup returned zero or more than one result: " + size);
    } else {
        // not strict -> return null if zero entries found
        if (size > 1)
            throw new AssertException("Repository resourceable lookup returned more than one result: " + size);
        if (size == 0) {
            return null;
        }
    }
    return result.get(0);
}
Also used : AssertException(org.olat.core.logging.AssertException) OLATResource(org.olat.resource.OLATResource)

Example 40 with AssertException

use of org.olat.core.logging.AssertException in project OpenOLAT by OpenOLAT.

the class WikiEditController method getWikiReference.

/**
 * @param config the moduleConfig
 * @param strict an assertion exception is thrown if no entry is found when
 *          strict is set to true, otherwise, null is returned
 * @return the repositoryentry or null if not in strict mode and no entry
 *         found
 * @throws AssertException when in strict mode and no entry is found
 */
public static RepositoryEntry getWikiReference(ModuleConfiguration config, boolean strict) {
    if (config == null) {
        if (strict)
            throw new AssertException("missing config in Wiki");
        else
            return null;
    }
    String repoSoftkey = (String) config.get(WikiEditController.CONFIG_KEY_REPOSITORY_SOFTKEY);
    if (repoSoftkey == null) {
        if (strict)
            throw new AssertException("invalid config when being asked for references");
        else
            return null;
    }
    RepositoryManager rm = RepositoryManager.getInstance();
    RepositoryEntry entry = rm.lookupRepositoryEntryBySoftkey(repoSoftkey, strict);
    // entry can be null only if !strict
    return entry;
}
Also used : AssertException(org.olat.core.logging.AssertException) RepositoryManager(org.olat.repository.RepositoryManager) RepositoryEntry(org.olat.repository.RepositoryEntry)

Aggregations

AssertException (org.olat.core.logging.AssertException)364 IOException (java.io.IOException)38 File (java.io.File)28 Identity (org.olat.core.id.Identity)28 ArrayList (java.util.ArrayList)26 HashMap (java.util.HashMap)24 Controller (org.olat.core.gui.control.Controller)22 OLATResourceable (org.olat.core.id.OLATResourceable)22 RepositoryEntry (org.olat.repository.RepositoryEntry)22 WindowControl (org.olat.core.gui.control.WindowControl)20 UnsupportedEncodingException (java.io.UnsupportedEncodingException)18 JSONException (org.json.JSONException)18 BusinessGroup (org.olat.group.BusinessGroup)18 JSONObject (org.json.JSONObject)16 UserRequest (org.olat.core.gui.UserRequest)16 VFSContainer (org.olat.core.util.vfs.VFSContainer)16 VFSItem (org.olat.core.util.vfs.VFSItem)16 Date (java.util.Date)14 Properties (java.util.Properties)14 Property (org.olat.properties.Property)14