Search in sources :

Example 26 with User

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

the class UserRatingApiIT method testCreateUserRating.

@Test
public void testCreateUserRating() {
    integrationTestSupportService.createStandardTestData();
    {
        ObjectContext context = serverRuntime.newContext();
        User user = integrationTestSupportService.createBasicUser(context, "testuser", "password");
        integrationTestSupportService.agreeToUserUsageConditions(context, user);
    }
    setAuthenticatedUser("testuser");
    CreateUserRatingRequest request = new CreateUserRatingRequest();
    request.naturalLanguageCode = NaturalLanguage.CODE_SPANISH;
    request.userNickname = "testuser";
    request.repositoryCode = "testrepo";
    request.userRatingStabilityCode = UserRatingStability.CODE_VERYUNSTABLE;
    request.comment = "The supermarket has gone crazy";
    request.rating = (short) 5;
    request.pkgName = "pkg1";
    request.pkgVersionArchitectureCode = "x86_64";
    request.pkgVersionType = PkgVersionType.LATEST;
    // ------------------------------------
    String code = userRatingApi.createUserRating(request).code;
    // ------------------------------------
    {
        ObjectContext context = serverRuntime.newContext();
        Optional<UserRating> userRatingOptional = UserRating.tryGetByCode(context, code);
        Assertions.assertThat(userRatingOptional.isPresent()).isTrue();
        Assertions.assertThat(userRatingOptional.get().getActive()).isTrue();
        Assertions.assertThat(userRatingOptional.get().getComment()).isEqualTo("The supermarket has gone crazy");
        Assertions.assertThat(userRatingOptional.get().getNaturalLanguage().getCode()).isEqualTo(NaturalLanguage.CODE_SPANISH);
        Assertions.assertThat(userRatingOptional.get().getRating()).isEqualTo((short) 5);
        Assertions.assertThat(userRatingOptional.get().getUser().getNickname()).isEqualTo("testuser");
        Assertions.assertThat(userRatingOptional.get().getUserRatingStability().getCode()).isEqualTo(UserRatingStability.CODE_VERYUNSTABLE);
        Assertions.assertThat(userRatingOptional.get().getPkgVersion().getPkg().getName()).isEqualTo("pkg1");
        Assertions.assertThat(userRatingOptional.get().getPkgVersion().getMajor()).isEqualTo("1");
        Assertions.assertThat(userRatingOptional.get().getPkgVersion().getMinor()).isNull();
        Assertions.assertThat(userRatingOptional.get().getPkgVersion().getMicro()).isEqualTo("2");
        Assertions.assertThat(userRatingOptional.get().getPkgVersion().getPreRelease()).isNull();
        Assertions.assertThat(userRatingOptional.get().getPkgVersion().getRevision()).isEqualTo(4);
    }
}
Also used : User(org.haiku.haikudepotserver.dataobjects.User) CreateUserRatingRequest(org.haiku.haikudepotserver.api1.model.userrating.CreateUserRatingRequest) Optional(java.util.Optional) ObjectContext(org.apache.cayenne.ObjectContext) AbstractIntegrationTest(org.haiku.haikudepotserver.AbstractIntegrationTest) Test(org.junit.jupiter.api.Test)

Example 27 with User

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

the class UserAuthorizationServiceImplIT method testPerformCheckOnViewOther.

/**
 * <p>Checks that a user is not able to see another user.</p>
 */
@Test
public void testPerformCheckOnViewOther() {
    Stream.of("testuser", "testuser2").forEach(n -> {
        ObjectContext context = serverRuntime.newContext();
        User user = integrationTestSupportService.createBasicUser(context, n, "guwfwef67");
        integrationTestSupportService.agreeToUserUsageConditions(context, user);
    });
    boolean result;
    {
        ObjectContext context = serverRuntime.newContext();
        // ---------------------------------
        result = userAuthorizationService.check(context, User.getByNickname(context, "testuser"), User.getByNickname(context, "testuser2"), Permission.USER_VIEW);
    // ---------------------------------
    }
    Assertions.assertThat(result).isFalse();
}
Also used : User(org.haiku.haikudepotserver.dataobjects.User) ObjectContext(org.apache.cayenne.ObjectContext) AbstractIntegrationTest(org.haiku.haikudepotserver.AbstractIntegrationTest) Test(org.junit.jupiter.api.Test)

Example 28 with User

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

the class UserAuthenticationServiceImpl method authenticateByNicknameAndPassword.

@Override
public Optional<ObjectId> authenticateByNicknameAndPassword(String nickname, String passwordClear) {
    Optional<ObjectId> result = Optional.empty();
    if (!Strings.isNullOrEmpty(nickname) && !Strings.isNullOrEmpty(passwordClear)) {
        ObjectContext objectContext = serverRuntime.newContext();
        Optional<User> userOptional = User.tryGetByNickname(objectContext, nickname);
        if (userOptional.isPresent()) {
            User user = userOptional.get();
            if (matchPassword(user, passwordClear)) {
                result = Optional.ofNullable(userOptional.get().getObjectId());
                maybeUpdateLastAuthenticationTimestamp(objectContext, user);
            } else {
                LOGGER.info("the authentication for the user; {} failed", nickname);
            }
        } else {
            LOGGER.info("unable to find the user; {}", nickname);
        }
    } else {
        LOGGER.info("attempt to authenticate with no username or no password");
    }
    return result;
}
Also used : User(org.haiku.haikudepotserver.dataobjects.User) ObjectId(org.apache.cayenne.ObjectId) ObjectContext(org.apache.cayenne.ObjectContext)

Example 29 with User

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

the class UserAuthenticationServiceImpl method authenticate.

/**
 * <p>This method will validate the json web token and assuming that everything is OK, it will return
 * an ObjectId that refers to the </p>
 */
private Optional<ObjectId> authenticate(SignedJWT signedJwt) {
    Preconditions.checkArgument(null != signedJwt, "the JWT must be provided");
    JWTClaimsSet claimsSet;
    long nowMillis = System.currentTimeMillis();
    try {
        claimsSet = signedJwt.getJWTClaimsSet();
    } catch (ParseException pe) {
        throw new IllegalStateException("unable to parse the jwt", pe);
    }
    String issuer = claimsSet.getIssuer();
    if (null == issuer || !issuer.equals(jsonWebTokenIssuer)) {
        LOGGER.info("rejected jwt authentication; the issuer '{}' on the jwt does not match the expected '{}'", issuer, jsonWebTokenIssuer);
    } else {
        java.util.Date issueTime = claimsSet.getIssueTime();
        java.util.Date expirationTime = claimsSet.getExpirationTime();
        if (null == issueTime || null == expirationTime || nowMillis < issueTime.getTime() || nowMillis > expirationTime.getTime()) {
            LOGGER.info("rejected jwt authentication; the issue time or expiration time are invalid or do not contain the current time");
        } else {
            String subject = claimsSet.getSubject();
            if (null == subject || !subject.endsWith(SUFFIX_JSONWEBTOKEN_SUBJECT) || subject.length() <= SUFFIX_JSONWEBTOKEN_SUBJECT.length()) {
                LOGGER.info("rejected jwt authentication; bad subject");
            } else {
                String nickname = subject.substring(0, subject.length() - SUFFIX_JSONWEBTOKEN_SUBJECT.length());
                ObjectContext context = serverRuntime.newContext();
                Optional<User> userOptional = User.tryGetByNickname(context, nickname);
                if (userOptional.isPresent()) {
                    return Optional.of(userOptional.get().getObjectId());
                }
            }
        }
    }
    return Optional.empty();
}
Also used : User(org.haiku.haikudepotserver.dataobjects.User) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(java.text.ParseException) ObjectContext(org.apache.cayenne.ObjectContext)

Example 30 with User

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

the class AuthorizationRulesSpreadsheetJobRunner method run.

@Override
public void run(JobService jobService, AuthorizationRulesSpreadsheetJobSpecification specification) throws IOException, JobRunnerException {
    final ObjectContext context = serverRuntime.newContext();
    DateTimeFormatter dateTimeFormatter = DateTimeHelper.createStandardDateTimeFormat();
    // this will register the outbound data against the job.
    JobDataWithByteSink jobDataWithByteSink = jobService.storeGeneratedData(specification.getGuid(), "download", MediaType.CSV_UTF_8.toString());
    try (OutputStream outputStream = jobDataWithByteSink.getByteSink().openBufferedStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
        CSVWriter writer = new CSVWriter(outputStreamWriter, ',')) {
        writer.writeNext(new String[] { "create-timestamp", "user-nickname", "user-active", "permission-code", "permission-name", "pkg-name" });
        ObjectSelect<PermissionUserPkg> objectSelect = ObjectSelect.query(PermissionUserPkg.class).orderBy(PermissionUserPkg.USER.dot(User.NICKNAME).asc(), PermissionUserPkg.PERMISSION.dot(Permission.CODE).asc());
        try (ResultBatchIterator<PermissionUserPkg> batchIterator = objectSelect.batchIterator(context, 50)) {
            batchIterator.forEach((pups) -> pups.forEach((pup) -> writer.writeNext(new String[] { dateTimeFormatter.format(Instant.ofEpochMilli(pup.getCreateTimestamp().getTime())), pup.getUser().getNickname(), Boolean.toString(pup.getUser().getActive()), pup.getPermission().getCode(), pup.getPermission().getName(), null != pup.getPkg() ? pup.getPkg().getName() : "" })));
        }
        writer.flush();
        outputStreamWriter.flush();
    }
}
Also used : JobDataWithByteSink(org.haiku.haikudepotserver.job.model.JobDataWithByteSink) OutputStream(java.io.OutputStream) MediaType(com.google.common.net.MediaType) ObjectContext(org.apache.cayenne.ObjectContext) AbstractJobRunner(org.haiku.haikudepotserver.job.AbstractJobRunner) Resource(javax.annotation.Resource) CSVWriter(com.opencsv.CSVWriter) ResultBatchIterator(org.apache.cayenne.ResultBatchIterator) IOException(java.io.IOException) Instant(java.time.Instant) AuthorizationRulesSpreadsheetJobSpecification(org.haiku.haikudepotserver.security.model.AuthorizationRulesSpreadsheetJobSpecification) Component(org.springframework.stereotype.Component) Permission(org.haiku.haikudepotserver.dataobjects.Permission) DateTimeFormatter(java.time.format.DateTimeFormatter) PermissionUserPkg(org.haiku.haikudepotserver.dataobjects.PermissionUserPkg) JobDataWithByteSink(org.haiku.haikudepotserver.job.model.JobDataWithByteSink) OutputStreamWriter(java.io.OutputStreamWriter) Preconditions(com.google.common.base.Preconditions) ObjectSelect(org.apache.cayenne.query.ObjectSelect) User(org.haiku.haikudepotserver.dataobjects.User) JobService(org.haiku.haikudepotserver.job.model.JobService) JobRunnerException(org.haiku.haikudepotserver.job.model.JobRunnerException) ServerRuntime(org.apache.cayenne.configuration.server.ServerRuntime) DateTimeHelper(org.haiku.haikudepotserver.support.DateTimeHelper) OutputStream(java.io.OutputStream) CSVWriter(com.opencsv.CSVWriter) OutputStreamWriter(java.io.OutputStreamWriter) ObjectContext(org.apache.cayenne.ObjectContext) DateTimeFormatter(java.time.format.DateTimeFormatter) PermissionUserPkg(org.haiku.haikudepotserver.dataobjects.PermissionUserPkg)

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