No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Asignar roles a usuario

14/23
Recursos

Aportes 8

Preguntas 3

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

Inserts:


insert into user_role (username, role, granted_date)
values ('admin','ADMIN',NOW());

insert into user_role (username, role, granted_date)
values ('customer','CUSTOMER',NOW());
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.io.Serializable;
import java.util.Objects;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class UserRoleId implements Serializable {
    private String username;
    private String role;

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof UserRoleId that)) return false;
        return Objects.equals(username, that.username) && Objects.equals(role, that.role);
    }

    @Override
    public int hashCode() {
        return Objects.hash(username, role);
    }
}
package com.platzi.pizza.persistence.entity;

import jakarta.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.time.LocalDateTime;

@Entity
@Table(name = "user_role")
@IdClass(UserRoleId.class)
@Getter
@Setter
@NoArgsConstructor
public class UserRoleEntity {

    @Id
    @Column(nullable = false, length = 20)
    private String username;

    @Id
    @Column(nullable = false, length = 20)
    private String role;

    @Column(name = "granted_date", nullable = false, columnDefinition = "DATETIME")
    private LocalDateTime grantedDate;

    @ManyToOne
    @JoinColumn(name = "username", referencedColumnName = "username", insertable = false, updatable = false)
    private UserEntity user;
}

UserRoleEntity ```js package com.platzi.pizzeria.persistence.entity; import jakarta.persistence.*; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.time.LocalDateTime; @Entity @Table(name = "user_role") @IdClass(UserRoleId.class) @Getter @Setter @NoArgsConstructor public class UserRoleEntity { @Id @Column(nullable = false, length = 20) private String username; @Id @Column(nullable = false, length = 20) private String role; @Column(name = "granted_date", nullable = false, columnDefinition = "DATETIME") private LocalDateTime grantedDate; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "username", referencedColumnName = "username", insertable = false, updatable = false) private UserEntity user; } ``` U ```js package com.platzi.pizzeria.persistence.entity; import jakarta.persistence.*; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.util.List; @Entity @Table(name = "user") @Getter @Setter @NoArgsConstructor public class UserEntity { @Id @Column(nullable = false, length = 20) private String username; @Column(nullable = false, length = 200) private String password; @Column(length = 50) private String email; @Column(nullable = false, columnDefinition = "TINYINT") private Boolean locked; @Column(nullable = false, columnDefinition = "TINYINT") private Boolean disabled; @OneToMany(mappedBy = "user", fetch = FetchType.EAGER) private List<UserRoleEntity> roles; } ``` UserRoleId ```js package com.platzi.pizzeria.persistence.entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.io.Serializable; import java.util.Objects; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class UserRoleId implements Serializable { private String username; private String role; @Override public boolean equals(Object o) { if(this == o) return true; if(!(o instanceof UserRoleId that)) return false; return Objects.equals(username, that.username) && Objects.equals(role, that.role); } @Override public int hashCode() { return Objects.hash(username, role); } } ``` UserSecuriryService ```js package com.platzi.pizzeria.service; import com.platzi.pizzeria.persistence.entity.UserEntity; import com.platzi.pizzeria.persistence.entity.UserRoleEntity; import com.platzi.pizzeria.persistence.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class UserSecurityService implements UserDetailsService { private final UserRepository userRepository; @Autowired public UserSecurityService(UserRepository userRepository) { this.userRepository = userRepository; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserEntity userEntity = this.userRepository.findById(username) .orElseThrow(() -> new UsernameNotFoundException("User + " + username + " NOT FOUND")); String[] roles = userEntity.getRoles().stream().map(UserRoleEntity::getRole).toArray(String[]::new); return User.builder() .username(userEntity.getUsername()) .password(userEntity.getPassword()) .roles(roles) .accountLocked(userEntity.getLocked()) .disabled(userEntity.getDisabled()) .build(); } } ```
Otra forma de convertir un objeto del tipo List\<T> a un objeto del tipo T\[]: ```java String[] roles = userEntity.getRoles().toArray(new String[userEntity.getRoles().size()]); ```String\[] roles = userEntity.getRoles().toArray(new String\[userEntity.getRoles().size()]);
Otra forma de convertir un objeto de tipo List\<T> a un array del tipo T\[]: `String[] roles = userEntity.getRoles().toArray(new String[userEntity.getRoles().size()]);`

✅

package com.platzi.pizza.persistence.entity;

import jakarta.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.List;

@Entity
@Table(name = "user")
@Getter
@Setter
@NoArgsConstructor
public class UserEntity {
    @Id
    @Column(nullable = false, length = 20)
    private String username;

    @Column(nullable = false, length = 200)
    private String password;

    @Column(length = 50)
    private String email;

    @Column(nullable = false, columnDefinition = "TINYINT")
    private Boolean locked;

    @Column(nullable = false, columnDefinition = "TINYINT")
    private Boolean disabled;

    @OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
    private List<UserRoleEntity> roles;
}