Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / NewStats: 3,151,062 members, 7,810,954 topics. Date: Saturday, 27 April 2024 at 07:25 PM |
Nairaland Forum / Science/Technology / Programming / SQL Query That Displays A List Assigned Only To Only The Logged In User Java (1559 Views)
SQL Query Interview Questions / Top 20 Websites To Learn Coding With Java, Python, SQL, Algorithms, And Git For / Java EE Developer And Spring Developer In Here. (2) (3) (4)
SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 1:00pm On Nov 09, 2021 |
I have a set of Users with different role types Marketer , Admin, General Manager. When a customer account is registered , there is a column that gets the name of the Marketer assigned to the Customer . I have created a @ManyToOne and @OneToMany relationship between Users and Customers. When User type Marketer logs in to the software , I want the marketer to see only customers registered to the logged in Marketer name. It seems complicated because first I need to get the logged in Marketer details using the username then get the first and last name then display customer list assigned to the name. Please help i need to deliver the project soon. This is the Customer entity @Entity @JsonIgnoreProperties({"hibernateLazyInitializer","handler"}) public class Customer implements Serializable { /** * */ private static final long serialVersionUID = 8348682056500740593L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private String userName; private String password; private String firstName ; private String lastName; private String gender; private String Address; private String idNumber; private String phoneNumber; private String email; @DateTimeFormat(pattern = "yyyy-MM-dd" private Date dateOfBirth; @DateTimeFormat(pattern = "yyyy-MM-dd" private Date registrationDate; @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) @ManyToOne(targetEntity = User.class, fetch = FetchType.LAZY ) @JoinColumn(name="marketer_id" private User marketer ; @JsonBackReference @OneToMany(mappedBy="customer_id",cascade = CascadeType.ALL, targetEntity=Investment.class) private List <Investment> investment; This is the User Entity @Entity public class User { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private String firstName ; private String lastName; private String username; private String password; @DateTimeFormat(pattern = "yyyy-MM-dd" private Date createdDate; @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinTable( name = "users_roles", joinColumns = @JoinColumn(name = "user_id", inverseJoinColumns = @JoinColumn(name = "role_id" ) private Set<UserRole> userRole = new HashSet<>(); @Enumerated(EnumType.STRING) private UserStatus status; @JsonBackReference @OneToMany(mappedBy="marketer",cascade = CascadeType.ALL, targetEntity=Customer.class) private List <Customer> customer; This is the User Repository that contains a FindByUsername method that's being used by JWT authentication manager @Repository public interface UserAccountRepository extends JpaRepository <User, Long> { Optional<User> findById(Long id); User findByUsername(String username); } |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by richebony: 4:54pm On Nov 09, 2021 |
I think you should paste the rest endpoint where you make the API call .. To get the current user you can leverage on the Authentication object passed as a paramter on the handler and invoke the getPrincipal () method ...When you get the currently logged in user ,create a custom implementation on the repo .or better still you can use @Prefilter and filter based on the currently logged in user on the handler |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 9:50pm On Nov 09, 2021 |
richebony: Thanks very much for the response . I already have a custom implementation on the customer repo here it is . @Query("select customer from Customer customer join customer.marketer marketer where marketer = :marketer" List<Customer> findByMarketer(User marketer); Now what I am thinking is how the passed :marketer parameter in the query get the logged in marketer name and display the Customers registered with the marketer's name. Thanks much I really appreciate your reply. I'll as well look into the getPrincipal method from spring security. Here is the controller where other endpoints are implemented @RestController public class CustomerController { @Autowired CustomerAccountService customerRepo; @GetMapping(value="list/Customers" public List<Customer> getCustomers() { return customerRepo.getCustomers(); } @GetMapping(value = "list/customer/{id}" public Optional<Customer> getCustomer (@PathVariable Long id) { return customerRepo.getCustomer(id); } @DeleteMapping(value="/deleteCustomer/{id}" public void deleteCustomer(@PathVariable Long id) { customerRepo.deleteCustomer(id); } ............................................................................................................................................ |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by richebony: 11:04am On Nov 10, 2021 |
Ok Maybe you can try the attached code
|
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 7:40pm On Nov 10, 2021 |
Thanks much , I'll implement and get back to you with response |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 5:28pm On Nov 12, 2021 |
richebony: I tried running the code but it came back with an empty array response after inspecting the console. I made sure that I logged in with a Marketer type role and spring security detected Authorities type Marketer. Could it be from the authentication.getName parameter of the security context because in my user class what I have is firstName and lastName variables not Name variable ? I plan to refactor and change the first and last name variables to just Name . Do you think that should fix it ? Thanks for your support Jah bless
|
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by Singlecliq: 11:14pm On Nov 12, 2021 |
I can’t provide a Java implementation because I don’t develop on Java, but I believe algorithm should suffice. 1. There should be a middleware than only accepts authenticated request. 2. Save authenticated response of the user to the state. 2. Get the name of the authenticated user. 4. Fetch the customer table with the name, which is the marketer name in this case. |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by richebony: 12:25am On Nov 13, 2021 |
sweetguy10: Ok, I see. If you used spring security for your authentication, authentication.geName() should return the username of the currently logged in user, username here is the username you use for authentication, You can confirm this by logging out the response or placing a breakpoint there if it returns the username of currently logged in user then that step is correct. What I did next was a query to return the User Object using the username as a search parameter. I even see that "customer" is a property in your user class so you can as well just return it (user.getCustomer() will return the customers of the logged-in user which should be a marketer (to ensure this you can use prefilters to make sure only marketers have access to that method , though this is optional )) |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 12:18pm On Nov 15, 2021 |
Singlecliq: Thanks duly appreciated |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 12:27pm On Nov 15, 2021 |
richebony: Turns out that the authentication.getName method returns null values, then I went further by implementing the findByUsername method in the user Repository but it returns a null object values. I deleted all existing data ,refactored and changed username to userName and changed the Repository method to fndByUserName but it still return null values. Presently stuck here and still debugging. Attached are the repository and controller images , there is a UserAccountService service class in between that implemented the repo method and provide to the controller. Thanks
|
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by richebony: 3:54pm On Nov 15, 2021 |
You said you used jwt for your authentication. .can you log in ?..please show me the response it gives when you log in Because the authentication object cannot return null if that path is protected and you have been duly authenticated For that service layer issue ..try querying using the repoObject ..and see the result |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by bet9ja(m): 10:13pm On Nov 15, 2021 |
@PathVariable("username") or @PathVariable String username |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 10:42pm On Nov 15, 2021 |
I refactored the controller method and added @pathvariable to the method parameter beside String username ...got it working
|
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 10:46pm On Nov 15, 2021 |
bet9ja: Fixed it before seeing this , you are absolutely right. appreciate your contribution thanks much. |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 10:57pm On Nov 15, 2021 |
richebony: I think that happened because of spring security UserDetails class that maps to User class and get the Username value directly, might be wrong though. I appreciate your support so far. |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 10:28am On Nov 16, 2021 |
richebony: So I ran a test to get list of Customers assigned to User type Marketer but it still return null values even though the findByUserName in the user repo method is working. I Autowired the UserRepository to the UserService class and did the concrete implementation in the service class , then Imported and Autowired the UserService class to the customer controller to be able to use the findByUsername method and pass the authentication.getName method as a parameter. Where am I getting it wrong ? The last image is to confirm that the findByUserName method in the user repository is functional |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by richebony: 1:31pm On Nov 16, 2021 |
That's why I asked if you were able to log in and the tokens were sent to the headers, if so, please send your Authentication(Token generation) and Authorization filter implementations and also your UserRoles class. If your codes are similar to the attached, then the issue should be from there. Your roles should also implement the GrantedAuthority interface that's the only way you can pass it directly to the returned User class in the UserDetailsServiceImpl.
|
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 1:57pm On Nov 16, 2021 |
richebony: I use a MyUserDetails class that Implements UserDetails and build with the User class , could the problem be from there ? Here are what I have thanks much I appreciate you
|
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 11:24am On Nov 17, 2021 |
richebony: I removed /** from antmatchers parameter and authorized all requests going to marketers/customers endpoint then signed in on postman , it generated a token and I put it in the header then made request call to marketers/customers , returned NullPointerException: null . I noticed that when I tried to use userName it returned a bad credentials response till I changed to username but what I have in my User entity is userName. What could I be doing wrong ? Please forgive my back and forth this is my first huge project with Spring Security.
|
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by richebony: 2:43pm On Nov 17, 2021 |
I think the issue should be in your JWTAuthorizationFilter Class (if you have any ).because on every request the Authentication object should be set by extracting the relevant details from the generated token Something like this jwt = jwt.replace(SecurityConstants.TOKEN_PREFIX, "" SecretKey key = Keys.hmacShaKeyFor(SecurityConstants.JWT_KEY.getBytes(StandardCharsets.UTF_8)); Claims claims = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jwt).getBody(); String username = String.valueOf(claims.get("username"); String authorities = (String) claims.get("authorities" Authentication auth = new UsernamePasswordAuthenticationToken(username, null, AuthorityUtils.commaSeparatedStringToAuthorityList(authorities)); SecurityContextHolder.getContext().setAuthentication(auth); ...and I don't see any filters added to your HttpSecurity configure method in your WebSecurity class There should be something like this http.addFilterAfter(new AuthoritiesLoggingAfterFilter(), BasicAuthenticationFilter.class) .addFilterBefore(new JWTTokenValidatorFilter(), BasicAuthenticationFilter.class) One of the issues with JWT authentication is that there different implementations, a beauty, and a curse. I can give u the one that works for me. It's long and you have to do some major refactoring And for the naming issue, i don't really get it but the difference between userName and username is that hibernate would map requests with userName to the column named "user_name", while username will be mapped to "username" And please change your antMachers to mvcMatchers..They are less opinionated |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 4:56pm On Nov 17, 2021 |
richebony: I have a JWT Filter here is the attached image and the filter has been added to my HttpSecurity config , couldnt snipe it earlier because of the length of the code . Here they are
|
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 1:13pm On Nov 18, 2021 |
richebony: Got it resolved thanks much !!! the problem before was that the frontend guy did not add the token bearer to requests going to marketers/customers endpoint . I tested on postman with the generated token added to the authorization header just as you suggested then refactored the entity classes User and Branch by removing the toString methods therein because it was causing an Infinite recursion and VOILA ! I got customers attached to the authenticated User. I really appreciate your patience with me you are such a rare one , thanks once again . 1 Like |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 11:59am On Nov 23, 2021 |
richebony: Good day sir , please I need your help one more time with a custom query implementation. Still on the user role login, When the UserRole Managing Director logs In, I want the userrole Managing Director to only see customers assigned to UserRole Marketers with the same Branch ID as the Managing Director. I have a custom Query in the customer repository that returns a null result. I have the user authentication issue resolved so I am pretty sure it's my query. Kindly help check if the query is correct. Thanks sir |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by richebony: 4:23pm On Nov 23, 2021 |
You can add a method level prefilter to allow only managers to access the method When you return the currently logged in user get the branch Id of that manager Query the db for all users where the branch id is equal to the returned branch id and the role is marketer Since you have a onetomany bidirectional relationship between the marketers and their customer you can return a list of all customers for each marketer returned and append it to a main list that would be returned as a json object |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 10:18pm On Nov 23, 2021 |
richebony: So I refactored and passed the Branch object as the query parameter , then changed the logged in User authentication by Inserting spring security Principal object to get the authenticated user , got the user branchID and got the customers registered under the director's branch, thanks once again sir . Do you belong to any local java community ? |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by richebony: 7:45am On Nov 24, 2021 |
No local one though ..just on reddit and fb ...do I know anyone I can join |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 10:07am On Jan 20, 2022 |
richebony: Good morning sir , I need your input on deploying the backend app. |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by richebony: 10:57am On Jan 20, 2022 |
Are u using a cloud solution provider or a shared hosting platform . I think AWS offers a 1-year free tier you can use a Linux instance(EC2) for staging and provision it for your application, or rather go with GCP and put a cap on your expenditure. |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 11:18am On Jan 20, 2022 |
richebony: The React(Frontend) is being deployed in public_html directory on same server after it has been built to production and it's running ( Login Page) No its being deployed on a VPS server Centos 7 . I packaged as a WAR file , Installed Apache Tomcat to the WHM/Cpanel, then I Uploaded the renamed build to ROOT.war then I extracted there. (inside Catalina/domain/webapps). I get error 404 when trying to login. Should I package the backend as a JAR because it does not have html, jsp or leave it as a WAR package then exclude the spring-boot-maven-plugin from <build></build> from pom.xnl file ? |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by roberto3456: 11:21am On Jan 20, 2022 |
You can always go to experts. As it is Avenga company. https://www.avenga.com/salesforce-development-company/[/code] They have helped a lot of companies to update their businesses. i think they can find something for you. |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by richebony: 11:56am On Jan 20, 2022 |
sweetguy10: Firstly it should be a war file and you must tell your spring boot starter file that your want to package the application as a Web application Archive public class ApplicationName extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(ApplicationName.class); } public static void main(String[] args) { SpringApplication.run(ApplicationName.class, args); } } I think you should stage it in your local environment first before you deploy it on your remote machine, the steps are quite the same extracting files on the /domain/web apps folder isn't the right approach from what I know, I think tomcat has an administrator(GUI) interface where you deploy your apps, To create a new user you must change the configuration settings in the conf/tomcat-users.xml and supply your credentials <tomcat-users xmlns="http://tomcat.apache.org/xml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd" version="1.0"> <user username="your-username" password="your-password" roles="manager-gui" /> <tomcat-users> restart the server You can easily log in with your credentials then deploy your app. Repeat the same process on your remote server |
Re: SQL Query That Displays A List Assigned Only To Only The Logged In User Java by sweetguy10(m): 12:15pm On Jan 20, 2022 |
richebony: I really appreciate you I've done everything but For the bolded , is it the server root username and pass or the domain cpanel username and pass ? |
Hi guys review this my app: a whatsapp, 2go, instagram, olx, game app all-in-one / Datanemesis 1: In The Minds Of Nairaland, Seun Give Us A Copy ! / Want To Automate Your Sme Data Sharing Contact Me
(Go Up)
Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health religion celebs tv-movies music-radio literature webmasters programming techmarket Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10) Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 84 |