Return a value to a CGI script - html

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.

Related

Adldap2 authentication always returns true - Yii2

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.

Using Dancer2::Plugin::DBIC to pull values from database

I have a webapp where a user can log in and see a dashboard with some data. I'm using APIary for mock data and in my Postgres Database each of my users have an ID. These ID's are also used in the APIary JSON file with relevant information.
I'm using REST::Client and JSON to connect so for example the url for the user's dashboard is: "/user/dashboard/12345" (in Apiary)
and in the database there is a user with the ID "12345".
How can I make it so when the user logs in, their ID is used to pull the data that is relevant to them? (/user/dashboard/{id})? Any documentation or advice would be much appreciated!
The docs of Dancer2::Plugin::Auth::Extensible are showing one part of what you need to do already. In short, save the user ID in the session. I took part of code in the doc and added the session.
post '/login' => sub {
my ($success, $realm) = authenticate_user(
params->{username}, params->{password}
);
if ($success) {
# we are saving your user ID to the session here
session logged_in_user => params->{username};
session logged_in_user_realm => $realm;
} else {
# authentication failed
}
};
get '/dashboard' => sub {
my $client = REST::Client->new();
# ... and now we use the user ID from the session to get the
# from the webservice
$client->GET( $apiary . '/user/dashboard/' . session('logged_in_user') );
my $data = $client->responseContent();
# do stuff with $data
};
For those who want to know what I ended up doing:
Dancer2::Plugin::Auth::Extensible has
$user = logged_in_user();
When I printed this it showed me a hash of all the values that user had in the database including the additional ID I had. So I accessed the id with
my $user_id = $user->{user_id};
And appended $user_id to the end of the url!

How to login user and Admin in same page

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.

php/mysql:what's the idea to active/inactive a code from being executed

i have a php code to show online users,my question is that how to make an option(yes,no) in the admin panel to control the appearance of enabling or disabling the code
just i want to know the idea for making something like that?what are the fields required?what are the queries to do that?
or an article discuss the process of activate or in activate some code from being executed according the state of selected option(y,n)
and a practical snippet for that.......
session_start();
$session=session_id();
$time=time();
$time_check=$time-600; //SET TIME 10 Minute
$host="localhost"; // Host name
$username="advphp_advphp"; // Mysql username
$password="112233"; // Mysql password
$db_name="advphp_download"; // Database name
$tbl_name="user_online"; // Table name
// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name WHERE session='$session'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count=="0"){
$sql1="INSERT INTO $tbl_name(session, time)VALUES('$session', '$time')";
$result1=mysql_query($sql1);
}
else {
"$sql2=UPDATE $tbl_name SET time='$time' WHERE session = '$session'";
$result2=mysql_query($sql2);
}
$sql3="SELECT * FROM $tbl_name";
$result3=mysql_query($sql3);
$count_user_online=mysql_num_rows($result3);
echo "المتواجدون الان : "; echo $count_user_online + 30;
// if over 10 minute, delete session
$sql4="DELETE FROM $tbl_name WHERE time<$time_check";
$result4=mysql_query($sql4);
mysql_close();
You can think of the list of online users as a module that you can configure from a back end.
Keep a XML file with the list of all the modules and their statuses (enabled/disabled) and allow the user to disable/enable the module from the back end by setting the right value for the module name in the XML file.
When you need to check the module you can either load the XML file and check the status or just keep a session variable with the statuses of the modules and decide according to that variable weather to show it or not.
For each user add an extra field called privilege which stores if user has admin, special privilege
Write a php page like admin.php
if the logged in user has admin privilege then include the admin.php page in their homepage or else do not include the admin.php
admin,php will contain the additional features for an admin user
query
select username, status from tableName
where loginName='$user' and password='$password';
then in code
if(row['status'] == 'admin')
{
include_once('admin.php');
}

How to retain login information for subsequent use

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.