JHipster get the current user

梦想与她 提交于 2019-12-03 23:13:04

I did something similar: In xxxResource.java:

 public String getCurrentUserLogin() {
        org.springframework.security.core.context.SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        String login = null;
        if (authentication != null)
            if (authentication.getPrincipal() instanceof UserDetails)
             login = ((UserDetails) authentication.getPrincipal()).getUsername();
            else if (authentication.getPrincipal() instanceof String)
             login = (String) authentication.getPrincipal();

        return login; 
        }

then before xxxRepository.save add:

 User user=new User();
 user=UserRepository.findOneByLogin(getCurrentUserLogin()).get();
 Order.setUser(user);

See https://codefitter2.blogspot.com/2016/12/how-to-add-user-to-new-record-in.html

If I understood correctly, you have a Study which has a relationship with User and when you retrieve a Study object: study.user is undefined in your problem in angular code.

You can't trust angular code, so User selection cannot be in client when creating a Study, so you should ignore it in StudyMapper (assuming you use DTOs) or StudyService should overwrite it.

JHipster creates views and APIs that are for administrators. In your case you want to build an API for simple users who are only allowed to manage their own studies, if you try to address both use cases in same classes your code could get messy and you may introduce security flaws. So I'd suggest that you split the 2 APIs and probably views unless you want to drop the admin part. By having StudyResource on/api/study for admins and MyStudyResource on /api/user/study, you can protect them differently by role and avoid the issues you have in view because you'll have a well-defined context rather than putting if/then/else all a round.

Another reason to do so is that it makes easier to upgrade JHipster generated code using jhipster upgradecommand.

JHipster does not design your API because it does know about your business domain. It provides you with a CRUD interface to manage data above a REST API and entities from a technical standpoint. This is why it maps one resource per entity rather than aggregates which are what you end up with when you analyze your business domain using DDD. Aggregates are better also in terms of performance especially for mobile clients because you end up making less API calls.

You could also add an API using https://github.com/cbornet/generator-jhipster-swagger-api-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!