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.
Related
I am very new to Spring Boot. This is what I want to do: The user's email is test#example.com. That user already exists in my database, but I would like to know if their verificationCode is 123.
Entity:
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String email;
private String password;
private String verificationCode;
#Column(name = "verified", columnDefinition = "default false")
private boolean verified = false;
#CreationTimestamp
private Date registrationDate;
protected Users() {}
public Users(String email, String password, String verificationCode) {
this.email = email;
this.password = password;
this.verificationCode = verificationCode;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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 getVerificationCode() {
return verificationCode;
}
public void setVerificationCode(String verificationCode) {
this.verificationCode = verificationCode;
}
public boolean isVerified() {
return verified;
}
public void setVerified(boolean verified) {
this.verified = verified;
}
}
So with userRepository.findByEmail("test#example.com") I am getting the correct user, but how do I check their verification code?
if you're using userRepository.findByEmail("test#example.com"), just take the verification code from entity.
private static final String CODE = "123";
final User user = userRepository.findByEmail("test#example.com");
if (CODE.equals(user.getVerificationCode())) {
// do something
}
Another option to have it within query.
userRepository.findByEmailAndVerificationCode("test#example.com", CODE);
Or you can have something similar as Philipp wrote, but I would not get whole entity just find out if it exist. So solution would be
if (userRepository.existsByCode(CODE)) {
// do something
}
You search for something like that:
public void checkVerificationCode(final String verificationCode) {
final User user = userRepository.findByEmail("test#example.com");
if (!user.getVerificationCode(verificationCode)) {
throw new VerificationCodeException("Incorrect verification code.");
}
}
This question already has answers here:
Springboot Security hasRole not working
(3 answers)
Closed 2 years ago.
I've a set rules where it dictates which roles have access to which url. However, I'm getting 403 at urls where the role should have access to. Please refer below for the code and problem
Log
org.springframework.security.access.AccessDeniedException: Access is
denied at
org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84)
~[spring-security-core-5.3.3.RELEASE.jar:5.3.3.RELEASE] at
org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233)
~[spring-security-core-5.3.3.RELEASE.jar:5.3.3.RELEASE] at
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:123)
~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
Spring security configuration. Notice admin/** allows admin usage. I've logged in with admin, going to admin/welcome and it gives me 403.
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
// To access the h2 embedded database
#Autowired
DataSource dataSource;
#Autowired
Securityhandler successHandler;
#Autowired
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.jdbcAuthentication()
// To find logins in the h2 database
.dataSource(dataSource)
.usersByUsernameQuery("select email, password, 'true' as enabled from User where email = ?")
.authoritiesByUsernameQuery("select email, role " +
"from User " +
"where email =?");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/*", "/h2-console/**").permitAll()
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.antMatchers("/admin/**").hasRole("ADMIN")
// formLogin redirect to login page
.and().formLogin()
.successHandler(successHandler);
// In order to work with spring security csrf protection needs to be disabled
http.csrf().disable();
http.headers().frameOptions().disable();
}
// To encrypt password
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Admin user created with commandlinerunner so it is automatically created upon running the app. Notice the admin role at the end
#Override
public void run(String... args) throws Exception {
// Creates new user upon running the app
String password = securityConfig.passwordEncoder().encode("github");
User user = new User("Billy", "billy", password, password, "sof#gmail.com", "ADMIN");
userRep.save(user);
System.out.println("Saved user:" + user);
}
Entity class
#Entity
#ValidPassword
public class User {
#Pattern(regexp="[a-zA-Z]+", message = "Enter letters only!")
private String firstName;
#Pattern(regexp="[a-zA-Z]+", message = "Enter letters only!")
private String lastName;
private String password;
private String matchingPassword;
private String passportNumber;
private String address;
private String phoneNumber;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#ValidEmail
private String email;
// Mark as primary key
#Id
// Will be auto generated
#GeneratedValue
private long id;
private String role;
public User(String firstName, String lastName, String password, String passportNumber, String address,
String phoneNumber, String email, String role) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.passportNumber = passportNumber;
this.address = address;
this.phoneNumber = phoneNumber;
this.email = email;
this.role = role;
}
#Override
public String toString() {
return "User [firstName=" + firstName + ", lastName=" + lastName + ", password=" + password
+ ", matchingPassword=" + matchingPassword + ", passportNumber=" + passportNumber + ", address="
+ address + ", phoneNumber=" + phoneNumber + ", email=" + email + ", id=" + id + ", role=" + role + "]";
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMatchingPassword() {
return matchingPassword;
}
public void setMatchingPassword(String matchingPassword) {
this.matchingPassword = matchingPassword;
}
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 getPassportNumber() {
return passportNumber;
}
public void setPassportNumber(String passportNumber) {
this.passportNumber = passportNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setId(long id) {
this.id = id;
}
public User() {
}
public User(String firstName, String lastName, String password, String matchingPassword, String email,
String role) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.matchingPassword = matchingPassword;
this.password = password;
this.email = email;
this.role = role;
}
public long getId() {
return id;
}
Use hasAuthority/hasAnyAuthority instead of hasRole/hasAnyRole or add the prefix ROLE_ when you create the user as #matejko219 wrote in his comment.
I am currently new to do website project with JSF specification. as you all know, JSF should include xhtml for the server page and managed bean to determine the class method, and I have made connection between my project and MySQL localhost.
The problem is, i created 1 main table for User categories which include common attributes such as name, gender etc. and i made other two table that specify the user for its role. The thing is that the main User table that contain user_ID as PRIMARY KEY to become the reference for the other 2 tables FOREIGN KEY ex: student, staff.
If i created a registration form on the server page, how should i determine the method to separate the data into the database from coming to the wrong table?
LoginBean.Java
private String fullName_;
private String gender_;
private String phoneNumber_;
private String IC_;
private String email_;
private String Address_;
private String password_;
public String getFullName_() {
return fullName_;
}
public void setFullName_(String fullName_) {
this.fullName_ = fullName_;
}
public String getGender_() {
return gender_;
}
public void setGender_(String gender_) {
this.gender_ = gender_;
}
public String getPhoneNumber_() {
return phoneNumber_;
}
public void setPhoneNumber_(String phoneNumber_) {
this.phoneNumber_ = phoneNumber_;
}
public String getIC_() {
return IC_;
}
public void setIC_(String IC_) {
this.IC_ = IC_;
}
public String getEmail_() {
return email_;
}
public void setEmail_(String email_) {
this.email_ = email_;
}
public String getAddress_() {
return Address_;
}
public void setAddress_(String Address_) {
this.Address_ = Address_;
}
public String getPassword_() {
return password_;
}
public void setPassword_(String password_) {
this.password_ = password_;
}
public String saveUser(LoginBean loginBean){
UserDao dao = new UserDao(); //METODE SIMPAN KE DATABASE!!!
User user = new User();
user.setFullName(loginBean.getFullName_());
user.setGender(loginBean.getGender_());
user.setPhoneNumber(Integer.parseInt(loginBean.getPhoneNumber_()));
user.setIc(loginBean.getIC_());
user.setEmail(loginBean.getEmail_());
user.setPassword(loginBean.getPassword_());
dao.saveStudent(user);//untuk menyimpan di database
Map<String,Object> sessionMapObj = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
sessionMapObj.put("msg", "Data "+user.getIc() +"successfull!");
return"/sukses.xhtml?faces-redirect=true";
}
User.java
private Integer userId;
private String fullName;
private String gender;
private Integer phoneNumber;
private String ic;
private String email;
private String address;
private String password;
private Set students = new HashSet(0);
private Set staffs = new HashSet(0);
public User() {
}
public User(String fullName, String gender, Integer phoneNumber, String ic, String email, String address, String password, Set students, Set staffs) {
this.fullName = fullName;
this.gender = gender;
this.phoneNumber = phoneNumber;
this.ic = ic;
this.email = email;
this.address = address;
this.password = password;
this.students = students;
this.staffs = staffs;
}
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getFullName() {
return this.fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(Integer phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getIc() {
return this.ic;
}
public void setIc(String ic) {
this.ic = ic;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Set getStudents() {
return this.students;
}
public void setStudents(Set students) {
this.students = students;
}
public Set getStaffs() {
return this.staffs;
}
public void setStaffs(Set staffs) {
this.staffs = staffs;
}
I suppose you want to have a look at jdbc. Java Database Connectivity allows you to create sql queries in java. However, alot of times a Java Persistence API is used (JPA) in Java EE applications. This is a specification on how you can store and retrieve Java-Objects from a database. A very common implementation of that is the hibernate framework.
If you want to enable Hibernate capabilies for your jsf project, follow this guide:
https://howtodoinjava.com/hibernate/hibernate-3-introduction-and-writing-hello-world-application/. If your project isn't build with Maven, just ignore that part of the tutorial.
With hibernate for eg. you can create a User Entity. You can follow this easy tutorial on how to create entities: https://www.baeldung.com/jpa-entities
Now let's suppose you don't want to use any of that and just want a default solution with jdbc:
import java.sql.*;
public class Userdao
{
public static void saveUser(User user)
{
try
{
value1 = user.getId();
value2 = user.getFirstName();
value3 = user.getLastName();
String myUrl = "jdbc:somesql:localhost/test";
//now we load the driver
Class.forName("oracle.jdbc.driver.OracleDriver"); //download the correct driver of your database and add as library to your project
Connection conn = DriverManager.getConnection(myUrl, "root", "");
// our SQL SELECT query.
// if you only need a few columns, specify them by name instead of using "*"
String addUserQuery = "INSERT INTO table_name (column1, column2, column3, ...) VALUES (" + value1 + ", " + value2 + ", " + value3, + "...);" //column1 could be Userid-Primarykey, 2 Name ...
Statement addSt = conn.createStatement();
addSt.executeQuery(addUserQuery)
// create the java statement for retrieving
String query = "SELECT + from table_name";
Statement st = conn.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next())
{
int id = rs.getInt("id");
String firstName = rs.getString("first_name"); //first_name being the column name
String lastName = rs.getString("last_name");
// print the Name
System.out.format("%s, %s\n", id, firstName, lastName);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
Foreign Key references are handled in the database, so for. eg. if you want to get the child objects you simply need a query that joins the tables, and then extract the corresponding values from the result set.
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.
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;
}
}