All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.elepy.admin.services.UserUpdate Maven / Gradle / Ivy

There is a newer version: 3.0.0-alpha-29
Show newest version
package com.elepy.admin.services;

import com.elepy.admin.ElepyAdminPanel;
import com.elepy.admin.models.User;
import com.elepy.dao.Crud;
import com.elepy.describers.ModelDescription;
import com.elepy.evaluators.DefaultIntegrityEvaluator;
import com.elepy.evaluators.DefaultObjectUpdateEvaluator;
import com.elepy.evaluators.ObjectEvaluator;
import com.elepy.exceptions.ElepyException;
import com.elepy.http.HttpContext;
import com.elepy.routes.UpdateHandler;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Optional;

public class UserUpdate implements UpdateHandler {

    @Override
    public void handleUpdatePut(HttpContext context, Crud crud, ModelDescription modelDescription, ObjectMapper objectMapper) throws Exception {
        String body = context.request().body();
        User loggedInUser = context.request().session().attribute(ElepyAdminPanel.ADMIN_USER);
        User updated = objectMapper.readValue(body, modelDescription.getModelType());

        Optional before = crud.getById(crud.getId(updated));

        if (!before.isPresent()) {
            context.response().status(404);
            throw new ElepyException("No object found with this ID");
        }
        if (!loggedInUser.getId().equals(updated.getId())) {
            if (!loggedInUser.getUserType().hasMoreRightsThan(updated.getUserType()) || !loggedInUser.getUserType().hasMoreRightsThan(before.get().getUserType())) {
                throw new ElepyException("You are not allowed to update users with an equal or higher rank than you!");
            }
        } else {
            if (!loggedInUser.getUserType().equals(updated.getUserType())) {
                throw new ElepyException("You can't promote/demote yourself!");

            }
        }

        DefaultObjectUpdateEvaluator updateEvaluator = new DefaultObjectUpdateEvaluator<>();

        updateEvaluator.evaluate(before.get(), updated);

        for (ObjectEvaluator objectEvaluator : modelDescription.getObjectEvaluators()) {
            objectEvaluator.evaluate(updated, User.class);
        }
        new DefaultIntegrityEvaluator().evaluate(updated, crud);
        if (!updated.getPassword().equals(before.get().getPassword())) {
            updated = updated.hashWord();
        }


        crud.update(updated);
        context.response().status(200);
        context.response().result("The item is updated");
    }

    @Override
    public void handleUpdatePatch(HttpContext context, Crud crud, ModelDescription modelDescription, ObjectMapper objectMapper) throws Exception {
        handleUpdatePut(context, crud, modelDescription, objectMapper);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy