Search in sources :

Example 36 with NotAuthorizedException

use of io.milton.http.exceptions.NotAuthorizedException in project lobcder by skoulouzis.

the class PutJsonResource method processForm.

@Override
public String processForm(Map<String, String> parameters, Map<String, FileItem> files) throws ConflictException, NotAuthorizedException, BadRequestException {
    log.info("processForm: " + wrapped.getClass());
    if (files.isEmpty()) {
        log.debug("no files uploaded");
        return null;
    }
    newFiles = new ArrayList<NewFile>();
    for (FileItem file : files.values()) {
        NewFile nf = new NewFile();
        String ua = HttpManager.request().getUserAgentHeader();
        String f = Utils.truncateFileName(ua, file.getName());
        nf.setOriginalName(f);
        nf.setContentType(file.getContentType());
        nf.setLength(file.getSize());
        newFiles.add(nf);
        String newName = getName(f, parameters);
        log.info("creating resource: " + newName + " size: " + file.getSize());
        InputStream in = null;
        Resource newResource;
        try {
            in = file.getInputStream();
            Resource existing = wrapped.child(newName);
            if (existing != null) {
                if (existing instanceof ReplaceableResource) {
                    log.trace("existing resource is replaceable, so replace content");
                    ReplaceableResource rr = (ReplaceableResource) existing;
                    rr.replaceContent(in, null);
                    log.trace("completed POST processing for file. Updated: " + existing.getName());
                    eventManager.fireEvent(new PutEvent(rr));
                    newResource = rr;
                } else {
                    log.trace("existing resource is not replaceable, will be deleted");
                    if (existing instanceof DeletableResource) {
                        DeletableResource dr = (DeletableResource) existing;
                        dr.delete();
                        newResource = wrapped.createNew(newName, in, file.getSize(), file.getContentType());
                        log.trace("completed POST processing for file. Deleted, then created: " + newResource.getName());
                        eventManager.fireEvent(new PutEvent(newResource));
                    } else {
                        throw new BadRequestException(existing, "existing resource could not be deleted, is not deletable");
                    }
                }
            } else {
                newResource = wrapped.createNew(newName, in, file.getSize(), file.getContentType());
                log.info("completed POST processing for file. Created: " + newResource.getName());
                eventManager.fireEvent(new PutEvent(newResource));
            }
            String newHref = buildNewHref(href, newResource.getName());
            nf.setHref(newHref);
        } catch (NotAuthorizedException ex) {
            throw new RuntimeException(ex);
        } catch (BadRequestException ex) {
            throw new RuntimeException(ex);
        } catch (ConflictException ex) {
            throw new RuntimeException(ex);
        } catch (IOException ex) {
            throw new RuntimeException("Exception creating resource", ex);
        } finally {
            FileUtils.close(in);
        }
    }
    log.trace("completed all POST processing");
    return null;
}
Also used : ConflictException(io.milton.http.exceptions.ConflictException) InputStream(java.io.InputStream) PutEvent(io.milton.event.PutEvent) DeletableResource(io.milton.resource.DeletableResource) PutableResource(io.milton.resource.PutableResource) ReplaceableResource(io.milton.resource.ReplaceableResource) Resource(io.milton.resource.Resource) PostableResource(io.milton.resource.PostableResource) NotAuthorizedException(io.milton.http.exceptions.NotAuthorizedException) IOException(java.io.IOException) ReplaceableResource(io.milton.resource.ReplaceableResource) BadRequestException(io.milton.http.exceptions.BadRequestException) DeletableResource(io.milton.resource.DeletableResource)

Example 37 with NotAuthorizedException

use of io.milton.http.exceptions.NotAuthorizedException in project lobcder by skoulouzis.

the class DefaultPropFindPropertyBuilder method processResource.

@Override
public void processResource(List<PropFindResponse> responses, PropFindableResource resource, PropertiesRequest parseResult, String href, int requestedDepth, int currentDepth, String collectionHref) throws NotAuthorizedException, BadRequestException {
    final LinkedHashMap<QName, ValueAndType> knownProperties = new LinkedHashMap<QName, ValueAndType>();
    final ArrayList<NameAndError> unknownProperties = new ArrayList<NameAndError>();
    if (resource instanceof CollectionResource) {
        if (!href.endsWith("/")) {
            href = href + "/";
        }
    }
    Set<QName> requestedFields;
    if (parseResult.isAllProp()) {
        requestedFields = findAllProps(resource);
    } else {
        requestedFields = parseResult.getNames();
    }
    Iterator<QName> it = requestedFields.iterator();
    while (it.hasNext()) {
        QName field = it.next();
        LogUtils.trace(log, "processResoource: find property:", field);
        if (field.getLocalPart().equals("href")) {
            knownProperties.put(field, new ValueAndType(href, String.class));
        } else {
            boolean found = false;
            for (PropertySource source : propertySources) {
                LogUtils.trace(log, "look for field", field, " in property source", source.getClass());
                PropertyMetaData meta = source.getPropertyMetaData(field, resource);
                if (meta != null && !meta.isUnknown()) {
                    Object val;
                    try {
                        val = source.getProperty(field, resource);
                        LogUtils.trace(log, "processResource: got value", val, "from source", source.getClass());
                        if (val == null) {
                            // null, but we still need type information to write it so use meta
                            knownProperties.put(field, new ValueAndType(val, meta.getValueType()));
                        } else {
                            // non-null, so use more robust class info
                            knownProperties.put(field, new ValueAndType(val, val.getClass()));
                        }
                    } catch (NotAuthorizedException ex) {
                        unknownProperties.add(new NameAndError(field, "Not authorised"));
                    }
                    found = true;
                    break;
                }
            }
            if (!found) {
                if (log.isDebugEnabled()) {
                    log.debug("property not found in any property source: " + field.toString());
                }
                unknownProperties.add(new NameAndError(field, null));
            }
        }
    }
    if (log.isDebugEnabled()) {
        if (unknownProperties.size() > 0) {
            log.debug("some properties could not be resolved. Listing property sources:");
            for (PropertySource ps : propertySources) {
                log.debug(" - " + ps.getClass().getCanonicalName());
            }
        }
    }
    // Map<Status, List<NameAndError>> errorProperties = new HashMap<Status, List<NameAndError>>();
    Map<Status, List<NameAndError>> errorProperties = new EnumMap<Status, List<NameAndError>>(Status.class);
    errorProperties.put(Status.SC_NOT_FOUND, unknownProperties);
    PropFindResponse r = new PropFindResponse(href, knownProperties, errorProperties);
    responses.add(r);
    if (requestedDepth > currentDepth && resource instanceof CollectionResource) {
        CollectionResource col = (CollectionResource) resource;
        List<? extends Resource> list = col.getChildren();
        list = new ArrayList<Resource>(list);
        for (Resource child : list) {
            if (child instanceof PropFindableResource) {
                String childName = child.getName();
                if (childName == null) {
                    log.warn("null name for resource of type: " + child.getClass() + " in folder: " + href + " WILL NOT be returned in PROPFIND response!!");
                } else {
                    String childHref = href + Utils.percentEncode(childName);
                    // Note that the new collection href, is just the current href
                    processResource(responses, (PropFindableResource) child, parseResult, childHref, requestedDepth, currentDepth + 1, href);
                }
            }
        }
    }
}
Also used : CollectionResource(io.milton.resource.CollectionResource) NotAuthorizedException(io.milton.http.exceptions.NotAuthorizedException) PropertySource(io.milton.property.PropertySource) PropFindableResource(io.milton.resource.PropFindableResource) Status(io.milton.http.Response.Status) ValueAndType(io.milton.http.values.ValueAndType) QName(javax.xml.namespace.QName) CollectionResource(io.milton.resource.CollectionResource) Resource(io.milton.resource.Resource) PropFindableResource(io.milton.resource.PropFindableResource) PropertyMetaData(io.milton.property.PropertySource.PropertyMetaData) NameAndError(io.milton.http.webdav.PropFindResponse.NameAndError)

Example 38 with NotAuthorizedException

use of io.milton.http.exceptions.NotAuthorizedException in project lobcder by skoulouzis.

the class LdapPropertyMapper method getLdapPropertyValue.

public String getLdapPropertyValue(String prop, Resource resource) throws BadRequestException {
    QName qn = mapToDavProp(prop);
    ValueAndType vt;
    try {
        vt = getProperty(qn, resource);
    } catch (NotAuthorizedException ex) {
        log.trace("property access not authorised");
        vt = null;
    }
    Object propValue;
    if (vt != null && vt.getValue() != null) {
        propValue = vt.getValue();
        return propValue.toString();
    }
    LogUtils.trace(log, "getLdapPropertyValue: property not found: ldap property: ", prop, " - dav prop: ", qn, "resource: ", resource.getClass());
    return null;
}
Also used : ValueAndType(io.milton.http.values.ValueAndType) QName(javax.xml.namespace.QName) NotAuthorizedException(io.milton.http.exceptions.NotAuthorizedException)

Example 39 with NotAuthorizedException

use of io.milton.http.exceptions.NotAuthorizedException in project lobcder by skoulouzis.

the class LoginResponseHandler method attemptRespondLoginPage.

private void attemptRespondLoginPage(Request request, Resource resource, Response response) throws RuntimeException {
    Resource rLogin;
    try {
        rLogin = resourceFactory.getResource(request.getHostHeader(), loginPage);
    } catch (NotAuthorizedException e) {
        throw new RuntimeException(e);
    } catch (BadRequestException ex) {
        throw new RuntimeException(ex);
    }
    if (rLogin == null || !(rLogin instanceof GetableResource)) {
        log.info("Couldnt find login resource: " + request.getHostHeader() + loginPage + " with resource factory: " + resourceFactory.getClass());
        wrapped.respondUnauthorised(resource, response, request);
    } else {
        log.trace("respond with 200 to suppress login prompt, using resource: " + rLogin.getName() + " - " + rLogin.getClass());
        try {
            // set request attribute so rendering knows it authorisation failed, or authentication is required
            Auth auth = request.getAuthorization();
            if (auth != null && auth.getTag() != null) {
                // no authentication was attempted,
                request.getAttributes().put("authReason", "notPermitted");
            } else {
                request.getAttributes().put("authReason", "required");
            }
            GetableResource gr = (GetableResource) rLogin;
            wrapped.respondContent(gr, response, request, null);
        } catch (NotAuthorizedException ex) {
            throw new RuntimeException(ex);
        } catch (BadRequestException ex) {
            throw new RuntimeException(ex);
        } catch (NotFoundException ex) {
            throw new RuntimeException(ex);
        }
    }
}
Also used : GetableResource(io.milton.resource.GetableResource) Resource(io.milton.resource.Resource) BadRequestException(io.milton.http.exceptions.BadRequestException) GetableResource(io.milton.resource.GetableResource) NotFoundException(io.milton.http.exceptions.NotFoundException) NotAuthorizedException(io.milton.http.exceptions.NotAuthorizedException)

Example 40 with NotAuthorizedException

use of io.milton.http.exceptions.NotAuthorizedException in project lobcder by skoulouzis.

the class CookieAuthenticationHandler method authenticate.

@Override
public Object authenticate(Resource resource, Request request) {
    // If there is a delegating handler which supports the request then we MUST use it
    // This would have been selected in the supports method
    AuthenticationHandler delegateHandler = (AuthenticationHandler) request.getAttributes().get(HANDLER_ATT_NAME);
    if (delegateHandler != null) {
        if (log.isTraceEnabled()) {
            log.trace("authenticate: use delegateHandler: " + delegateHandler);
        }
        // Attempt to authenticate against wrapped handler
        // If successful generate a signed cookie and put into a request attribute
        log.info("use handler: " + delegateHandler);
        Object tag = delegateHandler.authenticate(resource, request);
        if (tag != null) {
            if (tag instanceof DiscretePrincipal) {
                DiscretePrincipal p = (DiscretePrincipal) tag;
                setLoginCookies(p, request);
                log.trace("authentication passed by delegated handler, persisted userUrl to cookie");
            } else {
                log.warn("auth.tag is not a " + DiscretePrincipal.class + ", is: " + tag);
            }
            return tag;
        } else {
            log.info("Login failed by delegated handler: " + delegateHandler.getClass());
            return null;
        }
    } else {
        log.info("no delegating handler");
        // via a cookie, or this is an anonymous request
        if (isLogout(request)) {
            log.trace("authenticate: is logout");
            return null;
        } else {
            String userUrl = getUserUrl(request);
            log.info("userurl: " + userUrl);
            if (userUrl == null) {
                log.trace("authenticate: no userUrl in request or cookie, nothing to di");
                // no token in request, so is anonymous
                return null;
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("authenticate: userUrl=" + userUrl);
                }
                // we found a userUrl
                String host = request.getHostHeader();
                Resource r;
                try {
                    r = principalResourceFactory.getResource(host, userUrl);
                    log.info("found current user: " + r);
                } catch (NotAuthorizedException ex) {
                    log.error("Couldnt check userUrl in cookie", ex);
                    r = null;
                } catch (BadRequestException ex) {
                    log.error("Couldnt check userUrl in cookie", ex);
                    r = null;
                }
                if (r == null) {
                    log.warn("User not found host: " + host + " userUrl: " + userUrl + " with resourcefactory: " + principalResourceFactory);
                    clearCookieValue(HttpManager.response());
                } else {
                    // which case we need to set cookies
                    if (request.getParams() != null && request.getParams().containsKey(cookieUserUrlValue)) {
                        if (r instanceof DiscretePrincipal) {
                            DiscretePrincipal dp = (DiscretePrincipal) r;
                            setLoginCookies(dp, request);
                        } else {
                            log.warn("Found user from request, but user object is not expected type. Should be " + DiscretePrincipal.class + " but is " + r.getClass());
                        }
                    } else {
                        log.trace("Do not set cookies, because token did not come from request variable");
                    }
                }
                return r;
            }
        }
    }
}
Also used : DiscretePrincipal(io.milton.principal.DiscretePrincipal) Resource(io.milton.resource.Resource) BadRequestException(io.milton.http.exceptions.BadRequestException) NotAuthorizedException(io.milton.http.exceptions.NotAuthorizedException)

Aggregations

NotAuthorizedException (io.milton.http.exceptions.NotAuthorizedException)40 BadRequestException (io.milton.http.exceptions.BadRequestException)29 IOException (java.io.IOException)12 Resource (io.milton.resource.Resource)10 URISyntaxException (java.net.URISyntaxException)9 Connection (java.sql.Connection)9 SQLException (java.sql.SQLException)9 ConflictException (io.milton.http.exceptions.ConflictException)7 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 PreConditionFailedException (io.milton.http.exceptions.PreConditionFailedException)6 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 Permissions (nl.uva.cs.lobcder.auth.Permissions)6 NotFoundException (io.milton.http.exceptions.NotFoundException)5 CollectionResource (io.milton.resource.CollectionResource)5 ReplaceableResource (io.milton.resource.ReplaceableResource)5 QName (javax.xml.namespace.QName)5 Path (io.milton.common.Path)4 LockedException (io.milton.http.exceptions.LockedException)4 ValueAndType (io.milton.http.values.ValueAndType)4 LogicalData (nl.uva.cs.lobcder.resources.LogicalData)4