Search in sources :

Example 6 with User

use of org.haiku.haikudepotserver.dataobjects.User in project haikudepotserver by haiku.

the class UserApiImpl method renewToken.

@Override
public RenewTokenResult renewToken(RenewTokenRequest renewTokenRequest) {
    Preconditions.checkNotNull(renewTokenRequest);
    Preconditions.checkState(!Strings.isNullOrEmpty(renewTokenRequest.token));
    RenewTokenResult result = new RenewTokenResult();
    Optional<ObjectId> userOidOptional = userAuthenticationService.authenticateByToken(renewTokenRequest.token);
    if (userOidOptional.isPresent()) {
        ObjectContext context = serverRuntime.newContext();
        User user = User.getByObjectId(context, userOidOptional.get());
        result.token = userAuthenticationService.generateToken(user);
        LOGGER.debug("did renew token for user; {}", user.toString());
    } else {
        LOGGER.info("unable to renew token");
    }
    return result;
}
Also used : User(org.haiku.haikudepotserver.dataobjects.User) ObjectId(org.apache.cayenne.ObjectId) ObjectContext(org.apache.cayenne.ObjectContext)

Example 7 with User

use of org.haiku.haikudepotserver.dataobjects.User in project haikudepotserver by haiku.

the class UserRatingJobApiImpl method queueUserRatingSpreadsheetJob.

@Override
public QueueUserRatingSpreadsheetJobResult queueUserRatingSpreadsheetJob(QueueUserRatingSpreadsheetJobRequest request) {
    Preconditions.checkArgument(null != request);
    Preconditions.checkArgument(Strings.isNullOrEmpty(request.pkgName) || Strings.isNullOrEmpty(request.userNickname), "the user nickname or pkg name can be supplied, but not both");
    final ObjectContext context = serverRuntime.newContext();
    User user = obtainAuthenticatedUser(context);
    UserRatingSpreadsheetJobSpecification spec = new UserRatingSpreadsheetJobSpecification();
    if (!Strings.isNullOrEmpty(request.repositoryCode)) {
        spec.setRepositoryCode(getRepository(context, request.repositoryCode).getCode());
    }
    if (!Strings.isNullOrEmpty(request.userNickname)) {
        Optional<User> requestUserOptional = User.tryGetByNickname(context, request.userNickname);
        if (requestUserOptional.isEmpty()) {
            throw new AccessDeniedException("attempt to produce user rating report for user [" + request.userNickname + "], but that user does not exist -- not allowed");
        }
        if (!permissionEvaluator.hasPermission(SecurityContextHolder.getContext().getAuthentication(), requestUserOptional.get(), Permission.BULK_USERRATINGSPREADSHEETREPORT_USER)) {
            throw new AccessDeniedException("attempt to access a user rating report for user [" + request.userNickname + "], but this was disallowed");
        }
        spec.setUserNickname(request.userNickname);
    } else {
        if (!Strings.isNullOrEmpty(request.pkgName)) {
            Optional<Pkg> requestPkgOptional = Pkg.tryGetByName(context, request.pkgName);
            if (requestPkgOptional.isEmpty()) {
                throw new AccessDeniedException("attempt to produce user rating report for pkg [" + request.pkgName + "], but that pkg does not exist -- not allowed");
            }
            if (!permissionEvaluator.hasPermission(SecurityContextHolder.getContext().getAuthentication(), requestPkgOptional.get(), Permission.BULK_USERRATINGSPREADSHEETREPORT_PKG)) {
                throw new AccessDeniedException("attempt to access a user rating report for pkg [" + request.pkgName + "], but this was disallowed");
            }
            spec.setPkgName(request.pkgName);
        } else {
            if (!permissionEvaluator.hasPermission(SecurityContextHolder.getContext().getAuthentication(), null, Permission.BULK_USERRATINGSPREADSHEETREPORT_ALL)) {
                throw new AccessDeniedException("attempt to access a user rating report, but was unauthorized");
            }
        }
    }
    spec.setOwnerUserNickname(user.getNickname());
    return new QueueUserRatingSpreadsheetJobResult(jobService.submit(spec, JobSnapshot.COALESCE_STATUSES_QUEUED_STARTED));
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) User(org.haiku.haikudepotserver.dataobjects.User) UserRatingSpreadsheetJobSpecification(org.haiku.haikudepotserver.userrating.model.UserRatingSpreadsheetJobSpecification) ObjectContext(org.apache.cayenne.ObjectContext) Pkg(org.haiku.haikudepotserver.dataobjects.Pkg) QueueUserRatingSpreadsheetJobResult(org.haiku.haikudepotserver.api1.model.userrating.job.QueueUserRatingSpreadsheetJobResult)

Example 8 with User

use of org.haiku.haikudepotserver.dataobjects.User in project haikudepotserver by haiku.

the class UserServiceImpl method isUserCurrentlyAgreeingToCurrentUserUsageConditions.

@Override
public boolean isUserCurrentlyAgreeingToCurrentUserUsageConditions(User user) {
    ObjectContext context = user.getObjectContext();
    String code = UserUsageConditions.getLatest(context).getCode();
    return user.tryGetUserUsageConditionsAgreement().filter(_UserUsageConditionsAgreement::getActive).filter(uuca -> uuca.getUserUsageConditions().getCode().equals(code)).isPresent();
}
Also used : ObjectContext(org.apache.cayenne.ObjectContext) Logger(org.slf4j.Logger) UserUsageConditions(org.haiku.haikudepotserver.dataobjects.UserUsageConditions) LoggerFactory(org.slf4j.LoggerFactory) Strings(com.google.common.base.Strings) org.haiku.haikudepotserver.dataobjects.auto._UserUsageConditionsAgreement(org.haiku.haikudepotserver.dataobjects.auto._UserUsageConditionsAgreement) List(java.util.List) Service(org.springframework.stereotype.Service) UserSearchSpecification(org.haiku.haikudepotserver.user.model.UserSearchSpecification) Preconditions(com.google.common.base.Preconditions) ObjectSelect(org.apache.cayenne.query.ObjectSelect) User(org.haiku.haikudepotserver.dataobjects.User) UserService(org.haiku.haikudepotserver.user.model.UserService) LikeHelper(org.haiku.haikudepotserver.support.LikeHelper) ObjectContext(org.apache.cayenne.ObjectContext) org.haiku.haikudepotserver.dataobjects.auto._UserUsageConditionsAgreement(org.haiku.haikudepotserver.dataobjects.auto._UserUsageConditionsAgreement)

Example 9 with User

use of org.haiku.haikudepotserver.dataobjects.User in project haikudepotserver by haiku.

the class JobController method downloadGeneratedData.

/**
 * <p>This URL can be used to download job data that has resulted from a job being run.</p>
 */
@RequestMapping(value = "/" + SEGMENT_JOBDATA + "/{" + KEY_GUID + "}/" + SEGMENT_DOWNLOAD, method = RequestMethod.GET)
public void downloadGeneratedData(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = KEY_GUID) String guid) throws IOException {
    Preconditions.checkArgument(PATTERN_GUID.matcher(guid).matches(), "the supplied guid does not match the required pattern");
    ObjectContext context = serverRuntime.newContext();
    JobSnapshot job = jobService.tryGetJobForData(guid).orElseThrow(() -> {
        LOGGER.warn("attempt to access job data {} for which no job exists", guid);
        return new JobDataAuthorizationFailure();
    });
    if (!Strings.isNullOrEmpty(job.getOwnerUserNickname())) {
        User user = tryObtainAuthenticatedUser(context).orElseThrow(() -> {
            LOGGER.warn("attempt to obtain job data {} with no authenticated user", guid);
            return new JobDataAuthorizationFailure();
        });
        User ownerUser = User.tryGetByNickname(context, job.getOwnerUserNickname()).orElseThrow(() -> {
            LOGGER.warn("owner of job does not seem to exist; {}", job.getOwnerUserNickname());
            return new JobDataAuthorizationFailure();
        });
        if (!permissionEvaluator.hasPermission(SecurityContextHolder.getContext().getAuthentication(), ownerUser, Permission.USER_VIEWJOBS)) {
            LOGGER.warn("attempt to access jobs view for; {}", job.toString());
            throw new JobDataAuthorizationFailure();
        }
    } else {
        LOGGER.debug("access to job [{}] allowed for unauthenticated access", job.toString());
    }
    JobDataWithByteSource jobDataWithByteSink = jobService.tryObtainData(guid).orElseThrow(() -> {
        LOGGER.warn("requested job data {} not found", guid);
        return new JobDataAuthorizationFailure();
    });
    // finally access has been checked and the logic can move onto actual
    // delivery of the material.
    JobData jobData = jobDataWithByteSink.getJobData();
    if (!Strings.isNullOrEmpty(jobData.getMediaTypeCode())) {
        response.setContentType(jobData.getMediaTypeCode());
    } else {
        response.setContentType(MediaType.OCTET_STREAM.toString());
    }
    response.setContentType(MediaType.CSV_UTF_8.toString());
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + jobService.deriveDataFilename(guid));
    response.setDateHeader(HttpHeaders.EXPIRES, 0);
    response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
    // now switch to async for the delivery of the data.
    AsyncContext async = request.startAsync();
    async.setTimeout(TIMEOUT_DOWNLOAD_MILLIS);
    ServletOutputStream outputStream = response.getOutputStream();
    outputStream.setWriteListener(new JobDataWriteListener(guid, jobService, async, outputStream));
    LOGGER.info("did start async stream job data; {}", guid);
}
Also used : User(org.haiku.haikudepotserver.dataobjects.User) JobDataWriteListener(org.haiku.haikudepotserver.support.web.JobDataWriteListener) ServletOutputStream(javax.servlet.ServletOutputStream) AsyncContext(javax.servlet.AsyncContext) ObjectContext(org.apache.cayenne.ObjectContext)

Example 10 with User

use of org.haiku.haikudepotserver.dataobjects.User in project haikudepotserver by haiku.

the class PkgScreenshotController method handleAdd.

/**
 * <p>This handler will take-up an HTTP POST that provides a new screenshot for the package.</p>
 */
@RequestMapping(value = "/{" + KEY_PKGNAME + "}/add", method = RequestMethod.POST)
public void handleAdd(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = KEY_FORMAT) String format, @PathVariable(value = KEY_PKGNAME) String pkgName) throws IOException {
    if (Strings.isNullOrEmpty(pkgName) || !Pkg.PATTERN_NAME.matcher(pkgName).matches()) {
        throw new MissingPkgName();
    }
    if (Strings.isNullOrEmpty(format) || !"png".equals(format)) {
        throw new MissingOrBadFormat();
    }
    ObjectContext context = serverRuntime.newContext();
    Pkg pkg = Pkg.tryGetByName(context, pkgName).orElseThrow(PkgNotFound::new);
    // check the authorization
    Optional<User> user = tryObtainAuthenticatedUser(context);
    if (!permissionEvaluator.hasPermission(SecurityContextHolder.getContext().getAuthentication(), pkg, Permission.PKG_EDITSCREENSHOT)) {
        LOGGER.warn("attempt to add a pkg screenshot, but there is no user present or that user is not able to edit the pkg");
        throw new PkgAuthorizationFailure();
    }
    String screenshotCode;
    try {
        screenshotCode = pkgScreenshotService.storePkgScreenshotImage(request.getInputStream(), context, pkg.getPkgSupplement(), null).getCode();
    } catch (SizeLimitReachedException sizeLimit) {
        LOGGER.warn("attempt to load in a screenshot larger than the size limit");
        throw new MissingOrBadFormat();
    } catch (BadPkgScreenshotException badIcon) {
        throw new MissingOrBadFormat();
    }
    context.commitChanges();
    // trigger optimization of the screenshot image.
    jobService.submit(new PkgScreenshotOptimizationJobSpecification(screenshotCode), JobSnapshot.COALESCE_STATUSES_QUEUED_STARTED);
    response.setHeader(HEADER_SCREENSHOTCODE, screenshotCode);
    response.setStatus(HttpServletResponse.SC_OK);
}
Also used : User(org.haiku.haikudepotserver.dataobjects.User) BadPkgScreenshotException(org.haiku.haikudepotserver.pkg.model.BadPkgScreenshotException) PkgScreenshotOptimizationJobSpecification(org.haiku.haikudepotserver.pkg.model.PkgScreenshotOptimizationJobSpecification) ObjectContext(org.apache.cayenne.ObjectContext) SizeLimitReachedException(org.haiku.haikudepotserver.pkg.model.SizeLimitReachedException) Pkg(org.haiku.haikudepotserver.dataobjects.Pkg)

Aggregations

User (org.haiku.haikudepotserver.dataobjects.User)51 ObjectContext (org.apache.cayenne.ObjectContext)47 AbstractIntegrationTest (org.haiku.haikudepotserver.AbstractIntegrationTest)16 Test (org.junit.jupiter.api.Test)16 AccessDeniedException (org.springframework.security.access.AccessDeniedException)14 Pkg (org.haiku.haikudepotserver.dataobjects.Pkg)7 ObjectId (org.apache.cayenne.ObjectId)5 ObjectNotFoundException (org.haiku.haikudepotserver.api1.support.ObjectNotFoundException)5 org.haiku.haikudepotserver.dataobjects.auto._User (org.haiku.haikudepotserver.dataobjects.auto._User)5 PermissionUserPkg (org.haiku.haikudepotserver.dataobjects.PermissionUserPkg)4 AuthenticateUserRequest (org.haiku.haikudepotserver.api1.model.user.AuthenticateUserRequest)3 AuthenticateUserResult (org.haiku.haikudepotserver.api1.model.user.AuthenticateUserResult)3 Captcha (org.haiku.haikudepotserver.captcha.model.Captcha)3 Preconditions (com.google.common.base.Preconditions)2 SignedJWT (com.nimbusds.jwt.SignedJWT)2 CSVWriter (com.opencsv.CSVWriter)2 OutputStream (java.io.OutputStream)2 OutputStreamWriter (java.io.OutputStreamWriter)2 Instant (java.time.Instant)2 DateTimeFormatter (java.time.format.DateTimeFormatter)2