Search in sources :

Example 1 with AuthenticationException

use of org.bimserver.webservices.authorization.AuthenticationException in project BIMserver by opensourceBIM.

the class OAuthAuthorizationServlet method service.

@Override
public void service(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException {
    OAuthAuthzRequest oauthRequest = null;
    String authType = request.getParameter("auth_type");
    if (request.getParameter("token") == null) {
        String location = "/apps/bimviews/?page=OAuth&auth_type=" + authType + "&client_id=" + request.getParameter("client_id") + "&response_type=" + request.getParameter("response_type") + "&redirect_uri=" + request.getParameter("redirect_uri");
        if (request.getParameter("state") != null) {
            String state = request.getParameter("state");
            LOGGER.info("Incoming state: " + state);
            String encodedState = UrlEscapers.urlFragmentEscaper().escape(state);
            LOGGER.info("Encoded state: " + encodedState);
            location += "&state=" + encodedState;
        }
        LOGGER.info("Redirecting to " + location);
        httpServletResponse.sendRedirect(location);
        return;
    }
    OAuthAuthorizationCode oauthCode = null;
    String token = request.getParameter("token");
    try (DatabaseSession session = getBimServer().getDatabase().createSession()) {
        OAuthServer oAuthServer = session.querySingle(StorePackage.eINSTANCE.getOAuthServer_ClientId(), request.getParameter("client_id"));
        org.bimserver.webservices.authorization.Authorization realAuth = org.bimserver.webservices.authorization.Authorization.fromToken(getBimServer().getEncryptionKey(), token);
        long uoid = realAuth.getUoid();
        User user = session.get(uoid, OldQuery.getDefault());
        for (OAuthAuthorizationCode oAuthAuthorizationCode : user.getOAuthIssuedAuthorizationCodes()) {
            if (oAuthAuthorizationCode.getOauthServer() == oAuthServer) {
                if (oAuthAuthorizationCode.getAuthorization() != null) {
                    oauthCode = oAuthAuthorizationCode;
                }
            }
        }
        try {
            if (oauthCode == null) {
                throw new ServletException("No auth found for token " + token);
            }
            oauthRequest = new OAuthAuthzRequest(request);
            String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
            OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);
            if (responseType.equals(ResponseType.CODE.toString())) {
                builder.setCode(oauthCode.getCode());
            // } else if (responseType.equals(ResponseType.TOKEN))) {
            // builder.setAccessToken(oauthCode.get)
            }
            // if (responseType.equals(ResponseType.TOKEN.toString())) {
            // builder.setAccessToken(oauthIssuerImpl.accessToken());
            // // builder.setTokenType(OAuth.DEFAULT_TOKEN_TYPE.toString());
            // builder.setExpiresIn(3600l);
            // }
            String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
            if (redirectURI != null && !redirectURI.equals("")) {
                URI uri = makeUrl(redirectURI, oauthCode, builder);
                LOGGER.info("Redirecting to " + uri);
                httpServletResponse.sendRedirect(uri.toString());
            } else {
                URI uri = makeUrl("http://fakeaddress", oauthCode, builder);
                httpServletResponse.getWriter().println("No redirectURI provided");
                httpServletResponse.getWriter().println("Would have redirected to: " + uri);
            }
        } catch (OAuthProblemException e) {
            final Response.ResponseBuilder responseBuilder = Response.status(HttpServletResponse.SC_FOUND);
            String redirectUri = e.getRedirectUri();
            if (OAuthUtils.isEmpty(redirectUri)) {
                throw new WebApplicationException(responseBuilder.entity("OAuth callback url needs to be provided by client!!!").build());
            }
            try {
                OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e).location(redirectUri).buildQueryMessage();
                // final URI location = new URI(response.getLocationUri());
                httpServletResponse.sendRedirect(response.getLocationUri());
            } catch (OAuthSystemException e1) {
                e1.printStackTrace();
            }
        }
    } catch (OAuthSystemException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (BimserverLockConflictException e2) {
        e2.printStackTrace();
    } catch (BimserverDatabaseException e2) {
        e2.printStackTrace();
    } catch (AuthenticationException e2) {
        e2.printStackTrace();
    }
}
Also used : User(org.bimserver.models.store.User) WebApplicationException(javax.ws.rs.WebApplicationException) DatabaseSession(org.bimserver.database.DatabaseSession) AuthenticationException(org.bimserver.webservices.authorization.AuthenticationException) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) URISyntaxException(java.net.URISyntaxException) OAuthServer(org.bimserver.models.store.OAuthServer) OAuthAuthorizationResponseBuilder(org.apache.oltu.oauth2.as.response.OAuthASResponse.OAuthAuthorizationResponseBuilder) URI(java.net.URI) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) ServletException(javax.servlet.ServletException) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) OAuthAuthzRequest(org.apache.oltu.oauth2.as.request.OAuthAuthzRequest) OAuthASResponse(org.apache.oltu.oauth2.as.response.OAuthASResponse) OAuthAuthorizationResponseBuilder(org.apache.oltu.oauth2.as.response.OAuthASResponse.OAuthAuthorizationResponseBuilder) BimserverLockConflictException(org.bimserver.database.BimserverLockConflictException) OAuthAuthorizationCode(org.bimserver.models.store.OAuthAuthorizationCode)

Example 2 with AuthenticationException

use of org.bimserver.webservices.authorization.AuthenticationException in project BIMserver by opensourceBIM.

the class AutologinDatabaseAction method execute.

@Override
public String execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException {
    try {
        Authorization authorization = Authorization.fromToken(bimServer.getEncryptionKey(), token);
        User user = getDatabaseSession().get(authorization.getUoid(), OldQuery.getDefault());
        if (user.getState() == ObjectState.DELETED) {
            throw new UserException("User account has been deleted");
        } else if (user.getUserType() == UserType.SYSTEM) {
            throw new UserException("System user cannot login");
        }
        if (bimServer.getServerSettingsCache().getServerSettings().isStoreLastLogin()) {
            user.setLastSeen(new Date());
            getDatabaseSession().store(user);
        }
        authorization.setUoid(user.getOid());
        String asHexToken = authorization.asHexToken(bimServer.getEncryptionKey());
        serviceMap.setAuthorization(authorization);
        return asHexToken;
    } catch (AuthenticationException e) {
        LOGGER.error("", e);
    }
    try {
        // Adding a random sleep to prevent timing attacks
        Thread.sleep(LoginDatabaseAction.DEFAULT_LOGIN_ERROR_TIMEOUT + new java.security.SecureRandom().nextInt(1000));
    } catch (InterruptedException e) {
        LOGGER.error("", e);
    }
    throw new UserException("User not found or inccorrect autologin token");
}
Also used : Authorization(org.bimserver.webservices.authorization.Authorization) User(org.bimserver.models.store.User) AuthenticationException(org.bimserver.webservices.authorization.AuthenticationException) UserException(org.bimserver.shared.exceptions.UserException) Date(java.util.Date)

Example 3 with AuthenticationException

use of org.bimserver.webservices.authorization.AuthenticationException in project BIMserver by opensourceBIM.

the class ServiceRunnerServlet method service.

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if (request.getRequestURI().endsWith("/servicelist")) {
        processServiceList(request, response);
        return;
    }
    String token = null;
    if (request.getHeader("Authorization") != null) {
        String a = request.getHeader("Authorization");
        if (a.startsWith("Bearer")) {
            token = a.substring(7);
        }
    }
    if (token == null) {
        token = request.getHeader("Token");
    }
    LOGGER.info("Token: " + token);
    String serviceName = request.getHeader("ServiceName");
    if (serviceName == null) {
        serviceName = request.getRequestURI();
        if (serviceName.startsWith("/services/")) {
            serviceName = serviceName.substring(10);
        }
    }
    LOGGER.info("ServiceName: " + serviceName);
    long serviceOid = Long.parseLong(serviceName);
    String inputType = request.getHeader("Input-Type");
    LOGGER.info("Input-Type: " + inputType);
    try (DatabaseSession session = getBimServer().getDatabase().createSession()) {
        Authorization authorization = Authorization.fromToken(getBimServer().getEncryptionKey(), token);
        User user = session.get(authorization.getUoid(), OldQuery.getDefault());
        if (user == null) {
            LOGGER.error("Service \"" + serviceName + "\" not found for this user");
            throw new UserException("No user found with uoid " + authorization.getUoid());
        }
        if (user.getState() == ObjectState.DELETED) {
            LOGGER.error("User has been deleted");
            throw new UserException("User has been deleted");
        }
        InternalServicePluginConfiguration foundService = null;
        UserSettings userSettings = user.getUserSettings();
        for (InternalServicePluginConfiguration internalServicePluginConfiguration : userSettings.getServices()) {
            if (internalServicePluginConfiguration.getOid() == serviceOid) {
                foundService = internalServicePluginConfiguration;
                break;
            }
        }
        if (foundService == null) {
            LOGGER.info("Service \"" + serviceName + "\" not found for this user");
            throw new ServletException("Service \"" + serviceName + "\" not found for this user");
        }
        PluginDescriptor pluginDescriptor = foundService.getPluginDescriptor();
        ServicePlugin servicePlugin = getBimServer().getPluginManager().getServicePlugin(pluginDescriptor.getPluginClassName(), true);
        if (servicePlugin instanceof BimBotsServiceInterface) {
            LOGGER.info("Found service " + servicePlugin);
            BimBotsServiceInterface bimBotsServiceInterface = (BimBotsServiceInterface) servicePlugin;
            try {
                if (getBimServer().getServerSettingsCache().getServerSettings().isStoreServiceRuns()) {
                    LOGGER.info("Storing intermediate results");
                    // When we store service runs, we can just use the streaming deserializer to stream directly to the database, after that we'll trigger the actual service
                    // Create or find project and link user and service to project
                    // Checkin stream into project
                    // Trigger service
                    ServiceInterface serviceInterface = getBimServer().getServiceFactory().get(authorization, AccessMethod.INTERNAL).get(ServiceInterface.class);
                    SProject project = serviceInterface.addProject("tmp-" + new Random().nextInt(), "ifc2x3tc1");
                    SDeserializerPluginConfiguration deserializer = serviceInterface.getSuggestedDeserializerForExtension("ifc", project.getOid());
                    if (deserializer == null) {
                        throw new BimBotsException("No deserializer found");
                    }
                    serviceInterface.checkin(project.getOid(), "Auto checkin", deserializer.getOid(), -1L, "s", new DataHandler(new InputStreamDataSource(request.getInputStream())), false, true);
                    project = serviceInterface.getProjectByPoid(project.getOid());
                    PackageMetaData packageMetaData = getBimServer().getMetaDataManager().getPackageMetaData(project.getSchema());
                    IfcModelInterface model = new BasicIfcModel(packageMetaData, null);
                    try {
                        Revision revision = session.get(project.getLastRevisionId(), OldQuery.getDefault());
                        session.getMap(model, new OldQuery(packageMetaData, project.getId(), revision.getId(), revision.getOid(), null, Deep.NO));
                    } catch (BimserverDatabaseException e) {
                        e.printStackTrace();
                    }
                    BimServerBimBotsInput input = new BimServerBimBotsInput(getBimServer(), authorization.getUoid(), null, null, model);
                    BimBotsOutput output = bimBotsServiceInterface.runBimBot(input, getBimServer().getSConverter().convertToSObject(foundService.getSettings()));
                    SExtendedData extendedData = new SExtendedData();
                    SFile file = new SFile();
                    file.setData(output.getData());
                    file.setFilename(output.getContentDisposition());
                    file.setMime(output.getContentType());
                    file.setSize(output.getData().length);
                    Long fileId = serviceInterface.uploadFile(file);
                    extendedData.setFileId(fileId);
                    extendedData.setTitle(output.getTitle());
                    SExtendedDataSchema extendedDataSchema = null;
                    try {
                        extendedDataSchema = serviceInterface.getExtendedDataSchemaByName(output.getSchemaName());
                    } catch (UserException e) {
                        extendedDataSchema = new SExtendedDataSchema();
                        extendedDataSchema.setContentType(output.getContentType());
                        extendedDataSchema.setName(output.getSchemaName());
                        serviceInterface.addExtendedDataSchema(extendedDataSchema);
                    }
                    extendedData.setSchemaId(extendedDataSchema.getOid());
                    serviceInterface.addExtendedDataToRevision(project.getLastRevisionId(), extendedData);
                    response.setHeader("Output-Type", output.getSchemaName());
                    response.setHeader("Data-Title", output.getTitle());
                    response.setHeader("Data-Identifier", "" + project.getOid());
                    response.setHeader("Content-Type", output.getContentType());
                    response.setHeader("Content-Disposition", output.getContentDisposition());
                    response.getOutputStream().write(output.getData());
                } else {
                    // When we don't store the service runs, there is no other way than to just use the old deserializer and run the service from the EMF model
                    LOGGER.info("NOT Storing intermediate results");
                    DeserializerPlugin deserializerPlugin = getBimServer().getPluginManager().getFirstDeserializer("ifc", Schema.IFC2X3TC1, true);
                    if (deserializerPlugin == null) {
                        throw new BimBotsException("No deserializer plugin found");
                    }
                    byte[] data = IOUtils.toByteArray(request.getInputStream());
                    SchemaName schema = SchemaName.valueOf(inputType);
                    Deserializer deserializer = deserializerPlugin.createDeserializer(new PluginConfiguration());
                    PackageMetaData packageMetaData = getBimServer().getMetaDataManager().getPackageMetaData("ifc2x3tc1");
                    deserializer.init(packageMetaData);
                    IfcModelInterface model = deserializer.read(new ByteArrayInputStream(data), schema.name(), data.length, null);
                    BimServerBimBotsInput input = new BimServerBimBotsInput(getBimServer(), authorization.getUoid(), schema, data, model);
                    BimBotsOutput output = bimBotsServiceInterface.runBimBot(input, getBimServer().getSConverter().convertToSObject(foundService.getSettings()));
                    response.setHeader("Output-Type", output.getSchemaName());
                    response.setHeader("Data-Title", output.getTitle());
                    response.setHeader("Content-Type", output.getContentType());
                    response.setHeader("Content-Disposition", output.getContentDisposition());
                    response.getOutputStream().write(output.getData());
                }
            } catch (BimBotsException e) {
                LOGGER.error("", e);
            } catch (DeserializeException e) {
                LOGGER.error("", e);
            } catch (PluginException e) {
                LOGGER.error("", e);
            } catch (ServerException e) {
                LOGGER.error("", e);
            }
        } else {
            throw new ServletException("Service \"" + serviceName + "\" does not implement the BimBotsServiceInterface");
        }
    } catch (AuthenticationException e) {
        LOGGER.error("", e);
    } catch (BimserverDatabaseException e) {
        LOGGER.error("", e);
    } catch (UserException e) {
        LOGGER.error("", e);
    }
}
Also used : ServicePlugin(org.bimserver.plugins.services.ServicePlugin) User(org.bimserver.models.store.User) SDeserializerPluginConfiguration(org.bimserver.interfaces.objects.SDeserializerPluginConfiguration) DatabaseSession(org.bimserver.database.DatabaseSession) AuthenticationException(org.bimserver.webservices.authorization.AuthenticationException) IfcModelInterface(org.bimserver.emf.IfcModelInterface) DataHandler(javax.activation.DataHandler) BimBotsServiceInterface(org.bimserver.bimbots.BimBotsServiceInterface) SProject(org.bimserver.interfaces.objects.SProject) SExtendedDataSchema(org.bimserver.interfaces.objects.SExtendedDataSchema) Authorization(org.bimserver.webservices.authorization.Authorization) ServletException(javax.servlet.ServletException) InputStreamDataSource(org.bimserver.utils.InputStreamDataSource) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) Random(java.util.Random) BimBotsServiceInterface(org.bimserver.bimbots.BimBotsServiceInterface) ServiceInterface(org.bimserver.shared.interfaces.ServiceInterface) InternalServicePluginConfiguration(org.bimserver.models.store.InternalServicePluginConfiguration) SDeserializerPluginConfiguration(org.bimserver.interfaces.objects.SDeserializerPluginConfiguration) PluginConfiguration(org.bimserver.plugins.PluginConfiguration) UserException(org.bimserver.shared.exceptions.UserException) SFile(org.bimserver.interfaces.objects.SFile) ServerException(org.bimserver.shared.exceptions.ServerException) UserSettings(org.bimserver.models.store.UserSettings) PackageMetaData(org.bimserver.emf.PackageMetaData) PluginException(org.bimserver.shared.exceptions.PluginException) DeserializerPlugin(org.bimserver.plugins.deserializers.DeserializerPlugin) BimBotsException(org.bimserver.bimbots.BimBotsException) DeserializeException(org.bimserver.plugins.deserializers.DeserializeException) BasicIfcModel(org.bimserver.ifc.BasicIfcModel) BimServerBimBotsInput(org.bimserver.bimbots.BimServerBimBotsInput) OldQuery(org.bimserver.database.OldQuery) PluginDescriptor(org.bimserver.models.store.PluginDescriptor) Revision(org.bimserver.models.store.Revision) SExtendedData(org.bimserver.interfaces.objects.SExtendedData) ByteArrayInputStream(java.io.ByteArrayInputStream) Deserializer(org.bimserver.plugins.deserializers.Deserializer) InternalServicePluginConfiguration(org.bimserver.models.store.InternalServicePluginConfiguration) BimBotsOutput(org.bimserver.bimbots.BimBotsOutput) SchemaName(org.bimserver.plugins.SchemaName)

Aggregations

User (org.bimserver.models.store.User)3 AuthenticationException (org.bimserver.webservices.authorization.AuthenticationException)3 ServletException (javax.servlet.ServletException)2 BimserverDatabaseException (org.bimserver.BimserverDatabaseException)2 DatabaseSession (org.bimserver.database.DatabaseSession)2 UserException (org.bimserver.shared.exceptions.UserException)2 Authorization (org.bimserver.webservices.authorization.Authorization)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 Date (java.util.Date)1 Random (java.util.Random)1 DataHandler (javax.activation.DataHandler)1 WebApplicationException (javax.ws.rs.WebApplicationException)1 OAuthAuthzRequest (org.apache.oltu.oauth2.as.request.OAuthAuthzRequest)1 OAuthASResponse (org.apache.oltu.oauth2.as.response.OAuthASResponse)1 OAuthAuthorizationResponseBuilder (org.apache.oltu.oauth2.as.response.OAuthASResponse.OAuthAuthorizationResponseBuilder)1 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)1 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)1 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)1