getting the current logged in user in JHipster

2019-01-20 16:42发布

问题:

I am building a jhipster application. and I am trying to get a list of objects based on the current logged in user. there are a few simple examples online such as jhipster blog demo that describe how to get the current user's blogs by the current logged in user--and I wanted to mimic this. in the demo there isa repo method:

@Query("select blog from Blog blog where blog.user.login = ?#{principal.username}")
List<Blog> findByUserIsCurrentUser();

I have tried to mimic this with the following:

@Query("select userWorkoutTemplate from WorkoutTemplate workoutTemplate where workoutTemplate.userDemographic.user.login = ?#{principal.username}")
List<WorkoutTemplateDTO> findByUserIsCurrentUser();

but my IDE throws this error:

nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.thefitnation.repository.WorkoutTemplateRepository.findByUserIsCurrentUser()!

I am not too familiar with hibernate queries, but the parameter seems to be in error in my IDE. Does the parameter on the end need to be configured somewhere? I am using plain jhipster 4 out of the box with DTO objects.

here are the relevant entities:

User.java

@Entity
@Table(name = "jhi_user")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User extends AbstractAuditingEntity implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;

@NotNull
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
@Column(length = 50, unique = true, nullable = false)
private String login;

@JsonIgnore
@NotNull
@Size(min = 60, max = 60)
@Column(name = "password_hash",length = 60)
private String password;

@Size(max = 50)
@Column(name = "first_name", length = 50)
private String firstName;

@Size(max = 50)
@Column(name = "last_name", length = 50)
private String lastName;

@Email
@Size(max = 100)
@Column(length = 100, unique = true)
private String email;

@NotNull
@Column(nullable = false)
private boolean activated = false;

@Size(min = 2, max = 5)
@Column(name = "lang_key", length = 5)
private String langKey;

@Size(max = 256)
@Column(name = "image_url", length = 256)
private String imageUrl;

@Size(max = 20)
@Column(name = "activation_key", length = 20)
@JsonIgnore
private String activationKey;

@Size(max = 20)
@Column(name = "reset_key", length = 20)
private String resetKey;

@Column(name = "reset_date")
private ZonedDateTime resetDate = null;

@JsonIgnore
@ManyToMany
@JoinTable(
    name = "jhi_user_authority",
    joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
    inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")})
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@BatchSize(size = 20)
private Set<Authority> authorities = new HashSet<>();
....

UserDemographic.java

@Entity
@Table(name = "user_demographic")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class UserDemographic implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;

@NotNull
@Column(name = "created_on", nullable = false)
private LocalDate createdOn;

@NotNull
@Column(name = "last_login", nullable = false)
private LocalDate lastLogin;

@Enumerated(EnumType.STRING)
@Column(name = "gender")
private Gender gender;

@NotNull
@Column(name = "date_of_birth", nullable = false)
private LocalDate dateOfBirth;

@Column(name = "height")
private Float height;

@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "unit_of_measure", nullable = false)
private UnitOfMeasure unitOfMeasure;

@OneToOne(optional = false)
@NotNull
@JoinColumn(unique = true)
private User user;

@ManyToMany
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@JoinTable(name = "user_demographic_gym",
           joinColumns = @JoinColumn(name="user_demographics_id", referencedColumnName="id"),
           inverseJoinColumns = @JoinColumn(name="gyms_id", referencedColumnName="id"))
private Set<Gym> gyms = new HashSet<>();

@OneToMany(mappedBy = "userDemographic")
@JsonIgnore
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<UserWeight> userWeights = new HashSet<>();

@OneToMany(mappedBy = "userDemographic")
@JsonIgnore
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<WorkoutTemplate> workoutTemplates = new HashSet<>();

@OneToMany(mappedBy = "userDemographic")
@JsonIgnore
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<UserWorkoutTemplate> userWorkoutTemplates = new HashSet<>();

@ManyToOne(optional = false)
@NotNull
private SkillLevel skillLevel;

UserWorkoutTemplate.java

@Entity
@Table(name = "user_workout_template")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class UserWorkoutTemplate implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;

@NotNull
@Column(name = "created_on", nullable = false)
private LocalDate createdOn;

@NotNull
@Column(name = "last_updated", nullable = false)
private LocalDate lastUpdated;

@Column(name = "notes")
private String notes;

@ManyToOne(optional = false)
@NotNull
private UserDemographic userDemographic;

@ManyToOne
private WorkoutTemplate workoutTemplate;

@OneToMany(mappedBy = "userWorkoutTemplate", fetch = FetchType.EAGER)
@JsonIgnore
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<UserWorkoutInstance> userWorkoutInstances = new HashSet<>();

回答1:

You can get the current logged in user id from SecurityUtils. SecurityUtils.getCurrentUserLogin() will give you the login of current logged in user. Use this login to fetch the user entity from db. (findOneByLogin)



回答2:

Currently the best answer is to use built-in UserService - the one provided by JHipster. You don't have to repeat calling SecurityUtils.getCurrentUserLogin() twice (once yourself and once in UserService - check implementation). Usage would look like this:

final Optional<User> isUser = userService.getUserWithAuthorities();
if(!isUser.isPresent()) {
   log.error("User is not logged in");
   return new Shinything()
}

final User user = isUser.get();
// continue with the user


回答3:

You can get User from userService.getUserWithAuthorities().get();