Search in sources :

Example 36 with User

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

the class UserApiImpl method authenticateUser.

// TODO; some sort of brute-force checking here; too many authentication requests in a short period; go into lock-down?
@Override
public AuthenticateUserResult authenticateUser(AuthenticateUserRequest authenticateUserRequest) {
    Preconditions.checkNotNull(authenticateUserRequest);
    AuthenticateUserResult authenticateUserResult = new AuthenticateUserResult();
    authenticateUserResult.token = null;
    if (null != authenticateUserRequest.nickname) {
        authenticateUserRequest.nickname = authenticateUserRequest.nickname.trim();
    }
    if (null != authenticateUserRequest.passwordClear) {
        authenticateUserRequest.passwordClear = authenticateUserRequest.passwordClear.trim();
    }
    Optional<ObjectId> userOidOptional = userAuthenticationService.authenticateByNicknameAndPassword(authenticateUserRequest.nickname, authenticateUserRequest.passwordClear);
    if (userOidOptional.isEmpty()) {
        // if the authentication has failed then best to sleep for a moment
        // to make brute forcing a bit more tricky.
        // TODO; this will eat threads; any other way to do it?
        Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);
    } else {
        ObjectContext context = serverRuntime.newContext();
        User user = User.getByObjectId(context, userOidOptional.get());
        authenticateUserResult.token = userAuthenticationService.generateToken(user);
    }
    return authenticateUserResult;
}
Also used : User(org.haiku.haikudepotserver.dataobjects.User) ObjectId(org.apache.cayenne.ObjectId) ObjectContext(org.apache.cayenne.ObjectContext)

Example 37 with User

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

the class UserApiImpl method changePassword.

@Override
public ChangePasswordResult changePassword(ChangePasswordRequest changePasswordRequest) throws ValidationException {
    Preconditions.checkNotNull(changePasswordRequest);
    Preconditions.checkState(!Strings.isNullOrEmpty(changePasswordRequest.nickname));
    Preconditions.checkState(!Strings.isNullOrEmpty(changePasswordRequest.newPasswordClear));
    // get the logged in and target user.
    final ObjectContext context = serverRuntime.newContext();
    User authUser = obtainAuthenticatedUser(context);
    User targetUser = User.tryGetByNickname(context, changePasswordRequest.nickname).orElseThrow(() -> new ObjectNotFoundException(User.class.getSimpleName(), changePasswordRequest.nickname));
    if (!permissionEvaluator.hasPermission(SecurityContextHolder.getContext().getAuthentication(), targetUser, Permission.USER_CHANGEPASSWORD)) {
        throw new AccessDeniedException("the logged in user is not allowed to change the password of another user [" + changePasswordRequest.nickname + "]");
    }
    if (!userAuthenticationService.validatePassword(changePasswordRequest.newPasswordClear)) {
        throw new ValidationException(new ValidationFailure("passwordClear", "invalid"));
    }
    if (Strings.isNullOrEmpty(changePasswordRequest.captchaToken)) {
        throw new IllegalStateException("the captcha token must be supplied to change the password");
    }
    if (Strings.isNullOrEmpty(changePasswordRequest.captchaResponse)) {
        throw new IllegalStateException("the captcha response must be supplied to change the password");
    }
    if (!captchaService.verify(changePasswordRequest.captchaToken, changePasswordRequest.captchaResponse)) {
        throw new CaptchaBadResponseException();
    }
    if (targetUser.getNickname().equals(authUser.getNickname())) {
        if (Strings.isNullOrEmpty(changePasswordRequest.oldPasswordClear)) {
            throw new IllegalStateException("the old password clear is required to change the password of a user unless the logged in user is root.");
        }
        if (userAuthenticationService.authenticateByNicknameAndPassword(changePasswordRequest.nickname, changePasswordRequest.oldPasswordClear).isEmpty()) {
            // if the old password does not match to the user then we should present this
            // as a validation failure rather than an authorization failure.
            LOGGER.info("the supplied old password is invalid for the user {}", changePasswordRequest.nickname);
            throw new ValidationException(new ValidationFailure("oldPasswordClear", "mismatched"));
        }
    }
    userAuthenticationService.setPassword(targetUser, changePasswordRequest.newPasswordClear);
    context.commitChanges();
    LOGGER.info("did change password for user {}", changePasswordRequest.nickname);
    return new ChangePasswordResult();
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) User(org.haiku.haikudepotserver.dataobjects.User) ObjectContext(org.apache.cayenne.ObjectContext)

Example 38 with User

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

the class UserApiImpl method agreeUserUsageConditions.

@Override
public AgreeUserUsageConditionsResult agreeUserUsageConditions(AgreeUserUsageConditionsRequest request) {
    Preconditions.checkNotNull(request);
    Preconditions.checkArgument(StringUtils.isNotBlank(request.nickname));
    Preconditions.checkArgument(StringUtils.isNotBlank(request.userUsageConditionsCode));
    final ObjectContext context = serverRuntime.newContext();
    User user = User.getByNickname(context, request.nickname);
    if (!permissionEvaluator.hasPermission(SecurityContextHolder.getContext().getAuthentication(), user, Permission.USER_AGREE_USAGE_CONDITIONS)) {
        throw new AccessDeniedException("unable to agree user usage conditions for user [" + user + "]");
    }
    // remove any existing agreement
    user.getUserUsageConditionsAgreements().forEach(uuca -> uuca.setActive(false));
    UserUsageConditionsAgreement agreement = context.newObject(UserUsageConditionsAgreement.class);
    agreement.setUser(user);
    agreement.setTimestampAgreed();
    agreement.setUserUsageConditions(UserUsageConditions.getByCode(context, request.userUsageConditionsCode));
    context.commitChanges();
    LOGGER.info("did agree to user usage conditions [{}]", request.userUsageConditionsCode);
    return new AgreeUserUsageConditionsResult();
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) User(org.haiku.haikudepotserver.dataobjects.User) UserUsageConditionsAgreement(org.haiku.haikudepotserver.dataobjects.UserUsageConditionsAgreement) ObjectContext(org.apache.cayenne.ObjectContext)

Example 39 with User

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

the class AuthorizationApiIT method checkAuthorizationRequest_asUserWithRule.

/**
 * <P>With a user-pkg rule in place we should see this authorization come through in a check
 * for that permission against the package being true.</P>
 */
@Test
public void checkAuthorizationRequest_asUserWithRule() {
    integrationTestSupportService.createStandardTestData();
    {
        ObjectContext context = serverRuntime.newContext();
        User user1 = integrationTestSupportService.createBasicUser(context, "testuser1", "fakepassword");
        integrationTestSupportService.agreeToUserUsageConditions(context, user1);
        Pkg pkg1 = Pkg.tryGetByName(context, "pkg1").get();
        org.haiku.haikudepotserver.dataobjects.Permission permission = org.haiku.haikudepotserver.dataobjects.Permission.getByCode(context, Permission.PKG_EDITICON.name().toLowerCase()).get();
        PermissionUserPkg pup_u1p1 = context.newObject(PermissionUserPkg.class);
        pup_u1p1.setPkg(pkg1);
        pup_u1p1.setUser(user1);
        pup_u1p1.setPermission(permission);
        context.commitChanges();
    }
    CheckAuthorizationRequest request = new CheckAuthorizationRequest();
    request.targetAndPermissions = new ArrayList<>();
    request.targetAndPermissions.add(new CheckAuthorizationRequest.AuthorizationTargetAndPermission(AuthorizationTargetType.PKG, "pkg1", Permission.PKG_EDITICON.name()));
    setAuthenticatedUser("testuser1");
    // ------------------------------------
    CheckAuthorizationResult result = authorizationApi.checkAuthorization(request);
    // ------------------------------------
    Assertions.assertThat(result.targetAndPermissions.size()).isEqualTo(1);
    Assertions.assertThat(result.targetAndPermissions.get(0).authorized).isTrue();
}
Also used : User(org.haiku.haikudepotserver.dataobjects.User) Permission(org.haiku.haikudepotserver.security.model.Permission) CheckAuthorizationResult(org.haiku.haikudepotserver.api1.model.authorization.CheckAuthorizationResult) ObjectContext(org.apache.cayenne.ObjectContext) CheckAuthorizationRequest(org.haiku.haikudepotserver.api1.model.authorization.CheckAuthorizationRequest) Pkg(org.haiku.haikudepotserver.dataobjects.Pkg) PermissionUserPkg(org.haiku.haikudepotserver.dataobjects.PermissionUserPkg) PermissionUserPkg(org.haiku.haikudepotserver.dataobjects.PermissionUserPkg) AbstractIntegrationTest(org.haiku.haikudepotserver.AbstractIntegrationTest) Test(org.junit.jupiter.api.Test)

Example 40 with User

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

the class JobApiIT method testSearchJobs_userOnly.

@Test
public void testSearchJobs_userOnly() {
    {
        ObjectContext context = serverRuntime.newContext();
        // language is english
        User user = integrationTestSupportService.createBasicUser(context, "testuser", "yUe4o2Nwe009");
        integrationTestSupportService.agreeToUserUsageConditions(context, user);
        setAuthenticatedUser("testuser");
    }
    SearchJobsRequest request = new SearchJobsRequest();
    request.ownerUserNickname = "testuser";
    // ------------------------------------
    SearchJobsResult result = jobApi.searchJobs(request);
    // ------------------------------------
    Assertions.assertThat(result.items.size()).isEqualTo(1);
    SearchJobsResult.Job job = result.items.get(0);
    Assertions.assertThat(job.guid).isEqualTo("finished");
    Assertions.assertThat(job.queuedTimestamp.longValue()).isEqualTo(TestJobServiceImpl.DT_1976_APR.toEpochMilli());
    Assertions.assertThat(job.startTimestamp.longValue()).isEqualTo(TestJobServiceImpl.DT_1976_JUN.toEpochMilli());
    Assertions.assertThat(job.finishTimestamp.longValue()).isEqualTo(TestJobServiceImpl.DT_1976_JUL.toEpochMilli());
    Assertions.assertThat(job.ownerUserNickname).isEqualTo("testuser");
    Assertions.assertThat(job.jobStatus).isEqualTo(JobStatus.FINISHED);
}
Also used : User(org.haiku.haikudepotserver.dataobjects.User) SearchJobsRequest(org.haiku.haikudepotserver.api1.model.job.SearchJobsRequest) SearchJobsResult(org.haiku.haikudepotserver.api1.model.job.SearchJobsResult) ObjectContext(org.apache.cayenne.ObjectContext) AbstractIntegrationTest(org.haiku.haikudepotserver.AbstractIntegrationTest) Test(org.junit.jupiter.api.Test)

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