com.xlrit.gears.server.graphql.IdentityResolver Maven / Gradle / Ivy
package com.xlrit.gears.server.graphql;
import java.util.List;
import com.xlrit.gears.base.model.Role;
import com.xlrit.gears.base.model.User;
import com.xlrit.gears.base.repository.RoleRepository;
import com.xlrit.gears.base.repository.UserRepository;
import com.xlrit.gears.engine.security.AuthManager;
import com.xlrit.gears.server.security.TokenManager;
import graphql.schema.DataFetchingEnvironment;
import graphql.schema.DataFetchingFieldSelectionSet;
import jakarta.persistence.EntityGraph;
import jakarta.persistence.EntityManager;
import lombok.RequiredArgsConstructor;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.MutationMapping;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.graphql.data.method.annotation.SchemaMapping;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
@Controller
@RequiredArgsConstructor
public class IdentityResolver {
private final EntityManager entityManager;
private final UserRepository userRepository;
private final RoleRepository roleRepository;
private final AuthManager authManager;
private final TokenManager tokenManager;
// === queries === //
@QueryMapping
public User currentUser(DataFetchingEnvironment env) {
String id = authManager.getCurrentUserId();
if (id == null) return null;
EntityGraph loadGraph = createUserEntityGraph(env.getSelectionSet());
return userRepository.findById(id, loadGraph);
}
@QueryMapping
@PreAuthorize("hasRole('admin')")
public List users(DataFetchingEnvironment env) {
EntityGraph loadGraph = createUserEntityGraph(env.getSelectionSet());
return userRepository.findAll(loadGraph);
}
private EntityGraph createUserEntityGraph(DataFetchingFieldSelectionSet selectionSet) {
EntityGraph eg = entityManager.createEntityGraph(User.class);
if (selectionSet.containsAnyOf("roles", "isAdmin")) {
eg.addAttributeNodes("roles");
}
return eg;
}
@QueryMapping
@PreAuthorize("hasRole('admin')")
public List roles() {
return roleRepository.findAll();
}
@SchemaMapping
public boolean isAdmin(User user) {
return User.getRoleNames(user).contains(AuthManager.ADMIN);
}
// === mutations === //
@MutationMapping
public String login(@Argument String username, @Argument String password) {
return tokenManager.createToken(username, password);
}
}