I have a class User with:
int id;
String username;
String password;
String token;
Date tokenExpires;
And i have a method like this:
private EntityManager em;
private User authenticate(String username, String password) throws Exception {
// Authenticate against a database, LDAP, file or whatever
// Throw an Exception if the credentials are invalid
Query query = em.createQuery("Select u from User u WHERE u.username = :name and u.password = :password");
query.setParameter("name", username);
query.setParameter("password", password);
return (User) query.getSingleResult();
}
and a method to generate a token:
private String issueToken(String username) {
Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);
return token;
}
how to save this token to db, everytime user log in? so when user log in should generate a token, if user log in again it should generate a new token
When a user logs in, simply fetch the user from the database, then set the mentioned fields, the token and its' expiration date:
public User updateUser(String username, String password) {
User user = getUserBy(username, password);
String token = issueToken();
// token expires in 30 mins;
Date tokenExpires = new Date(System.currentTimeMillis() + 1800000);
user.setToken(token);
user.setTokenExpires(tokenExpires);
entityManager.getTransaction().begin();
entityManager.merge(user);
entityManager.getTransaction().commit();
}
Considering you are using Hibernate, then, the User model has to be annotated as well:
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String password;
private String token;
#Temporal(TemporalType.TIMESTAMP)
private Date tokenExpires;
// getters and setters, make sure they are present
}
if you use spring, try this guide, for example: https://javadeveloperzone.com/spring-boot/spring-boot-oauth2-jdbc-token-store-example/
Related
I am making a project where when a user login he will get a mail otp.I have successfully made the login page and also I am sending otp to the user mail address. Now I also want to validate the otp for that I have already created a otp column in database. But I can't figure out how to store the generated otp in the table.
Here is my code.
EmailSenderService class :
public class EmailSenderService {
#Autowired
private JavaMailSender mailSender;
public void sendMail(String toEmail,
String subject,
String body) {
SimpleMailMessage message=new SimpleMailMessage();
message.setFrom("growthgreek#gamil.com");
message.setTo(toEmail);
message.setText(body);
message.setSubject(subject);
mailSender.send(message);
System.out.println("message sent .....");
}
}
OtpEmailController Class:
#Controller
public class OtpEmailController {
#Autowired
private EmailSenderService emailService;
Random random = new Random(1000);
#PostMapping("/send-otp")
public String sendOtp(#RequestParam("email") String email) {
int otp = random.nextInt(999999);
String subject = "OTP from session-handling-proj By Harshit";
String toEmail = email;
String body = "<h1> OTP = " + otp + "</h1>";
this.emailService.sendMail(toEmail, subject, body);
return ("success");
}
Repository Class :
#Repository
#Transactional
public interface SessionHandlingRepository extends JpaRepository<SessionHandling, Integer>{
#Query(value="Select * from session_handling where email= :email",nativeQuery =true)
public SessionHandling findByEmailId(#Param("email")String email);
#Query(value="Select * from session_handling where email= :email AND password= :password",nativeQuery =true)
public SessionHandling findByEmailIdAndPassword(#Param("email")String email, #Param("password")String password);
}
Entity Class :
#Entity
public class SessionHandling {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String email;
private String password;
private String cpassword;
private static final long OTP_VALID_DURATION = 5 * 60 * 1000; // 5 minutes
#Column(name = "one_time_password")
private String oneTimePassword;
#Column(name = "otp_requested_time")
private Date otpRequestedTime;
Where and how to write the query for saving the otp in database?
You can do it with your repository, first inject the repository in your service :
#Autowired
private SessionHandlingRepository sessionHandlingRepository;
you can then create an instance of your entity at the desired location (add getter and setter to the entity first):
SessionHandling sessionHandling = new SessionHandling();
sessionHandling.setName("theName");
// call Other setters ...
you can use the following repository method to save the entity in the database :
sessionHandlingRepository.save(sessionHandling);
I want to save user in database, but i have an error about saving date:
Error accessing field [private java.util.Date ru.sfedu.diplomabackend.model.User.created] by reflection for persistent property [ru.sfedu.diplomabackend.model.User#created] : User(id=null, email=user#gmail.com, password=$2a$12$H3Wm1XGRPFse5AP0ZnzAs.SPiGMBp35mRgqI5WLwu1Zp/1RVRSnwC, firstName=Da, lastName=Mi, created=Fri Jun 04 21:51:39 MSK 2021, goalSet=[], diaryDays=[])
Caused by: java.lang.IllegalArgumentException: Can not set java.util.Date field ru.sfedu.diplomabackend.model.User.created to ru.sfedu.diplomabackend.model.User
User class:
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String email;
private String password;
private String firstName;
private String lastName;
private Date created;
UserPostRequestDto class:
public class UserPostRequestDto {
private String email;
private String password;
private String firstName;
private String lastName;
private Date created;
public UserPostRequestDto(User user) {
email = user.getEmail();
password = user.getPassword();
firstName = user.getFirstName();
lastName = user.getLastName();
}
public User toUser() {
User user = new User();
user.setEmail(email);
user.setPassword(password);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setCreated(new Date());
return user;
}
rest controller:
public ResponseEntity<?> createUser(#RequestBody UserPostRequestDto userPostRequestDto) {
var user = userPostRequestDto.toUser();
//user.setCreated(new Date());
user.setPassword(passwordEncoder.encode(user.getPassword()));
return userDao.addUser(user)
? ResponseEntity.ok(user)
: new ResponseEntity<>("Invalid user", HttpStatus.BAD_REQUEST);
}
Your error clearly says that you are trying to assign a ru.sfedu.diplomabackend.model.User object into the ru.sfedu.diplomabackend.model.User.created field that holds a java.util.Date object. Square peg, round hole.
Caused by: java.lang.IllegalArgumentException: Can not set java.util.Date field ru.sfedu.diplomabackend.model.User.created to ru.sfedu.diplomabackend.model.User
You must have some offending code not shown to us here.
P.S. As commented, you should never use the terrible Date class. Replaced years ago by java.time.Instant.
I am trying to execute this query:
#Override
public UserInfo get(Long id) {
String sql = "SELECT * FROM users WHERE id = ? ";
List<UserInfo> list = jdbcTemplate.query(sql,new UserInfoMapper(),id);
return list.get(0);
}
but jdbc return empty list and I get exception at return line.
But if try to execute directly though the console it returns:
Query, Answer
Query was executed with id 1 and retured correct anwser;
But in method its returned this
I couldn't find any same questions so that may be point at my inattention to something. But I can't see any problem that may cause this. Thanks in advance;
Updated 1
Changing code to
#Override
public UserInfo get(Long id) {
String sql = "SELECT * FROM users WHERE id = ? ";
List<UserInfo> list = jdbcTemplate.query(sql, new Object[] {id},new UserInfoMapper());
return list.get(0);
}
resulted in same: result
Updated 2
#Override
public UserInfo mapRow(ResultSet resultSet, int i) throws SQLException {
UserInfo info = new UserInfo();
info.setId(resultSet.getLong("id"));
info.setFirstname(resultSet.getString("firstname"));
info.setMiddlename(resultSet.getString("middlename"));
info.setLastname(resultSet.getString("lastname"));
info.setUsername(resultSet.getString("username"));
info.setPassword(resultSet.getString("password"));
info.setEmail(resultSet.getString("email"));
info.setMobilephone(resultSet.getString("mobilephone"));
info.setPosition(resultSet.getString("position"));
return info;
}
public class UserInfo {
private Long id;
private String firstname;
private String middlename;
private String lastname;
private String username;
private String password;
private String email;
private String mobilephone;
private String position;
public UserInfo() {
}
}
Getter and setters for each field is there but I think there is no need to show them up.
Check user credentials that you are using to connect database from your application and the user credentials in console. And also check owner schema , table owner schema in your application.
I am trying to create a mini chat application that has users table. The users table has a field called isAdmin that identifies that such a particular user is an admin and if isAdmin is set to false such a user is a customer
the user.java table fields
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "userId")
private Long id;
#Column(nullable = false)
private String name;
#Column(unique = true, nullable = false)
private String email;
#Column(nullable = false)
private long timestamp;
#Column(nullable = true)
private boolean isAdmin;
When I am trying to save a user, I try maintaining a request-response setAttribute method parameter using email field to hold the session attribute email is unique in my db
snippet of the code
#RequestMapping(value = "/create-user", method = RequestMethod.POST)
public ModelAndView createUser(HttpServletRequest request,
HttpServletResponse response,
#RequestParam String name,
#RequestParam String email) {
try {
// create new user object
User user = new User();
user.setName(name);
user.setEmail(email);
user.setTimestamp(new Date().getTime());
// save user in db (if new)
if (_userDao.getByEmail(email) == null) {
request.getSession().setAttribute("email", email);
_userDao.save(user);
}
} catch (Exception e) {
e.printStackTrace();
//logger.error("Exception in creating user: ", e.getStackTrace());
}
return new ModelAndView("redirect:/");
}
I am getting all the chats by email using requests.getSession.getAttribute as shown
#ResponseBody
#RequestMapping(value = "/get-all-chats", method = RequestMethod.GET)
public List<Chat> getAllChats(HttpServletRequest request,
HttpServletResponse response) {
String email = (String) request.getSession().getAttribute("email");
try {
if (email != null) {
return _chatDao.getAll(email);
}
} catch (Exception e) {
e.printStackTrace();
logger.error("Exception in fetching chats: ", e.getStackTrace());
}
return null;
}
my dao method has a query to retrieve all the chats based on the email session attribute that was set
public List getAll(String email) {
String hql = "from Chat c where c.user.email = :email";
return _sessionFactory.getCurrentSession().createQuery(hql).setParameter("email", email).list();
my challenge/confusion is that when I fetch the chat the user can only see his chat and the admin can only see his chat. the chat is not transferred between the admin and the user. Kindly assist.
With this search.jsp, it finds matches all words searched by user, then removes duplicate found users and shows a list of found matches.
I can only search for e-mail, firstname, lastname, username of a user, but I also want to search skills, and show the users who match that skill found.
For example I search for username; Admin, it finds the admin and shows
this person in the result. This works now, but I also want this;;; If
I search for Java, Then I want everybody that has the skill Java to
show up in the result.
I know it is easier with SQL query's, but this is different.
I have provided the models and database information below;
database:
**Table name: User**
userId
emailAddress
firstname
lastname
username
**Table name: user_skill**
User_userId
skills_skillId
**Table name: skill**
skillId
name
where it all happens : : : search.jsp:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Hij komt er in");
//get the action
String uri = request.getRequestURI();
String action = uri.substring(uri.lastIndexOf("/") + 1);
if (action.equals("searchUser")) {
Session session = HibernateUtil.getSessionFactory().openSession();
String searchQuery = request.getParameter("searchQuery");
String[] params = searchQuery.split(" ");
// Found users
List<User> usersFound = new ArrayList<User>();
// Exact match
String hqlMatch = this.getSearchHqlQuery(params, "AND");
List<User> exactResult = session.createQuery(hqlMatch).list();
if (exactResult != null && !exactResult.isEmpty()) {
usersFound.addAll(exactResult);
} // Multiple search
else {
String hqlLike = this.getSearchHqlQuery(params, "OR");
List<User> likeResult = session.createQuery(hqlLike).list();
if (likeResult != null && !likeResult.isEmpty()) {
usersFound.addAll(likeResult);
}
}
System.out.println("size:" + usersFound.size());
// set our results on the request and redirect back
request.setAttribute("users", usersFound);
request.setAttribute("usersSize", usersFound.size());
request.setAttribute("usersSizeResults", usersFound.size());
redirect(request, response, "/search.jsp");
session.close();
}
}
private String getSearchHqlQuery(String[] params, String andOrfilter) {
StringBuilder hql = new StringBuilder();
hql.append("from User ");
if (params.length > 0) {
hql.append("where ");
for (int i = 0; i < params.length; i++) {
if (i > 0) {
hql.append(andOrfilter);
}
hql.append(" (username like '%").append(params[i]);
hql.append("%' OR firstname like '%").append(params[i]);
hql.append("%' OR lastname like '%").append(params[i]);
hql.append("%' OR emailAddress like '%").append(params[i]);
hql.append("%') ");
}
}
return hql.toString();
}
model.user.java:
#Entity
public class User implements Serializable{
#Id
#GeneratedValue
private int userId;
private String username, firstname, lastname, emailAddress, position, password;
private String fullName;
private boolean isAdmin;
#ManyToMany
private List<Skill> skills;
public User(){
}
model.skill.java:
#Entity
public class Skill implements Serializable {
#Id
#GeneratedValue
private long skillId;
#Column(columnDefinition = "varchar(25)")
private String name;
#Column(columnDefinition = "varchar(25)")
private String level;
#Column(columnDefinition = "varchar(250)")
private String description;
public Skill() {
}
Add a join to the skills, and an or clause to your query:
select distinct u from User u
left join u.skills skill
where ... (existing or clauses)
or skill.name like :param
Also, your code is opened to SQL injection attacks, and will fail if the param contains a single quote. Use a named parameter as shown above.