Authentication for Small Website, example? - php

I need a login to let 10 students to view educational material. Simple is good.
Perhaps it just redirects to a page if student logs in correctly. Can you send me a link or example, or best tutorial?
I was told JavaScript alone doesn't work, so the next simplest thing is preferred.
If there's an example where I don't have to rename all of my pages 'php', that would be better.
Thanks,

I used this when I was learning to do secure logon using PHP.
http://www.devshed.com/c/a/PHP/Creating-a-Secure-PHP-Login-Script/1/
Found it quite helpful.

Simple...
Create a file called functions and insert the following:
session_start();
$_GLOBALS['users'] = array(
//'username' => 'password'
'robert' => 'my_pass'
);
function isAuthed()
{
if(empty($_SESSION['logged_in']))
{
if(!empty($_REQUEST['username']) || !empty($_REQUEST['password']))
{
if(isset($_GLOBALS['users']) && is_array($_GLOBALS['users']))
{
if(isset($_GLOBALS['users'][$_REQUEST['username']]) && $_GLOBALS['users'][$_REQUEST['username']] === $_REQUEST['password'])
{
$_SESSION['logged_in'] = true;
return true;
}
}
}
}else
{
return true;
}
return false;
}
and then in your secured pages just do:
if(!isAuthed())
{
die("You're not authorized to see this page");
}
and on your login page just create a form that sends the username, password to the an area of your site that your authorizing
Note: This is not copy and past'able code, this is for example purposes only.

You could possibly "do" it with JavaScript if you did some kind of AJAX function which called a php page, and then returned your value. This could work, and it's how a lot of sites do their logins actually. So, your client wouldn't have to rename their site, and you could just set up an array of logins on the php page.
This would NOT be secure at all, but it would work just fine.
I guess you would do something like this (I'm going to use jQuery because it's easier to do Ajax with it. It's really easy to use, and if you're going to learn Javascript, it's probably better nowadays to know the basics and then use a framework library like jQuery)
$(document).ready(function(){
$("#NAME-OF-SUBMIT-BUTTON").submit(function(){
var username = $(this).find("#username");
var password = $(this).find("#password");
$("NAME-OF-DIV-FOR-RETURN").load('login.php', {['parameters']:,[username,password]},function(responseText){
if(responseText == 'SUCCESSFUL-RESPONSE-TEXT'){
$("#NAME-OF-FORM").html("Login Successful");
}
});
});
});
and of course you're going to want to set a session variable or cookie or something on your php page to indicate the user has logged in. Again, this is not very secure, but it's what I would do if it were like a homework assignment or just SUPER temporary. Of course, I would suggest making hard-coded usernames and passwords in an array on your original page in PHP with a postback to itself if you were going to go that temporary. Using Javascript and Ajax for this just seems like a bit much.
But, you requested it!

It depends on exactly what you're trying to do. If you want a pure-JS login system, you could do something fairly simple like XOR'ing a redirect page with a password, storing that in the page and then XOR'ing it again when they type in a password.
If you want an actual login-system, you need a back-end running some server (perhaps Node.js if you're trying to learn JavaScript), some type of database (e.g. MySQL), users stored in that database.
The front-end javascript might be responsible for validating the login via ajax. Using jQuery, something like:
function validateLogin(user, pass, successCallback, errorCallback){
$.get('/login', {user: user, pass:pass}, function(data){
if(data.status == 'success'){
successCallback();
}else{
errorCallback();
}
}
}

Related

Is this method of ajax login secure at all?

I am building a login form using ajax php and MySql.
I've done my fair share of research and I didn't like much posts found online, so I've built the below code.
My question is, is this secure at all? I'm not using any hashing and I'm not sure how it would be done with ajax. All the examples are much appreciated
INDEX.PHP
<script>
$(document).ready(function(){
$('form[name=loginForm]').submit(function() {
$.post('ajax.php', { username: $('[name=username]').val(),
password: $('[name=password]').val()},
function(data){
if(data.success){
alert('welcome');
}else{
alert("incorrect");
}
}, 'json');
return false;
});
});
</script>
ajax.php
<?php
if($_POST){
/** Fetch data from mysql **/
$u = $_POST['username'];
$p = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$u' AND password='$p' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$_SESSION['userid'] = $row["username"];
$_SESSION['userid'] = $row["username"];
$data['success'] = true;
}
}
else
{
$data['success'] = false;
}
/** Fetch data from mysql **/
echo json_encode($data);
} ?>
THANKS ALOT
My question is, is this secure at all?
No, it is not secure.
I'm not using any hashing and I'm not sure how it would be done with ajax.
Authentication actually cannot be done with ajax. With respect, you're barking up the wrong tree.
Start by reading this part of the PHP manual. http://php.net/manual/en/faq.passwords.php Go read it now. We'll wait.
Welcome back. You should never put your plain text password into a database. If you're not sure why that's true read about the "Ashley Madison data breach" online or go visit https://haveIBeenPwned.com/
You want to make it as hard as possible for a cybercriminal who steals your user table to guess your users' passwords. If you store them as text, they are trivial to guess.
Let's say your users are registered already. The point of your password authentication is to
gather the username and password from the user.
look up the user by name in your database, pulling back the hashed password.
compare the hashed password in your database with the one you gathered from the user. php's password_verify() function does this well.
if the validation fails, refuse the user's information. Do not give them any hint what was wrong. Simply tell them "your login failed." You don't want to tell them "you gave the right username but the wrong password."
if the validation succeeds, you then generate a session for that user so they can continue to use other pages in your web app without logging in again. Read about php sessions here.
you use a session id to represent the session. A session id is a hard-to-guess data token with a limited lifetime. php offers a session_create_id() method for this.
you put that session id in a cookie and feed it back to your browser. You can't reliably feed cookies to browsers with AJAX so your authentication strategy won't work.
Subsequent requests to your web app present the session id in the cookie. You check it to make sure it it's valid and it hasn't timed out. Then you do what the user asks you to do.

How to access to an external database securely?

I'm developing a mobile app which has to access to an external webapp (PHP + Codeigniter) to administrate the actions queried by ajax.
So by this way, there is a problem. If anyone see the urls used, could delete rows, or modify the user's info from the database. So I thought in this system to aboid this:
After a sucessful login I would do this:
// getToken : https://stackoverflow.com/a/13733588/2154101
$this->session->set_userdata('private_token', getToken(50));
$public_token = getToken(50);
$this->session->set_userdata('secure_token', md5("$private_token:$public_token"));
$data['token'] = $public_token;
// some stuff ...
// send $data in JSON
Then the client would the public token in the next query I would do this on the server:
$public_token = $this->input->post('token');
$data['token'] = get_public_token($public_token);
// some stuff ...
// send $data in JSON
Where get_public_token is within a helper with this code:
public get_public_token($public_token) {
$last_secure_token = $this->session->userdata('secure_token');
$private_token = $this->session->userdata('private_token');
$actual_token = md5("$private_token:$public_token");
if ($actual_token === $last_secure_token) {
$public_token = getToken(50);
$this->session->set_data('private_token', getToken(50));
$this->session->set_data('secure_token', md5("$private_token:$public_token"));
return $public_token;
} else { // you are cheating me ...
$this->session->sess_destroy();
redirect('/');
}
}
So only the user of this session could modify the data of the database.
I'm just trying to do the same explained here: https://stackoverflow.com/a/17371101/2154101
The session are encrypted, and I store them in a database too.
Do you think this method will work ok? Am I missing something important?
You should create an API for your mobile application. Create a authentication mechanism.
If your database holds user specific data, then you should create account for each user. So if the user sniffs the network and tries to call the api manually, then he could only change he's own data.
There are some API libraries for php out there, you should look into that.
Actually your solution is doing more than necessary. The only token of interest is the public_token sent back and forth. So you can throw away private_token and secure_token from session data, keeping only public_token for checking. Your current check is something like (X + 5)/2 == (14 + 5)/2 (is [received_token + 5]/2 equal to [14 + 5]/2 ?) when you can simplify to X == 14.
However if someone is sniffing the network, he can get the last token sent to a client and use it to hijack into that session. He can execute anything while the original client doesn't send a request with the outdated token, killing the session.
A better solution would be creating a secure_key after login and keep it at both ends (client and server). Then server would keep sending a new public_token at each response, but the client would send a md5(secure_key + public_token) at requests. This would narrow even more the hijacking window to the exact point where the session started. Without the original key, attackers can't create a valid md5.
However we are talking about minor hacking fans here. Anyone more zealous could hack that anyway. If you are concerned about that, then throw away all that stuff and simply use a HTTPS connection. With a trusted connection your sessions and access control rules are protected.
The better way is create API using SOAP or SAML2.
OAuth can be a very good solution: http://oauth.net/. It takes care of token and has a very secured API! If you wish to support secure authentication of web application + mobile application then it can be a good/proven solution!
On the other hand, it really depends on how complex your current system is and how the system is going to be in future.

Is it possible to block cookies from being set using Javascript or PHP?

A lot of you are probably aware of the new EU privacy law, but for those who are not, it basically means no site operated by a company resident in the EU can set cookies classed as 'non-essential to the operation of the website' on a visitors machine unless given express permission to do so.
So, the question becomes how to best deal with this?
Browsers obviously have the ability to block cookies from a specific website built in to them. My question is, is there a way of doing something similar using JS or PHP?
i.e. intercept any cookies that might be trying to be set (including 3rd party cookies like Analytics, or Facebook), and block them unless the user has given consent.
It's obviously possible to delete all cookies once they have been set, but although this amounts to the same thing as not allowing them to be set in the first place, I'm guessing that it's not good enough in this case because it doesn't adhere to the letter of the law.
Ideas?
I'm pretty interested in this answer too. I've accomplished what I need to accomplish in PHP, but the JavaScript component still eludes me.
Here's how I'm doing it in PHP:
$dirty = false;
foreach(headers_list() as $header) {
if($dirty) continue; // I already know it needs to be cleaned
if(preg_match('/Set-Cookie/',$header)) $dirty = true;
}
if($dirty) {
$phpversion = explode('.',phpversion());
if($phpversion[1] >= 3) {
header_remove('Set-Cookie'); // php 5.3
} else {
header('Set-Cookie:'); // php 5.2
}
}
Then I have some additional code that turns this off when the user accepts cookies.
The problem is that there are third party plugins being used in my site that manipulate cookies via javascript and short of scanning through them to determine which ones access document.cookie - they can still set cookies.
It would be convenient if they all used the same framework, so I might be able to override a setCookie function - but they don't.
It would be nice if I could just delete or disable document.cookie so it becomes inaccessible...
EDIT:
It is possible to prevent javascript access to get or set cookies.
document.__defineGetter__("cookie", function() { return '';} );
document.__defineSetter__("cookie", function() {} );
EDIT 2:
For this to work in IE:
if(!document.__defineGetter__) {
Object.defineProperty(document, 'cookie', {
get: function(){return ''},
set: function(){return true},
});
} else {
document.__defineGetter__("cookie", function() { return '';} );
document.__defineSetter__("cookie", function() {} );
}
I adapted Michaels codes from here to come up with this.
Basically it uses the defineGetter and defineSetter methods to set all the cookies on the page and then remove the user specified ones, this role could of course also be reversed if this is what you are aiming for.
I have tested this with third party cookies such as Google Analytics and it appears to work well (excluding the __utmb cookie means I am no longer picked up in Google Analytics), maybe you could use this and adapt it to your specific needs.
I've included the part about if a cookies name is not __utmb for your reference, although you could easily take these values from an array and loop through these that way.
Basically this function will include all cookies except those specified in the part that states if( cookie_name.trim() != '__utmb' ) { all_cookies = all_cookies + cookies[i] + ";"; }
You could add to this using OR or AND filters or pull from an array, database, user input or whatever you like to exclude specific ones (useful for determining between essential and non-essential cookies).
function deleteSpecificCookies() {
var cookies = document.cookie.split(";");
var all_cookies = '';
for (var i = 0; i < cookies.length; i++) {
var cookie_name = cookies[i].split("=")[0];
var cookie_value = cookies[i].split("=")[1];
if( cookie_name.trim() != '__utmb' ) { all_cookies = all_cookies + cookies[i] + ";"; }
}
if(!document.__defineGetter__) {
Object.defineProperty(document, 'cookie', {
get: function(){return all_cookies; },
set: function(){return true},
});
} else {
document.__defineGetter__("cookie", function() { return all_cookies; } );
document.__defineSetter__("cookie", function() { return true; } );
}
}
You can not disable it completely but you can override the default setting with .htaccess
Try
SetEnv session.use_cookies='0';
If it is optional for some users don't use .htaccess
if(!$isAuth)
{
ini_set('session.use_cookies', '0');
}
A little bit old but I think you deserve a answer that works:
Step 1: Don't execute the third party script code.
Step 2: Show the cookie banner.
Step 3: Wait until user accepts, now you can execute the third party script code..
Worked for me.
How about not paying attention to hoaxes?
Aside from the fact that this is old news, the text clearly says that it only applies to cookies that are not essential to the site's function. Meaning session cookies, a shopping basket, or anything that is directly related to making the site work is perfectly fine. Anything else (tracking, stats, etc.) are "not allowed" without permission.

Change all domains in links on a website

need some advice on how to fix an ugly situation. our forum has resided on a couple of different domains over the years. we lost one domain that was in use 5-6 yrs ago and apparently some posts on our forum still have links in the threads that point to the old domain. what would be the most efficient way to change all links that point to
http://www.olddomain.com/stuff
point to
http://www.newdomain.com/stuff
the only part that has changed is the domain name, all thread variables in the url remain the same. is this something that is best done client side with javascript/jquery or should it be handled on a server level with a PHP function (dont know where to begin here..)? some pseudocode that doesn't seem to do what I need it to on the client side...
$('a').each(function() {
var domanin = 'newdomain';
if(href.search('olddomain.com') != -1) {
$(this).attr('href', newdomain);
}
});
thank you
I think it will make more sense if you handle this in the back end. Search engines will not notice the change you make through JavaScript.
So I advise you search for those domains in your database and replace them there.
Well you should probably do this on the server side, as it was said before, but if you can't for whatever reason, here is what you could do on the javascript side of things.
$('a').each(function() {
this.host = 'www.newdomain.com';
});
Note that this example uses jQuery, but you could do the same in plain javascript with getElementsByTagName.
To do this in JavaScript (w/ jQuery):
$('a').each(function() {
var link = this.href;
if(link.search('olddomain.com') != -1) {
this.href = link.replace('olddomain.com', 'newdomain.com');
}
});
Here is a jsfiddle: http://jsfiddle.net/tHXxK/
However I would suggest changing the links in the database, just get rid of all the old references. To do this create a script that searches for the old URLs and replaces them, something like:
$query = mysql_query("SELECT [id], [link] FROM [table] WHERE [link] LIKE '%//olddomain.com/%' OR [link] LIKE '%//www.olddomain.com/%'", $db) or trigger_erroR(mysql_error());
while ($row = mysql_query($query)) {
$iQuery = mysql_query("UPDATE [table] SET [link]='" . mysql_real_escape_string(str_replace(array('//olddomain.com/', '//www.olddomain.com/'), array('//newdomain.com/', '//www.newdomain.com/'), $row['link']) . "' WHERE [id]=" . $row['id']), $db) or trigger_error(mysql_error());
}
If it'd be me, I would have used a server side script to replace all instances of the old domain with the new one and be done with it once and for all.
I assume your forum DB is rather a large one. For the sake of system resources you can write a multi-step script and do the job in multiple steps.
This is a better approach as it can improve the data consistency for search engines as well.

How to make Drupal redirect to pages after user registration

I have a Drupal website and I want to show different welcome pages, depending on what my users enter as profile fields. I can't use the global $user variable, because users are not automatically logged in (They have to very their email address before they can log in).
Where can I add code to set the redirect?
I've tried with $form['#redirect'] and $form_state['redirect'] in the form validator, but that didn't work.
You can use logintobogan for inspiration:
#implementation of hook_user
mymodule_user($op) {
if ($op == 'login') {
$_REQUEST['destination'] = '/user/will/be/redirected/here'
}
}
The important part is to make sure, that by the time the final drupal_goto() is called in user.module, you have set your $_REQUEST['destination'].
A few things to note:
Logintoboggan has a lot of code to deal with all sorts of edge-cases, such as redirecting out/to https. You can ignore these, if your case is simple.
Your module must be called after user.module and probably after other modules implementing hook_user, for they might change this global too. Very ugly, but the way this works in Drupal.
Do not -ever- issue drupal_goto() in any hook. Especially not hook_user, or hook_form_alter. drupal_goto will prohibit other hooks from being called; breaking functionality at the least, but often corrupting your database.
Do not issue drupal_goto() in form_alter callbacks such as "_submit", this might break many other modules and might even corrupt your database.
Similar to Berke's answer, but it seems like you just want this to be a one time thing. For that, you can check for the $account->access property to check their last login. If it is 0, then they are logging in for the first time.
This should work fine for email or no email validation.
<?php
/**
* Implements hook_user().
*/
function mymodule_user($op, &$edit, &$account, $category = NULL) {
switch ($op) {
case 'login':
// execute this if they have never accessed the site before
if ($account->access == 0) {
// run conditional logic based on profile fields
// to set destination here
$_REQUEST['destination'] = 'path/to/welcome-page';
}
break;
}
}
?>
I suggest you use the Login Destionation module or you can use the Rules module redirect action which is maybe to robust for your purpose.
Just in case you don't want to write your own custom module :-)

Categories