I'm trying to make a blog using spring boot java with auth.
I created User class the implements UserDetails, and Post class.
When using the path /posts I wish to see all the posts in the blog, problem is that each post contains creator (User obj) and it shows the password of the user - and this is what I'm trying to avoid.
I tried #JsonIgnor, #JsonProperty didn't work
Tried also #JsonProperty(access = Access.WRITE_ONLY) I get an error on the Access.WRITE_ONLY.
Does are the classes:
package com.example.blog.entities;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import java.util.Collection;
import java.util.List;
#Entity
#Table(name = "users")
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String username;
#JsonIgnore
private String password;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Role> roles;
public User() {}
public User(String username, String password, List<Role> roles) {
this.username = username;
this.password = password;
this.roles = roles;
}
#JsonIgnore
public String getPassword() {
return password;
}
#JsonProperty
public void setPassword(String password) {
this.password = password;
}
public Integer getId() {
return id;
}
}
import javax.persistence.*;
import java.time.LocalDate;
import java.util.Date;
#Entity
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String title;
private String body;
private LocalDate date;
#ManyToOne
private User creator;
public Post() {
}
}
import com.example.blog.entities.Post;
import com.example.blog.entities.User;
import com.example.blog.repositories.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.List;
#Service
public class PostService {
private final PostRepository postRepository;
#Autowired
public PostService(PostRepository postRepository){
this.postRepository = postRepository;
}
public List<Post> getAllPosts(){
return postRepository.findAll();
}
public void insert(Post post) {
if(post.getBody() == null || post.getTitle() == null ){
throw new IllegalArgumentException("Missing args");
}
post.setDate(LocalDate.now());
postRepository.save(post);
}
public List<Post> getPostByUsername(User user){
return postRepository.findByCreatorId(user.getId());
}
}
The endpoint:
#GetMapping(value = "/posts")
public List<Post> posts(){
return postService.getAllPosts();
}
You should not expose your internal data model (JPA). Use transport classes. And you should remove the "#JsonProperty" from "public void setPassword(String password) ...". It is contradicting ("overriding") the "#JsonIgnore". And don't store your password as plaintext! Use for example jBCrypt.
My Setup:
public static class XUser {
private String username;
#JsonIgnore
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
//#JsonProperty
public void setPassword(String password) {
this.password = password;
}
}
#Test
public void testJson() {
XUser user = new XUser();
user.setPassword("oh shit!");
user.setUsername("name");
try {
ObjectMapper om = new ObjectMapper();
System.out.println(om.writeValueAsString(user));
} catch (Exception ex) {
ex.printStackTrace();
}
}
And the output:
{"username":"name"}
Related
I am making authorization for a web application. And I an faced witw problem. I can not use Getters and Setters. Namely setActive ans setRole. And I can not create variable UserFromDb.
RegistrationController.java
import com.Vova.Restart.Models.Role;
import com.Vova.Restart.repo.UserRepo;
import org.springframework.security.core.userdetails.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.Collections;
import java.util.Map;
#Controller
public class RegistrationController {
#Autowired
private UserRepo userRepo;
#GetMapping("/registration")
public String registration() {
return "registration";
}
#PostMapping("/registration")
public String addUser (User user, Map<String, Object> model) {
userFromDb = userRepo.findByUsername(user.getUsername());
if (userFromDb != null) {
model.put("message", "User exists!");
return "registration";
}
user.setActive(true);
user.setRole(Collections.singleton(Role.USER));
return "redirect:/login";
}
}
User.java
import javax.persistence.*;
import java.util.Set;
#Entity
#Table(name = "User")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username, password;
private boolean active;
#ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
#CollectionTable(name = "userRole", joinColumns = #JoinColumn(name = "userId"))
#Enumerated(EnumType.STRING)
private Set<Role> roles;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public void setRole(Set<Object> singleton) {
}
}
I tried to use import com.Vova.Restart.Models.User instead import org.springframework.security.core.userdetails.User and this error has gone but i get another problem Not a managed type: class org.springframework.security.core.userdetails.User. I think this is wrong imort. How can i solve it?
I have just started learning and experimenting with spring-boot and hibernate and there is this problem I can't seem to figure out.
package net.codejava;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.annotation.Rollback;
#DataJpaTest
#AutoConfigureTestDatabase(replace = Replace.NONE)
#Rollback(false)
public class UserRepositoryTests {
#Autowired
private UserRepositoryTests repo;
#Autowired
private TestEntityManager entityManager;
#Test
public void testCreateUser() {
User user = new User();
user.setEmail("xyz#gmail.com");
user.setPassword("XYZ!##");
user.setFirstname("XYZ");
user.setLastname("PQR");
user.setUsername("XZY");
User savedUser = repo.save(user);
User existUser = entityManager.find(User.class, savedUser.getIdUser());
assertThat(user.getEmail()).isEqualTo(existUser.getEmail());
}
}
There is some error with line 38 (i.e,User savedUser = repo.save(user);)
is says that"The method save(User) is undefined for the type UserRepositoryTests"
User.java
package net.codejava;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idUser;
#Column(nullable = false,unique=true,length = 45)
private String email;
#Column(nullable = false,unique=true,length = 45)
private String firstname;
#Column(nullable = false,unique=true,length = 45)
private String lastname;
#Column(nullable = false,unique=true,length = 45)
private String username;
#Column(nullable = true)
private String IPaddress;
#Column(nullable = false,length = 64)
private String password;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getIPaddress() {
return IPaddress;
}
public void setIPaddress(String iPaddress) {
IPaddress = iPaddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserRepository.java
package net.codejava;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
Please let me know what to do.
the problem was UserRepositoryTests it should have been UserRepository.
Hi people I am working on one application .I have created a model but after giving all annotation and configuring all properties it is showing below error. Can anyone please look into below issue?
application.properties
spring.datasource.url = jdbc:mysql://localhost:3306/expenses
spring.datasource.username =dante
spring.datasource.password =jboss
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.format_sql=true
server.port=9191
Main Class
package com.expenses.demo;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.expenses.demo.modal.Role;
import com.expenses.demo.modal.User;
import com.expenses.demo.modal.UserRole;
import com.expenses.service.UserService;
#SpringBootApplication
public class ExpenseApplication implements CommandLineRunner {
#Autowired
private UserService userService;
public static void main(String[] args) {
SpringApplication.run(ExpenseApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("Starting code");
User user = new User();
user.setFirstname("Aniket");
user.setLastname("Turiley");
user.setEmail("abc#gmail.com");
user.setPassword("abc");
user.setPhone("99220289");
Role role1=new Role();
role1.setRoleId(44L);
role1.setRoleName("ADMIN");
Set<UserRole> userRoleSet = new HashSet<>();
UserRole userRole = new UserRole();
userRole.setRole(role1);
userRole.setUser(user);
userRoleSet.add(userRole);
User user1= this.userService.createUser(user,userRoleSet);
System.out.println(user1.getUsername());
}
}
Model Class
Role.java
package com.expenses.demo.modal;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="roleinformation")
public class Role {
#Id
private long roleId;
private String roleName;
#OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY,mappedBy = "role")
private Set<UserRole> userRoles = new HashSet<>();
public Role() {
}
public Role(int roleId, String roleName) {
this.roleId = roleId;
this.roleName = roleName;
}
public long getRoleId() {
return roleId;
}
public void setRoleId(long l) {
this.roleId = l;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
User.java
package com.expenses.demo.modal;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="usersinfo")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstname;
private String lastname;
private String username;
private String password;
private String email;
private String phone;
private boolean enable=true;
// user has many roles
#OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER,mappedBy = "user")
#JsonIgnore
private Set<UserRole> userRoles = new HashSet<>();
public User() {
}
public User(Long id, String firstname, String lastname, String username, String password, String email,
String phone, boolean enable) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.username = username;
this.password = password;
this.email = email;
this.phone = phone;
this.enable = enable;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
Repository Interfaces
RoleRepository
package com.expenses.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.expenses.demo.modal.Role;
public interface RoleRepository extends JpaRepository<Role, Long>{
}
UserRepository
package com.expenses.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.expenses.demo.modal.User;
public interface UserRepository extends JpaRepository<User, Long> {
public User findByUsername(String username);
}
Service Class
Service.java
package com.expenses.service;
import java.util.Set;
import com.expenses.demo.modal.User;
import com.expenses.demo.modal.UserRole;
public interface UserService {
//creating user
public User createUser(User user,Set<UserRole> userRoles) throws Exception;
}
Service Implementation class
ServiceImplementation.java
package com.expenses.service;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.expenses.demo.modal.User;
import com.expenses.demo.modal.UserRole;
import com.expenses.repository.RoleRepository;
import com.expenses.repository.UserRepository;
import com.expenses.service.UserService;
#Service
public class UserServiceImplementation implements UserService{
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Override
public User createUser(User user, Set<UserRole> userRoles) throws Exception{
User local= this.userRepository.findByUsername(user.getUsername());
if(local!=null) {
System.out.println("User Already Exist");
throw new Exception("User Already Exist");
}else {
// user create
for(UserRole ur:userRoles) {
roleRepository.save(ur.getRole());
}
user.getUserRoles().addAll(userRoles);
local = this.userRepository.save(user);
}
return local;
}
}
ERROR
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
[2m2021-07-28 18:16:59.304[0;39m [31mERROR[0;39m [35m8492[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mo.s.b.d.LoggingFailureAnalysisReporter [0;39m [2m:[0;39m
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userService in com.expenses.demo.ExpenseApplication required a bean of type 'com.expenses.service.UserService' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.expenses.service.UserService' in your configuration.
Spring Boot will do the component scan (search for Classes with #Service, #Repository, #Controller, #Component) annotation only classes that are located in the same package as the main class (#SpringBootApplication annoteted class), and its subpackages.
So you need eighter to
move ExpenseApplication one package up, to com.expenses,
move all classes that needs to be found by the component scan to to com.expenses.demo or a subpackage, or
configure the component scan (and Spring Data too), for example, by #SpringBootApplication(scanBasePackages = "com.expenses")
BTW: Najeeb Arif is right too, in addition you need to add #Autowired to UserServiceImplementation.userRepository but I think you do not need to add the #Repository annotation to the Spring-Data-JPA repository interfaces.
Add this to your main class
#SpringBootApplication(scanBasePackages = "com.expenses")
This will help the component scan will find your classes.
First mark both of your Repositories with
#Repository
In your user service, you are missing the Autowired annotation.
I personally like the constructor injection.
Role Repository
#Repository
public interface RoleRepository extends JpaRepository<Role, Long>{
}
Same for the user repo.
in your User Service Impl
#Service
public class UserServiceImplementation implements UserService{
private final UserRepository userRepository;
private final RoleRepository roleRepository;
/* when using constructor injection #Autowired is not required */
public UserServiceImplementation(UserRepository userRepository, RoleRepository roleRepository){
this.userRepository = userRepository;
this.roleRepository = roleRepository;
}
#Override
public User createUser(User user, Set<UserRole> userRoles) throws Exception{
//...
}
}
I am new to spring boot as after completing a crud function rest API in spring-boot I'm badly stuck in login rest API for android application where I just want to use email and password in POSTMAPPING. Please anyone could help me here?
Controller class
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import demo.loginapi.main.model.UserModel;
import demo.loginapi.main.repository.UserRepository;
import demo.loginapi.main.repository.UserService;
#RestController
#RequestMapping("/api/user")
public class UserController {
#Autowired
UserRepository userRepository;
#Autowired
UserService userService;
#GetMapping("/getallusers")
public List<UserModel> getAllCustomer(){
List<UserModel> alluserlist = userRepository.findAll();
return alluserlist;
}
#PostMapping("/login/{email}")
public List<UserModel> getemailpassword(#PathVariable(value = "email") String email){
List<UserModel> alluseremailpassword = userRepository.findUserByEmail(email);
return alluseremailpassword;
}
#PostMapping("/login2/{email}")
public UserModel getuserbyemail(#PathVariable(value = "email") String email)
{
UserModel userByEmailForLogin = userRepository.findByEmail(email);
return userByEmailForLogin;
}
#PostMapping("/loginemailpass/{email}/{password}")
public ResponseEntity<Map<String, String>> loginUser(#RequestBody Map<String, Object> userMap){
String email = (String) userMap.get("email");
String password = (String) userMap.get("password");
UserModel userModel = userService.validate(email,password);
return new ResponseEntity<>(generateJWTToken(userModel),HttpStatus.OK);
}
private Map<String, String> generateJWTToken(UserModel userModel) {
// TODO Auto-generated method stub
return null;
}
}
** Entity Class **
package demo.loginapi.main.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "user_login")
public class UserModel {
#Id
#Column(name = "userId", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
#Column(name = "username", nullable = false)
private String username;
#Column(name = "email", nullable = false)
private String email;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "role", nullable = false)
private String role;
public UserModel() {
//default constructor
}
public UserModel(Long userId, String username, String email, String password, String role) {
//super();
this.userId = userId;
this.username = username;
this.email = email;
this.password = password;
this.role = role;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
#Override
public String toString() {
return "UserModel [userId=" + userId + ", username=" + username + ", email=" + email + ", password=" + password
+ ", role=" + role + "]";
}
}
** Repository Class **
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import demo.loginapi.main.model.UserModel;
#Repository
public interface UserRepository extends JpaRepository<UserModel, Long>{
List<UserModel> findUserByEmail(String email);
UserModel findByEmail(String email);
//UserModel validate(String email, String password);
UserModel findByEmailAndPaswword(String email, String password);
//UserModel findByEmailPassword(String email, String password);
}
** Service Class **
import demo.loginapi.main.model.UserModel;
public interface UserService {
UserModel validate(String email, String password);
}
** Service Implementation **
package demo.loginapi.main.repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import demo.loginapi.main.model.UserModel;
#Service
public class UserRepoImpl implements UserService{
#Autowired
UserRepository userRepository;
#Override
public UserModel validate(String email, String password) {
if(email != null) email = email.toLowerCase();
return userRepository.findByEmailAndPaswword(email, password);
}
}
In your repository class , is findByEmailAndPassword is available in jparepository, if not use through #query annotation like #query("select usename from userlogin us where us.username =:email") Something like that in your method.
Also if pre defined method is available please check the spelling, seems incorrect. It has double w in it. findByEmailAndPaswword
In my project N- number of User is available. Every user can do insert update deleted list of data. every users have different different data. suppose one user have 10 record another user have 20 record and 3rd user have 15 record etc.
I have try to multiple user can register and login to my application with first user in side first user account i have inserted 10 record and display then logout. again i will login with different user then that same data will be display which is inserted by previous user. So my problem is how to maintain every user data with your own account i am beginner in spring-boot with hibernate, jsp.
1.Usercontroller.java
package com.rajesh.controller;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.rajesh.model.User;
import com.rajesh.service.UserService;
#Controller
public class UserController {
private final Logger logger = LoggerFactory.getLogger(UserController.class);
#Autowired
private UserService userService;
#GetMapping("/")
public String Home(Model model) {
return "home";
}
#PostMapping("/user/register")
public String registerNewUser(ModelMap model, #ModelAttribute("userRegister")#Valid User user, BindingResult bindingResult) {
User userExists = userService.findUserByEmail(user.getEmail());
if (userExists != null) {
bindingResult
.rejectValue("email", "error.user",
"There is already a user registered with the email provided");
model.addAttribute("msgEmail", "your email is already registered");
logger.info("your email Id is already registered");
System.out.println("your email is already registered");
return "home";
} else {
userService.saveUser(user);
model.addAttribute("successMessage", "User has been registered successfully");
logger.info("User has been registered successfully");
System.out.println("User has been registered successfully");
return "home";
}
}
#PostMapping("/user/login")
public String doLogin(ModelMap model, #ModelAttribute("command")User user, HttpSession session) {
if(userService.loginUser(user.getEmail(), user.getPassword()) != null) {
session.setAttribute("email",user.getEmail());
session.setAttribute("user_id", user.getId());
model.addAttribute("sucessLogin", "You are login sucessfully");
logger.info("You are login sucessfully",user.getEmail());
System.out.println("You are login sucessfully "+ user.getEmail());
return "redirect:userdashboard";
}else {
System.out.println("Invalid Email/Password");
logger.error("Invalid Email/Password");
model.put("failed", "Invalid Email/Password");
return "home";
}
}
#PostMapping("/user/checkstatus")
#ResponseBody
public Integer checkUserStatus(String email, ModelMap model, #ModelAttribute("command")User user, HttpSession session) {
int userStatus = userService.isActiveUserStatus(email);
System.out.println(userStatus);
if(userStatus != 0) {
System.out.println(userStatus);
return userStatus;
}else {
System.out.println(userStatus);
return userStatus;
}
}
#GetMapping("/logout")
public String doLogout(ModelMap model, #ModelAttribute("command")User user, HttpSession session) {
session.removeAttribute("email");
logger.info("you are logout successfully");
return "home";
}
}
User.java
package com.rajesh.model;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import org.hibernate.validator.constraints.Length;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* #author Rajesh Bhushan
*/
#Data
#Builder
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "users")
public class User extends BaseEntity{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id")
private int id;
#Column(name="shopname")
#Length(min = 3, message = "*Your shopname must have at least 3 characters")
#NotEmpty(message = "*Please provide an shopname")
private String shopname;
#Column(name="name")
#Length(min = 3, message = "*Your name must have at least 3 characters")
#NotEmpty(message = "*Please provide an name")
private String name;
#Column(name="address")
#Length(min = 3, message = "*Your address must have at least 3 characters")
#NotEmpty(message = "*Please provide an address")
private String address;
#Column(name="mobile")
#NotEmpty(message = "*Please provide an address")
private String mobile;
#Column(name = "email")
#Email(message = "*Please provide a valid Email")
#NotEmpty(message = "*Please provide an email")
private String email;
#Column(name = "password")
#NotEmpty(message = "*Please provide your password")
private String password;
#Column(name="active")
private int active;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> roles;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getShopname() {
return shopname;
}
public void setShopname(String shopname) {
this.shopname = shopname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getActive() {
return active;
}
public void setActive(int active) {
this.active = active;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
UserRepository.java
package com.rajesh.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.rajesh.model.User;
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
public User findByEmail(String email);
#Query("from User as u where u.email=:email and u.password=:password")
public User loginUser(String email,String password);
#Query("select active from User as u where u.email=:email")
public Integer isActiveUserStatus(String email);
}
4.UserService.java
package com.rajesh.service;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rajesh.model.Role;
import com.rajesh.model.User;
import com.rajesh.repository.RoleRepository;
import com.rajesh.repository.UserRepository;
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
public User findUserByEmail(String email) {
return userRepository.findByEmail(email);
}
public void saveUser(User user) {
user.setShopname(user.getShopname());
user.setName(user.getName());
user.setEmail(user.getEmail());
user.setPassword(user.getPassword());
user.setMobile(user.getMobile());
user.setAddress(user.getAddress());
user.setActive(0);
user.setCreatedBy(user.getName());
user.setCreatedDate(new Date());
user.setUpdatedBy(user.getName());
user.setUpdatedDate(new Date());
Role userRole = roleRepository.findByRole("USER");
user.setRoles(new HashSet<Role>(Arrays.asList(userRole)));
userRepository.save(user);
}
public User loginUser(String email,String password) {
return userRepository.loginUser(email, password);
}
public Integer isActiveUserStatus(String email) {
Integer activeStatus = userRepository.isActiveUserStatus(email);
return activeStatus;
}
}
Create a userid column on data table. So when listing data get datas according to userid.