How to deal with Backspace while taking in password in Java? - java

I need to delete last character entered by user while entering password and I need help in handling Backspace pressed by user.
Below is the code I wrote for Login, how to modify it so that I can handle Backspace ?
void login(){
//As mentioned on internet
Console con=null;
con=System.console();
System.out.println("==============================================================");
System.out.println("\t\t\t LOGIN MENU\n");
System.out.print("\tEnter User Name: ");
String userName=scan.next();
System.out.print("\tEnter Your Password: ");
char[] password = con.readPassword("");
System.out.println(password);
System.out.println("==============================================================");
String pass=new String(password);
//Arrays.fill is used to fill 'spaces' to replace password (Security Concerns)
java.util.Arrays.fill(password, ' ');
//System.out.println(password);
con.flush();
}
Thank You! :)

Related

Two if statement is executed in java code

Im currently trying to do a validation for staff login form. but i realized in my validation output that whenever i enter a value to the username text field, it still pops up the message "please enter your username" then the "invalid credentials"message box. Here is my code down below :
String username = usernameTxt.getText();
String password = passwordTxt.getText();
if (username.contains(""))
{
JOptionPane.showMessageDialog(null,"Please Enter Your Username Credentials.");
}
else if (password.contains (""))
{
JOptionPane.showMessageDialog(null,"Please Enter Your Password Credentials.");
}
else if (password.contains ("") && (username.contains("")))
{
JOptionPane.showMessageDialog(null,"Please Enter Your Login Credentials.");
}
if ((username.contains("staff") && password.contains ("pass")))
{
JOptionPane.showMessageDialog(null,"Login Successfull","Success",JOptionPane.INFORMATION_MESSAGE);
passwordTxt.setText(null);
usernameTxt.setText(null);
staffdashboard sd = new staffdashboard();
sd.setVisible(true);
this.setVisible(false);
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Login Details","Login Error",JOptionPane.ERROR_MESSAGE);
passwordTxt.setText(null);
usernameTxt.setText(null);
}
enter user message box
invalid login details message box
What am i missing out and how do stop the form to output 2 message box at once?
The problem is in the first if statement: username.contains("")
Each String contains empty String.
You should replace it with if("".equals(username))
Or use StringUtils.isBlank(username);
And the same for all the contains("")
#Naya's answer is correct, however you may want to remove any empty spaces assuming they are not allowed as valid input, so :
if (username.trim().equals("")) ...
else if (password.trim.equals("")) ...
...

How to fix while loop error login logout system (no database) (also is there a code about session time)?

I create a basic login and logout system (no database) with the only username given for my school homework, but I have problems with while loops and also session time.
I tried to copy and paste a group of codes to different parts of this main code so that I can get my expected outcome but it turns out to be a bit faulty. I tried to search on the internet about session time but I got nothing.
while (login = true){
try {
System.out.println("Enter your name:");
String name = cue.nextLine();
System.out.println("--------------------");
System.out.println("");
System.out.println("Date and Time of Login:");
System.out.println(dtf.format(now));
System.out.println("");
System.out.println("--------------------");
System.out.println();
System.out.println("Enter your name to log out:");
String logout = cue.nextLine();
System.out.println("");
if (logout.equals(name)){
System.out.println("--------------------");
System.out.println("");
System.out.println("Date and Time of Logout:");
System.out.println(dtf.format(now));
System.out.println("Session Time:");
/*can you also please tell me what code to tell the gap between the
login time and log out time?*/
System.out.println("");
System.out.println("--------------------");
login = false;
} else {
login = true;
}
} catch (Exception e){
cue.nextLine();
} finally{
System.out.println("Do you want to register again? 0 for yes and 1 for no");
int no = cue.nextInt();
if (no==0) {
login = true;
} else if (no==1) {
System.exit(1);
} else {
System.out.println("1 or 0 only!");
}
}
}
This must be the expected output:
if the name is correct:
Enter your name:
nmae
--------------------
Date and Time of login:
2019/02/03 16:38:46
--------------------
Enter your name to log out:
nmae
--------------------
Date and Time of logout:
2019/02/03 16:38:46
Session Time:
(This must show how many minutes and seconds a client uses the program)
--------------------
Do you want to register again? 0 for yes and 1 for no
0
Enter your name:
incorrect and it is corrected later on:
Enter your name:
name
--------------------
Date and Time of login:
2019/02/03 16:38:46
--------------------
Enter your name to log out:
nmae
Enter your name to log out:
name
but it turns out that on second loop, third loop and so on, the program asks me to "enter your name to log out" and "Do you want to register again? 0 for yes and 1 for no" instead. The "enter your name" part prints instead of asking my name.
and then when I enter 0 to exit, this error showed up C:\Users\DELL\AppData\Local\NetBeans\Cache\10.0\executor-snippets\run.xml:111: The following error occurred while executing this line:
C:\Users\DELL\AppData\Local\NetBeans\Cache\10.0\executor-snippets\run.xml:94: Java returned: 1
To get difference beetwen login time and logout time you can use Duration class from java8:
loginTime = LocalDateTime.now();
...
logoutTime = LocalDateTime.now();
Duration.between(loginTime, logoutTime).getSeconds();
You are returning an error level 1, which is the way a program terminates returning an error to the OS.
I can not test is as I do not use Windows, but you could try replacing System.exit(1) with System.exit(0).

Java Swing Dialog issue

When pressed the "Inregistrare" button a dialog pops, requesting the user to enter a password (set to "qwerty"). I want it keep displaying dialogs until the password is correct. The method is the following:
private void ItemInregistrareActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane dialog = new JOptionPane();
dialog.setWantsInput(true);
dialog.showInputDialog("Password please:");
while(dialog.getInputValue()!="qwerty")
dialog.showInputDialog("Mai baga o fisa.");
ItemInregistrare.setEnabled(false);
ItemOpen.setEnabled(true);
ItemSave.setEnabled(true);
}
The problem is it never gets out of the while, even if the password is correct. Any tips?
JOptionPane.showInputDialog is a static method and does not need any instance of JOptionPane. Moreover, it already returns the entered value or null if user pressed Cancel. So you don't need to call dialog.getInputValue().
You could try something like this:
String pwd;
do {
pwd = JOptionPane.showInputDialog("Password please:");
} while (pwd != null && !pwd.equals("qwerty"));
if (pwd == null) {
JOptionPane.showMessageDialog(null, "You pressed cancel");
} else {
JOptionPane.showMessageDialog(null, "Password is correct");
}
Try using
!dialog.getInputValue().equals("qwerty")
to compare strings

How to take an input in asterix WHILE typing?

I have to create a login id which takes a password(in java) but I want the input to be in asterix while the user types to make it look professional. Is it even possible? Please give the syntax for the code to be input as asterix.
If the question has been asked before (i could not find it) please link before removing.
Thank You.
If you want to get password from console try the following:
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
char passwordArray[] = console.readPassword("Enter your password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));

How to create a link for password reset link by sending mail to user in java

String messageValue[] = {userNameFull, programName, url, url, newPass, programSupportEmail, programSupportEmail, programSupportPhone, signature, programWebsite};
//String subject = MessageUtil.getMessage("mail.ResetPasswordSubject", locale);
//String message = MessageUtil.getDynamicMessage("mail.UserMailForgotPassword", messageValue, locale);;
//mail.ResetPasswordSubject = Password Reset Request
String subject = "Password Reset Request";
String message = "Dear {0}"
+ ",<br/>"
+ "Greetings from the {1} Team."
+ "<br/><br/>"
+ "Your password has been reset."
+ "<br/><br/>"
+ "To access your account, "
+ "please click on the following link:<br/>"
+ "<a href={2}>{3}</a>"
+ "<br/>"
+ "or copy the link and paste it in your browser&#39s address bar."
+ "<br/><br/>"
+ "Your temporarily reset password will expire in 7 days "
+ "and you will be asked to change it on your first login."
+ "<br/>Login to your account using the following details:"
//+ "<br/><br/>Password:{4}"
//+ "<br/><br/>Password:"+newPass+""
here i have to enter the link for reset password in place of this "Password:"+newPass+"" please help me
Follow the below steps to avoid brute force attack in security perspective.
Create 32 char alphanumeric string as sessionid which will be valid till 7days (in your case)
Create code 8/12 char conformation code
Put reset link with sessionid in query param and conf code in email.
When user clicks on link, get him to insert conf code on ui.
Validate session id and conf code
All are valid, then show him his username and ask for new password and confirm password.

Categories