Search in sources :

Example 31 with User

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

the class PasswordResetServiceImpl method complete.

@Override
public void complete(String tokenCode, String passwordClear) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(tokenCode), "the token code must be provided");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(passwordClear), "the pssword clear must be provided");
    Instant now = Instant.now();
    try {
        if (!Strings.isNullOrEmpty(tokenCode)) {
            ObjectContext context = serverRuntime.newContext();
            Optional<UserPasswordResetToken> tokenOptional = UserPasswordResetToken.getByCode(context, tokenCode);
            if (tokenOptional.isPresent()) {
                try {
                    UserPasswordResetToken token = tokenOptional.get();
                    if (token.getCreateTimestamp().getTime() > now.minus(timeToLiveHours, ChronoUnit.HOURS).toEpochMilli()) {
                        User user = token.getUser();
                        if (user.getActive()) {
                            if (!Strings.isNullOrEmpty(passwordClear) && userAuthenticationService.validatePassword(passwordClear)) {
                                userAuthenticationService.setPassword(user, passwordClear);
                                context.deleteObjects(token);
                                context.commitChanges();
                                LOGGER.info("did reset the password for; {}", user.toString());
                            } else {
                                LOGGER.warn("the password has been supplied as invalid; will ignore");
                            }
                        } else {
                            LOGGER.warn("the user having their password reset is inactive; will ignore");
                        }
                    } else {
                        LOGGER.warn("the token used to reset the password is expired; will ignore");
                    }
                } finally {
                    // open a new context so that just in case something goes wrong / invalid in the other context,
                    // that the deletion of the token can still proceed.
                    ObjectContext deleteContext = serverRuntime.newContext();
                    Optional<UserPasswordResetToken> deleteTokenOptional = UserPasswordResetToken.getByCode(deleteContext, tokenCode);
                    if (deleteTokenOptional.isPresent()) {
                        deleteContext.deleteObjects(deleteTokenOptional.get());
                        deleteContext.commitChanges();
                        LOGGER.info("did delete user password reset token {} after having processed it", tokenCode);
                    }
                }
            } else {
                LOGGER.warn("unable to find the user password reset token {}; will ignore", tokenCode);
            }
        } else {
            LOGGER.warn("the code has been supplied as null when attempting to reset a password; will ignore");
        }
    } catch (Throwable th) {
        LOGGER.error("unable to reset the password from a token", th);
    }
}
Also used : User(org.haiku.haikudepotserver.dataobjects.User) UserPasswordResetToken(org.haiku.haikudepotserver.dataobjects.UserPasswordResetToken) Instant(java.time.Instant) ObjectContext(org.apache.cayenne.ObjectContext)

Example 32 with User

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

the class PkgJobApiImpl method queuePkgIconArchiveImportJob.

@Override
public QueuePkgIconArchiveImportJobResult queuePkgIconArchiveImportJob(QueuePkgIconArchiveImportJobRequest request) {
    Preconditions.checkArgument(null != request, "the request must be supplied");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(request.inputDataGuid), "the input data must be identified by guid");
    final ObjectContext context = serverRuntime.newContext();
    Optional<User> user = tryObtainAuthenticatedUser(context);
    if (!permissionEvaluator.hasPermission(SecurityContextHolder.getContext().getAuthentication(), null, Permission.BULK_PKGICONIMPORTARCHIVE)) {
        throw new AccessDeniedException("attempt to import package icons, but was not authorized");
    }
    // now check that the data is present.
    jobService.tryGetData(request.inputDataGuid).orElseThrow(() -> new ObjectNotFoundException(JobData.class.getSimpleName(), request.inputDataGuid));
    // setup and go
    PkgIconImportArchiveJobSpecification spec = new PkgIconImportArchiveJobSpecification();
    spec.setOwnerUserNickname(user.map(_User::getNickname).orElse(null));
    spec.setInputDataGuid(request.inputDataGuid);
    return new QueuePkgIconArchiveImportJobResult(jobService.submit(spec, JobSnapshot.COALESCE_STATUSES_NONE));
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) org.haiku.haikudepotserver.dataobjects.auto._User(org.haiku.haikudepotserver.dataobjects.auto._User) User(org.haiku.haikudepotserver.dataobjects.User) ObjectNotFoundException(org.haiku.haikudepotserver.api1.support.ObjectNotFoundException) org.haiku.haikudepotserver.dataobjects.auto._User(org.haiku.haikudepotserver.dataobjects.auto._User) ObjectContext(org.apache.cayenne.ObjectContext)

Example 33 with User

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

the class PkgJobApiImpl method queuePkgScreenshotArchiveImportJob.

@Override
public QueuePkgScreenshotArchiveImportJobResult queuePkgScreenshotArchiveImportJob(QueuePkgScreenshotArchiveImportJobRequest request) {
    Preconditions.checkArgument(null != request, "the request must be supplied");
    Preconditions.checkArgument(StringUtils.isNotBlank(request.inputDataGuid), "the data guid must be supplied");
    Preconditions.checkArgument(null != request.importStrategy, "the import strategy must be supplied");
    final ObjectContext context = serverRuntime.newContext();
    Optional<User> user = tryObtainAuthenticatedUser(context);
    if (!permissionEvaluator.hasPermission(SecurityContextHolder.getContext().getAuthentication(), null, Permission.BULK_PKGSCREENSHOTIMPORTARCHIVE)) {
        throw new AccessDeniedException("attempt to import package screenshots, but was not authorized");
    }
    // now check that the data is present.
    jobService.tryGetData(request.inputDataGuid).orElseThrow(() -> new ObjectNotFoundException(JobData.class.getSimpleName(), request.inputDataGuid));
    // setup and go
    PkgScreenshotImportArchiveJobSpecification spec = new PkgScreenshotImportArchiveJobSpecification();
    spec.setOwnerUserNickname(user.map(_User::getNickname).orElse(null));
    spec.setInputDataGuid(request.inputDataGuid);
    spec.setImportStrategy(PkgScreenshotImportArchiveJobSpecification.ImportStrategy.valueOf(request.importStrategy.name()));
    return new QueuePkgScreenshotArchiveImportJobResult(jobService.submit(spec, JobSnapshot.COALESCE_STATUSES_NONE));
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) org.haiku.haikudepotserver.dataobjects.auto._User(org.haiku.haikudepotserver.dataobjects.auto._User) User(org.haiku.haikudepotserver.dataobjects.User) ObjectNotFoundException(org.haiku.haikudepotserver.api1.support.ObjectNotFoundException) org.haiku.haikudepotserver.dataobjects.auto._User(org.haiku.haikudepotserver.dataobjects.auto._User) ObjectContext(org.apache.cayenne.ObjectContext)

Example 34 with User

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

the class UserApiImpl method createUser.

@Override
public CreateUserResult createUser(CreateUserRequest createUserRequest) throws InvalidUserUsageConditionsException {
    Preconditions.checkNotNull(createUserRequest);
    Preconditions.checkState(!Strings.isNullOrEmpty(createUserRequest.nickname));
    Preconditions.checkState(!Strings.isNullOrEmpty(createUserRequest.passwordClear));
    Preconditions.checkState(!Strings.isNullOrEmpty(createUserRequest.captchaToken));
    Preconditions.checkState(!Strings.isNullOrEmpty(createUserRequest.captchaResponse), "a capture response is required to create a user");
    Preconditions.checkState(!Strings.isNullOrEmpty(createUserRequest.naturalLanguageCode));
    if (!userAuthenticationService.validatePassword(createUserRequest.passwordClear)) {
        throw new ValidationException(new ValidationFailure("passwordClear", "invalid"));
    }
    if (!captchaService.verify(createUserRequest.captchaToken, createUserRequest.captchaResponse)) {
        throw new CaptchaBadResponseException();
    }
    if (Strings.isNullOrEmpty(createUserRequest.nickname)) {
        throw new ValidationException(new ValidationFailure(User.NICKNAME.getName(), "required"));
    }
    if (StringUtils.isBlank(createUserRequest.userUsageConditionsCode)) {
        throw new InvalidUserUsageConditionsException();
    }
    final ObjectContext context = serverRuntime.newContext();
    String latestUserUsageConditionsCode = UserUsageConditions.getLatest(context).getCode();
    if (!latestUserUsageConditionsCode.equals(createUserRequest.userUsageConditionsCode)) {
        throw new InvalidUserUsageConditionsException();
    }
    UserUsageConditions userUsageConditions = UserUsageConditions.getByCode(context, createUserRequest.userUsageConditionsCode);
    if (User.tryGetByNickname(context, createUserRequest.nickname).isPresent()) {
        throw new ValidationException(new ValidationFailure(User.NICKNAME.getName(), "notunique"));
    }
    User user = context.newObject(User.class);
    user.setNaturalLanguage(getNaturalLanguage(context, createUserRequest.naturalLanguageCode));
    user.setNickname(createUserRequest.nickname);
    user.setEmail(createUserRequest.email);
    userAuthenticationService.setPassword(user, createUserRequest.passwordClear);
    UserUsageConditionsAgreement agreement = context.newObject(UserUsageConditionsAgreement.class);
    agreement.setUser(user);
    agreement.setTimestampAgreed();
    agreement.setUserUsageConditions(userUsageConditions);
    context.commitChanges();
    LOGGER.info("data create user; {}", user.getNickname());
    return new CreateUserResult();
}
Also used : UserUsageConditions(org.haiku.haikudepotserver.dataobjects.UserUsageConditions) User(org.haiku.haikudepotserver.dataobjects.User) UserUsageConditionsAgreement(org.haiku.haikudepotserver.dataobjects.UserUsageConditionsAgreement) ObjectContext(org.apache.cayenne.ObjectContext)

Example 35 with User

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

the class UserApiImpl method getUser.

@Override
public GetUserResult getUser(GetUserRequest getUserRequest) {
    Preconditions.checkNotNull(getUserRequest);
    Preconditions.checkState(!Strings.isNullOrEmpty(getUserRequest.nickname));
    final ObjectContext context = serverRuntime.newContext();
    User user = User.tryGetByNickname(context, getUserRequest.nickname).orElseThrow(() -> new ObjectNotFoundException(User.class.getSimpleName(), User.NICKNAME.getName()));
    if (!permissionEvaluator.hasPermission(SecurityContextHolder.getContext().getAuthentication(), user, Permission.USER_VIEW)) {
        throw new AccessDeniedException("unable to view user [" + user + "]");
    }
    GetUserResult result = new GetUserResult();
    result.nickname = user.getNickname();
    result.email = user.getEmail();
    result.isRoot = user.getIsRoot();
    result.active = user.getActive();
    result.naturalLanguageCode = user.getNaturalLanguage().getCode();
    result.createTimestamp = user.getCreateTimestamp().getTime();
    result.modifyTimestamp = user.getModifyTimestamp().getTime();
    result.lastAuthenticationTimestamp = Optional.ofNullable(user.getLastAuthenticationTimestamp()).map(Timestamp::getTime).orElse(null);
    user.tryGetUserUsageConditionsAgreement().ifPresent(uuca -> {
        result.userUsageConditionsAgreement = new GetUserResult.UserUsageConditionsAgreement();
        result.userUsageConditionsAgreement.timestampAgreed = uuca.getTimestampAgreed().getTime();
        result.userUsageConditionsAgreement.userUsageConditionsCode = uuca.getUserUsageConditions().getCode();
        result.userUsageConditionsAgreement.isLatest = uuca.getUserUsageConditions().getCode().equals(UserUsageConditions.getLatest(context).getCode());
    });
    return result;
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) User(org.haiku.haikudepotserver.dataobjects.User) ObjectContext(org.apache.cayenne.ObjectContext) Timestamp(java.sql.Timestamp)

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