I am trying to Login with username and password in this way.Based on input values the pages should redirect.But i am not able to login.
<%#include file="database.jsp" %>
<%
String User = request.getParameter("User");
String Pass = request.getParameter("Pass");
if (User.equals("admin") && Pass.equals("admin123")) {
response.sendRedirect("AdminHome.jsp");
} else {
response.sendRedirect("Adminerror.jsp");
}
if (User != "admin") {
String sql = "select * from user where username='" + User + "' and password='" + Pass + "'";
rs = st.executeQuery(sql);
if (rs.next()) {
response.sendRedirect("userhome.jsp");
} else {
response.sendRedirect("usererror.jsp");
}
}
%>
You are using scriplet when you should use servlets. Servlets are simpler to write, test and debug than scriplets.
In you code, you will never properly reach the user part. Either you give correct admin user and pass and you should be redirected to AdminHome.jsp, else you pass through the response.sendRedirect("Adminerror.jsp");
If user was admin you should be properly redirected to AdminHome.jsp (provided there is nothing else after what you show). But else you will call twice sendRedirect which should cause an error.
You should at least test separately user and password for the admin part to avoid the response.sendRedirect("Adminerror.jsp"); branch if user is not admin and the multiple redirection error.
You should also try to type directly in your browser the URL with AdminHome.jsp to be sure that it is correctly accessible from the browser.
Related
I'm working in Yii2 with the Adldap extension found here: https://github.com/Adldap2/Adldap2
I'm running into an issue when I try to authenticate users on my ldap server. I can successfully make a connection and and retrieve user data, but when trying to authenticate if a user's username and password are correct or not, it always returns true, even if the creds are wrong. Below is my code snippet (with the config array not showing of course):
$ad->addProvider($config);
try {
// If a successful connection is made to your server, the provider will be returned.
$provider = $ad->connect();
//User below does return the correct information from the ldap server
$user = $provider->search()->users()->find('quillin');
try{
$provider->auth()->attempt("wrongUsername","wrongPassword");
die("WIN");
}catch( Exception $e ){
die("Exception " . $e);
}
}catch (\Adldap\Auth\BindException $e) {
die( "There was an issue binding / connecting to the server. <br />" . $e);
}
No matter what I put in for the username and password fields, it always returns true and hits the die("WIN"); line. In my composer.json file, i'm using "adldap2/adldap2": "v7.0.*"
I have also tried to bind the user using the following:
try{
$provider->auth()->attempt("wrongUsername","wrongPassword", $bindAsUser = true);
die("WIN");
}catch( Exception $e ){
die("lose :(");
die("Exception " . $e);
}
And that also always returns true;
I figured this out and will explain here in anyone else has the same issue.
1) $provider->auth()->attempt() should be wrapped in an IF, and not a try/catch.
2) The first parameter, $username, is actually looking for the userprincipalname, the docs had made it sound like it was looking instead for a username.
After that, I was able to authenticate the user successfully.
Here is my scenario.
A user will login to the system. Based on the username, I need to set the database in codeigniter configuration.
I know that the line $this->load->database() in each model loads the default database.
So, after checking the username in session(assuming that the user has successfully logged in), how can I dynamically load a database?
Below is something that I am looking for:
if(username == 'foo'){
$this->load->database('database_name');
}
An example of a model function that I have written is as follows:
public function check_valid_login($username, $password){
$this->db->from('tbl_user_details');
$this->db->where('email_address', $username);
$this->db->where('password', md5($password));
$query = $this->db->get();
$rowcount = $query->num_rows();
return $rowcount ;
}
On selecting the database, how can I still use statements like $this->db->from('tbl_user_details'); and so on. i.e., I want to use $this->db itself. Is it possible to do that?
I think I found a solution.
This is the strategy that I followed: When the user tries to login, a session variable $_SESSION['dynamic_db_username'] is set with the username that is provided by the user.
The following logic is used for selecting the database dynamically. The below code is written in config/database.php
/*Dynamic database selection - begins*/
if(!empty($_SESSION['dynamic_db_username'])){
$dynamic_db_username = $_SESSION['dynamic_db_username'];
if($dynamic_db_username == 'sample#domain.com')
{
$db['default']['database'] = 'database_1';
}
elseif($dynamic_db_username == 'sample2#domain.com')
{
$db['default']['database'] = 'database_2';
}
else
{
$db['default']['database'] = 'database_1';
}
}
else
{
$db['default']['database'] = 'database_1';
}
/*End*/
Kindly review this strategy and please let me know if this is right.
in the config folder there was a file named autoload.php
open the file
find first this code below
$autoload['libraries'] = array('');
you have to put "database" in the array , changed code will be like
$autoload['libraries'] = array('database');
after that you can use your database anytime and anywhere without loading it manually .
First up, I apologise if this is a duplicate in any way, but I have been trying many different things from this site for several hours now with no luck. And for the record, I am running OS X 10.11.5.
I have made this simple application using JDBC to connect to a database I created that is stored on my localhost (I am using phpMyAdmin, if that is any help):
#Override
public void actionPerformed(ActionEvent e) {
// The ID to search for
int search = Integer.parseInt(textField.getText());
// Setting up the connection to the database.
String url = "jdbc:mysql://my_ip_address:3306/javaDatabase";
String user = "root"; // root user
String password = ""; // no password
Connection con = null;
PreparedStatement searchID; // I used a prepared statement so I could include user input
ResultSet result = null; // results after SQL execution
try {
con = DriverManager.getConnection(url, user, password); // connect to MySQL
// Creating the prepared statement
searchID = con.prepareStatement("SELECT * FROM Names WHERE ID = ?");
// Setting the parameter to the user input
searchID.setInt(1, search);
result = searchID.executeQuery(); // execute the SQL query
while (result.next()) { // loop until the end of the results
String ID = result.getString("ID");
String FirstName = result.getString("FirstName");
String LastName = result.getString("LastName");
textArea1.setText("ID: " + ID + "\n" +
"First Name: " + FirstName + "\n" +
"Last Name: " + LastName + "\n");
}
} catch(SQLException e1) {
System.out.println("Exception caught " + e1.getMessage());
} finally {
try {
if (result != null) {
result.close();
}
if (con != null) {
con.close();
}
} catch(SQLException e2) {
System.out.println("SQLException caught " + e2.getMessage());
}
}
}
public static void main(String[] args) {
JavaWithSQL newJava = new JavaWithSQL();
}
Now, I am packaging this application up as an executable .JAR file, and want to be able to run it on someone else's computer and have it access the database and return the records.
I have tried instructions from here and here, without any luck. I looked at opening port 3306 on my Mac, but my firewall is off, but that doesn't seem to be the problem. I have also attempted to use GRANT privileges on the database in question using:
GRANT ALL PRIVILEGES ON javaDatabase.* TO '%'#'%' IDENTIFIED BY '';
to no avail. However, it does work on other computers when I explicitly write the computers IP address, like this:
GRANT ALL PRIVILEGES ON javaDatabase.* TO 'root'#'other_computer_ip' IDENTIFIED BY '';
But I need to be able to run it on my lecturer's computer, and in theory, other people's computers, without having to know everyone's IP addresses.
How can I do this? Am I missing something?
EDIT:
Okay, I have run the command
GRANT SELECT ON javaDatabase.* TO 'remoteUser'#'%' IDENTIFIED BY '';
FLUSH PRIVILEGES;
And now it works perfectly on any computer connected to the same network, but I need it to work even if I am connected to a different network.
I really need a pointer on this one.
You are using TO '%'#'%' IDENTIFIED BY '';
I'm not sure if that works. It should address the root user in your case.
GRANT ALL PRIVILEGES ON javaDatabase.* TO 'root'#'%' IDENTIFIED BY '';
In my main script, main.cgi, I present the user with a form to login. When this form is submitted it, another script is called to perform the verification, login.cgi.
login.cgi
# Convert request method to Uppercase eg: GET, POST
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
# If "POST" request sent, check login credentials
if ("$ENV{'REQUEST_METHOD'}" eq "POST"){
# Get login parameters
my $username = param('username');
my $password = param('password');
my $loginCheckResult = check_login($username, $password);
# If login was successful, create a cookie
if ($loginCheckResult){
# Set Cookie
my $cookie = CGI::Cookie->new(-name=>'USERID',-value=>$cookie_value);
print redirect(-uri => '/cgi-bin/main.cgi/', -cookie => $cookie);
# If login was Unsuccessful, redisplay the login page
} else {
# Do something here...
}
}
If the login is successful, I create a cookie and send the user back to the main page. Here I can test if a cookie is existent to determine whether the login was successful.
However, I'm not sure what to do if the login was unsuccessful.
main.cgi
if ($cookie eq ""){
print show_login_form();
# Login successful
} else{
print $cookie;
}
If I redirect them back to main.cgi, the login form will be showed again but no error will be displayed. If I include an error message underneath
print show_login_form();
then it will always be showed. Is there a way that I could send back a variable to indicate that the login failed and then check for this variable in main.cgi?
Or should I just create another login form in login.cgi upon an unsuccessful login attempt and include an error message in this form?
Thank you for your help.
The code in the 'successful login' code path is the code that generated the page a logged-in user should see.
Im fairly new to programming in JSP and I am making this web application where users need to log-in. I've done the registration of users but I am having problems when users are logging-in.
The main problem I am having is that, even though a user is able to successfully log-in, the information from the login form is lost. I need to retain the login information so that I can access the user's information during his/her session using the web application.
Here is the code that I currently have:
index.jsp (this is where the login form is shown)
<form name="Login Form" action="login.jsp"><table>
<tbody>
<tr>
<td><input type="text" name="emaillogin" value="email"/></td>
<td><input type="text" name="passlogin" value="password"/></td>
</tr>
<tr>
<td colspan="2" align="RIGHT><input type="submit" value="login" name="Login"/></td>
</tr>
</tbody></table></form>
login.jsp (this performs checking whether the user is valid or not, and redirects it to the user homepage if valid)
<%!
String email = "";
String password = "";
%>
<%
List users = new ArrayList();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", "pass");
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT email,password FROM users");
while (result.next()) {
users.add(result.getString(1));
users.add(result.getString(2));
}
con.close();
email = request.getParameter("emaillogin");
password = request.getParameter("passlogin");
int hasUser = 0;
Iterator<String> it = users.iterator();
while (hasUser == 0 && it.hasNext()) {
if (email.equals(it.next()) && password.equals(it.next())) {
hasUser = 1;
}
}
if (hasUser == 1) {
response.sendRedirect("homepage.jsp");
} else {
response.sendRedirect("index.jsp");
}
%>
homepage.jsp (this is where the user is redirected to after logging in, showing his/her email address)
.
.
<% out.println("Logged in as: " + request.getParameter("email")); %>
.
.
The current problem is that, null value is what I am getting from homepage.jsp. How can I solve this problem?
Thank you!
First of all I'll say - Avoid Java code in Jsp. Don't use JSP and Scriptlets to perform database operations. Always use Servlets.
You can use Jsp implicit tags (actions), EL and JSTL tag lib to format or present the data.
As per your question, you have to use session object to store data in one page and use them on another page.
I agree with putting this code into a servlet. A quick and simple way to pass a parameter is to the following:
response.sendRedirect("homepage.jsp?email="+email);
First of all let me give a clarity on Request parameters. Usually, request parameters will be in scope of request. So when you ask them in "Login.jsp" it will give you the email, password and what ever the fields you supplied from form. But when you are sending redirect to home page, those parameters won't be carried. So, when you find the user name and password is correct/ valid place them in session. So that you don't have to pass parameters manually to any request. Instead you can directly take the user name from "session" object and display where ever you want. This would be there in session, till the end of that session.
int hasUser = 0;
Iterator<String> it = users.iterator();
while (hasUser == 0 && it.hasNext()) {
if (email.equals(it.next()) && password.equals(it.next())) {
hasUser = 1;
}
}
if (hasUser == 1) {
session.setAttribute("email", email);
response.sendRedirect("homepage.jsp");
} else {
response.sendRedirect("index.jsp");
}
Usually this would be the process in real time. Of course Java code is not recommended here to use. Use JSTl, EL tags instead. In homepage.jsp you can display the email by taking from session.
Of course its too late reply.I guess this might help somebody facing the same problem.