I have a problem with Hibernate to make login process. All codes are perfectly correct in terms of syntax. NetBeans tell me that my code have no problem. However, when I run the web, and I test the login process, it doesn't reacting and the address is stucked on the doLogin.
All classes have been mapped correctly.
This is my problem: when I try to retrieve data, my code is stucked on a line.
on doLogin servlet (I use the template provided by NetBeans and just filling in my code on the try. Here's in brief:
Connect con = new Connect(); //my code is stucked on this line.
//I've done testing where's the cause of the stuck, and this line is the cause.
List logger = con.getLogin(username, password);
and to make it clear:
Connect.java
public class Connect {
Session sesi;
public Connect() {
sesi = HibernateUtil.getSessionFactory().openSession();
}
public List getLogin(String username, String password){
return sesi.createQuery("from MsUser WHERE username = '"+username+"' and password = '"+password+"'").list();
}
}
and since that query is HQL, here is the MsUser class:
public class MsUser {
public MsUser() {
}
private int userID;
private String username;
private String firstname;
private String lastname;
private String email;
private String password;
private String gender;
private String address;
private String phone;
private String photo;
public MsUser(int userID, String username, String firstname, String lastname, String email, String password, String gender, String address, String phone, String photo) {
this.userID = userID;
this.username = username;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.password = password;
this.gender = gender;
this.address = address;
this.phone = phone;
this.photo = photo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public int getUserID() {
return userID;
}
public void setUserID(int userID) {
this.userID = userID;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
please help. But I suspect on Connect's constructor as the main cause. Anybody can suggest or fix or tell me what causing me this.
appendix:
HibernateUtil.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
/**
* Hibernate Utility class with a convenient method to get Session Factory
* object.
*
* #author Ginanjar
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
You can try following code in your hibernateUtil.java file:
SessionFactory factory = new Configuration().configure().buildSessionFactory();
session = factory.openSession();
String query = "select reg.username,reg.password from MsUser as reg where reg.username='" + username + "' and reg.password='" + password + "'";
Query DBquery = session.createQuery(query);
for (Iterator it = DBquery.iterate(); it.hasNext();) { it.next();
count++;
}
System.out.println("Total rows: " + count);
if (count == 1) {
return true;
} else {
return false;
}
}
Related
This will be quite a bit of code as I don't know what will be important. I was trying to recreated the basic UI Alejandro made in my tutorial session with him a few months ago, substituting a table in my database for the one he used. The errors I'm getting all seem related to overriding Vaadin Flow functions. I know that replaces the behavior of the Super method. IntelliJ opens the relevant Super method when I click on the errors, which I'm assuming it wants me to edit to solve the problem, but I have no idea how to do that.
I was going to paste a link to the code but the forum told me to just place it here.
Customer.java
package com.dbproject.storeui;
import java.time.LocalDate;
public class Customer {
private Long id;
private String lastname;
private String firstname;
private String email;
private String password;
private String phone;
private String street;
private String city;
private String st;
private int zip;
private LocalDate dob;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
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 getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getSt() {
return st;
}
public void setSt(String st) {
this.st = st;
}
public int getZip() {
return zip;
}
public void setZip(int zip) {
this.zip = zip;
}
public LocalDate getDob() {
return dob;
}
public void setDob(LocalDate dob) {
this.dob = dob;
}
}
CustomerRepository.java
package com.dbproject.storeui;
import org.apache.ibatis.annotations.*;
import java.util.List;
#Mapper
public interface CustomerMapper {
#Select("SELECT * FROM customer ORDER BY id")
List<Customer> findAll();
#Update("UPDATE customer" +
"SET lastname=#{lastname}, firstname=#{firstname}, email=#{email}, password=#{password}, phone=#{phone}, street=#{street}, city=#{city}, st=${st}, zip=#{zip}, dob=#{dob}" +
"WHERE id=#{id}")
void update(Customer customer);
#Insert("INSERT INTO customer(lastname, firstname, email, password, phone, street, city, st, zip, dob) VALUES(#{lastname}, #{firstname}, #{email}, #{password}, #{phone}, #{street}, #{city}, #{st}, #{zip}, #{dob})")
#Options(useGeneratedKeys = true, keyProperty = "id")
void create(Customer customer);
}
CustomerView.java (the UI class)
package com.dbproject.storeui;
import com.vaadin.flow.component.Composite;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.Route;
#Route("")
public class CustomerView extends Composite<VerticalLayout> {
private final CustomerMapper customerMapper;
private Grid<Customer> grid = new Grid<>();
private TextField lastname = new TextField("Last Name");
private TextField firstname = new TextField("First Name");
private Button save = new Button("Save", VaadinIcon.CHECK.create());
private Button create = new Button("New", VaadinIcon.PLUS.create());
private VerticalLayout form = new VerticalLayout(lastname, firstname, save);
private Binder<Customer> binder = new Binder<>(Customer.class);
private Customer customer;
public CustomerView(CustomerMapper customerMapper) {
this.customerMapper = customerMapper;
grid.addColumn(Customer::getLastname).setHeader("Last Name");
grid.addColumn(Customer::getFirstname).setHeader("First Name");
grid.addSelectionListener(event -> setCustomer(grid.asSingleSelect().getValue()));
updateGrid();
save.addClickListener(event -> saveClicked());
create.addClickListener(event -> createClicked());
getContent().add(grid, create, form);
binder.bindInstanceFields(this);
binder.setBean(null);
}
private void createClicked() {
grid.asSingleSelect().clear();
setCustomer(new Customer());
}
private void saveClicked() {
binder.readBean(customer);
if (customer.getId() == null) {
customerMapper.create(customer);
} else {
customerMapper.update(customer);
}
updateGrid();
Notification.show("Saved!");
}
private void setCustomer(Customer customer) {
this.customer = customer;
form.setEnabled(customer != null);
binder.setBean(customer);
}
private void updateGrid() {
grid.setItems(customerMapper.findAll());
}
}
I am having trouble understanding why my userRepository is returning null even when there is a record like it in my table. I tried doing it with my demo codes and it works but when I try doing it with user Authentication it does not work.
Security Services
#Path("/securityservice")
public class SecurityServices {
private UserRepository userRepo;
// http://localhost:8990/login/securityservice/security
#GET
#Path("security")
#Produces(MediaType.APPLICATION_JSON)
public Response getOrderById(#QueryParam("orderId") int orderID,
#HeaderParam("Authorization") String authString) throws JSONException {
JSONObject json = new JSONObject();
if (isUserAuthenticated(authString)) {
json.put("INFO", "Authorized User!");
return Response.status(200)
.entity(json.toString())
.type(MediaType.APPLICATION_JSON)
.build();
} else {
json.put("ERROR", "Unauthorized User!");
return Response.status(403)
.entity(json.toString())
.type(MediaType.APPLICATION_JSON)
.build();
}
}
private boolean isUserAuthenticated(String authString) {
//authString = Basic 3hfjdksiwoeriounf
String[] authParts = authString.split("\\s+");
//authParts[0] = Basic
//authParts[1] = 3hfjdksiwoeriounf
String authInfo = authParts[1];
byte[] bytes = Base64.getDecoder().decode(authInfo);
String decodedAuth = new String(bytes);
// decodedAuth = dj:1234
String[] credentials = decodedAuth.split(":");
//credentials[0]=dj
//credentials[1]=1234
System.out.println("HELLO"+credentials[0]);
System.out.println("HELLO"+credentials[1]);
User user = userRepo.findByUsername(credentials[0]); //this line returns null
if (user != null) {
return true;
} else {
return false;
}
}
User class (Getters and setters for the JPA Repo)
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name="firstname")
private String firstName;
#Column(name="lastname")
private String lastName;
private String password;
private String username;
#Column(name="accesstype")
private String accessType;
public User() {
super();
}
public User(String firstName, String lastName, String password,
String username, String accessType) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.username = username;
this.accessType = accessType;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAccessType() {
return accessType;
}
public void setAccessType(String accessType) {
this.accessType = accessType;
}
}
I am using spring security to login and logout, eveything works fine.
I can get username from logged user fine, however i need userID,
I would like to know how can i get user as an object from logged in user or how could i get userID
#RequestMapping("/contato")
public String contato(Model model, Principal principal ){
String userName = principal.getName();
model.addAttribute("userName",userName);
System.out.println(userName);
return "contato";
}
Bean
import java.sql.Date;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
public class Users {
private int user_id;
#NotBlank
#Size(min=1, max=100, message="Name must be between 1 and 100 characters")
private String firstname;
#NotBlank
private String surname;
#NotNull
private Date dob;
#NotBlank
#Email
private String username;
#NotBlank
private String telephone;
#NotBlank
private String address;
#NotBlank
private String city;
#NotBlank
private String country;
#NotBlank
private String postcode;
#NotBlank
#Size(min=6, message="Password must be have more than 6 characters")
private String password;
private boolean enabled = false;
private String authority;
public Users() {
}
public Users(int user_id, String firstname, String surname, Date dob, String username, String telephone,
String address, String city, String country, String postcode, String password, boolean enabled,
String authority) {
super();
this.user_id = user_id;
this.firstname = firstname;
this.surname = surname;
this.dob = dob;
this.username = username;
this.telephone = telephone;
this.address = address;
this.city = city;
this.country = country;
this.postcode = postcode;
this.password = password;
this.enabled = enabled;
this.authority = authority;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
}
Can anyone please help me to get user id from logged user
I have also tried using
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Users user =(Users)authentication.getPrincipal();
but it still did not work
The simplest approach would be to leverage the UserDetails and UserDetailsService interfaces.
Write a simple UserDetailsService:
#Service
public class CustomUserDetailsService implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return findUserByUsername(username); //load the user from somewhere (e.g. Database)
}
}
Have your Users class implement the UserDetails interface:
public class Users implements UserDetails {
private String username;
private String userId;
private String password;
private String role;
public Users(String username, String userId, String password, String role) {
this.username = username;
this.userId = userId;
this.password = password;
this.role = role;
}
//...
}
Finally, when you call this static method you'll receive the Users object from which you can extract the userId:
Users user = (Users) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
I need to verify the email of the new user who would like to sign up in my application web. if the email is already in my database (mysql) so must don't accept this sign up and said said to him like: "your email already used".
Now I can save users in my database, but how to check them by his email for not repeat the inscription in my application web.
this is my Dao layer class :
public class UserDaoMysql implements UserDao {
private Session session;
private void openSession(){
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
}
private void closeSession(){
session.getTransaction().commit();
session.close();
}
public void insert(User user) {
if(checkEmail(user)){
openSession();
User p = new User(user.getName(), user.getEmail(), user.getPassword());
session.save(p);
System.out.println("sauvegarde reussi");
closeSession();
}
}
public boolean checkEmail(User user){
return true;
}
}
this is my user bean :
#ManagedBean(name="user")
public class User {
private int id;
private String name;
private String email;
private String password;
private String confirmationPass;
// private image
public User() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 getConfirmationPass() {
return confirmationPass;
}
public void setConfirmationPass(String confirmationPass) {
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password,
String confirmationPass) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
}
public User(String name, String email, String password) {
super();
this.name = name;
this.email = email;
this.password = password;
}
#Override
public String toString() {
return "User [id=" + id + ", Name=" + name + ", email=" + email
+ ", password=" + password + "]";
}
public void save(){
UserBusiness userBusiness = new UserBusinessImp();
userBusiness.add(new User(name, email,password));
}
}
And I created a table "user" in my database.
Maybe there is an annotation which can help us to specify the email property as an unique one or something else.
What you can do is create a unique key on your email column in your table. After that, decorate your field using #Column(unique=true), that will indicate to Hibernate that this field has a unique key.
Also, be careful with your annotations. This is unrelated to your problem, but #ManagedBean marks the class as a bean able to interact with the view in JSF. Probably you want/need to use #Entity instead.
I am programming an IHM for sign up the users, I need to check if this user is already in database(mysql), checking by his email . can you help me please.
I can save my user now but how to check if this user by his email
this is my Dao layer class :
public class UserDaoMysql implements UserDao {
private Session session;
private void openSession(){
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
}
private void closeSession(){
session.getTransaction().commit();
session.close();
}
public void insert(User user) {
if(checkEmail(user)){
openSession();
User p = new User(user.getName(), user.getEmail(), user.getPassword());
session.save(p);
System.out.println("sauvegarde reussi");
closeSession();
}
}
public boolean checkEmail(User user){
return true;
}
}
this is my user bean :
#ManagedBean(name="user")
public class User {
private int id;
private String name;
private String email;
private String password;
private String confirmationPass;
// private image
public User() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 getConfirmationPass() {
return confirmationPass;
}
public void setConfirmationPass(String confirmationPass) {
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password,
String confirmationPass) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
}
public User(String name, String email, String password) {
super();
this.name = name;
this.email = email;
this.password = password;
}
#Override
public String toString() {
return "User [id=" + id + ", Name=" + name + ", email=" + email
+ ", password=" + password + "]";
}
public void save(){
UserBusiness userBusiness = new UserBusinessImp();
userBusiness.add(new User(name, email,password));
}
}
And I have a table user in my database.
thanks for your help in advance
I would use NamedQuery for this. Define named query in your User entity like this:
...
#NamedQueries({
#NamedQuery(name = "User.findByEmail",
query = "SELECT u FROM User u WHERE u.email = :email")})
#ManagedBean(name="user")
public class User {
...
And then add method like this to your DAO
public List<User> getUsersByEmail(String email){
openSession();
Session session;
Query query = session.getNamedQuery("User.findByEmail");
query.setString("email", email);
Lis<Users> users = query.list();
closeSession();
return users;
}
This method is little bit more generic you can make it more specific returning user count only.