80 lines
2.5 KiB
Java
80 lines
2.5 KiB
Java
package dev.dinauer;
|
|
|
|
import dev.dinauer.login.User;
|
|
import dev.dinauer.login.UserEntity;
|
|
import dev.dinauer.login.UserRepo;
|
|
import io.quarkus.elytron.security.common.BcryptUtil;
|
|
import io.quarkus.security.Authenticated;
|
|
import io.quarkus.security.identity.SecurityIdentity;
|
|
import jakarta.enterprise.context.ApplicationScoped;
|
|
import jakarta.inject.Inject;
|
|
import jakarta.transaction.Transactional;
|
|
import jakarta.ws.rs.*;
|
|
import jakarta.ws.rs.core.MediaType;
|
|
|
|
import java.io.IOException;
|
|
import java.util.Optional;
|
|
import java.util.Set;
|
|
|
|
@Path("/users")
|
|
@ApplicationScoped
|
|
@Authenticated
|
|
public class UserResource
|
|
{
|
|
@Inject
|
|
UserRepo userRepo;
|
|
|
|
@Inject
|
|
SecurityIdentity securityIdentity;
|
|
|
|
@GET
|
|
@Produces(MediaType.APPLICATION_JSON)
|
|
@Path("/{username}")
|
|
public User getUser(@PathParam("username") String id)
|
|
{
|
|
Optional<UserEntity> userOptional = userRepo.findByIdOptional(id);
|
|
if (userOptional.isPresent())
|
|
{
|
|
UserEntity user = userOptional.get();
|
|
return new User(user.getUsername(), user.getEmail(), user.getRoles(), null);
|
|
}
|
|
throw new NotFoundException();
|
|
}
|
|
|
|
@POST
|
|
@Produces(MediaType.APPLICATION_JSON)
|
|
@Consumes(MediaType.APPLICATION_JSON)
|
|
@Transactional
|
|
public void createUser(User user)
|
|
{
|
|
UserEntity userEntity = UserEntity.init();
|
|
userEntity.setUsername(user.username());
|
|
userEntity.setPassword(BcryptUtil.bcryptHash(user.password()));
|
|
userEntity.setRoles(Set.of("user"));
|
|
userEntity.setEmail(user.email());
|
|
userRepo.persist(userEntity);
|
|
}
|
|
|
|
@PUT
|
|
@Path("/{username}/password")
|
|
@Produces
|
|
@Consumes(MediaType.TEXT_PLAIN)
|
|
@Transactional
|
|
public void changePassword(@PathParam("username") String username, String password) throws IOException
|
|
{
|
|
Optional<UserEntity> persistentUserOptional = userRepo.findOptionalByUsername(username);
|
|
if(persistentUserOptional.isPresent() && password != null && !password.isBlank())
|
|
{
|
|
UserEntity persistentUser = persistentUserOptional.get();
|
|
if(securityIdentity.getPrincipal().getName().equals(persistentUser.getUsername()))
|
|
{
|
|
persistentUser.setPassword(BcryptUtil.bcryptHash(password));
|
|
userRepo.persist(persistentUser);
|
|
return;
|
|
}
|
|
throw new ForbiddenException();
|
|
}
|
|
throw new BadRequestException("no_password_provided");
|
|
}
|
|
}
|