Week 11b - Database Coding
Week 11b - Database Coding
Password Management
Dr. Michele C. Weigle
CS 312 - Internet Concepts
Old Dominion University
2
Introduction to RDBMS
• RDBMS: relational database management system
• used by most Internet/Web applications for data persistence (storage)
• common systems: Oracle, MySQL, SQLite, etc.
3
Introduction to RDBMS
• Relation: a mathematical model of a data table
• e.g., User Table (a relation on all possible field values)
UserId Name Salt enc(Password) Address ...
rgrove Ralph Grove X71C77jE93 e7idkd^jehj*s 123 Main St.
8
jdoe Jane Doe C98EE3692 ijf82ksajaf&^3 456 High St.
89
...
4
Introduction to RDBMS
A table can represent
• Student Records Database - a person
- a thing
- an event (transaction)
Student Table
FinAid Table
5
SQL – Structured Query Language
• A language for accessing RDBs
• ISO/ANSI standard
6
SQL Data Types
• INT integer, 32 bits, signed or unsigned
• DECIMAL(p,s) p-digit decimal number, with s fractional digits
e.g., DECIMAL(6,2) - 9999.99
• CHAR(n) fixed length string, n characters
• VARCHAR(m)variable length string, up to m characters
• DATE yyyy-mm-dd
• TIME hh:mm:ss
• etc.
• NULL is a special value (any data type) that indicates –no value assigned–
7
Think, Discuss, Explain *
• What format will data have for these data types?
• INT
• DECIMAL(9, 4)
• VARCHAR(256)
• TIME
8
Basic SQL
• Define a table: CREATE TABLE
• View table contents: SELECT
• Update table data: UPDATE
• Delete table data: DELETE
https://www.sqlitetutorial.net 9
SQL – Create a Database Table
• Create a Pet table
CREATE TABLE pet (
species CHAR(1), /* D=dog, C=cat, B=bird,
F=fish */
name VARCHAR(25),
owner VARCHAR(25),
dob DATE,
PRIMARY KEY(name) /* the unique identifier for each pet
*/
species name * owner dob
);
C Fluffy Jane 2014-03-12
D Rover Susan 2019-11-13
B Polly John 2018-05-18
10
SQL – Add a Row to a Table
• Add a Pet to the table
INSERT INTO pet VALUES ('D', 'Fido', 'Robert', '2017-09-
15');
species name * owner dob
C Fluffy Jane 2014-03-12
D Rover Susan 2019-11-13
B Polly John 2018-05-18
D Fido Robert 2017-09-15
• Delete a Pet
DELETE FROM pet WHERE name='Rover';
species name * owner dob
C Fluffy Jane 2014-03-12
D Rover Susan 2019-11-13
B Polly John 2018-05-18
D Fido Robert Steve 2017-09-15
12
SQL – Retrieve Data
• Retrieve an entire table
SELECT * FROM pet;
• Retrieve one record from a table
SELECT * FROM pet WHERE name='Fido';
• Retrieve one field from one record from a table
SELECT owner FROM pet WHERE name='Fido';
• Retrieve entire table sorted by one field
SELECT * FROM pet ORDER BY dob ASC;
15
SQLite Commands Commands don't
have to be all caps
17
Think, Discuss, Explain *
• Find three errors in this SQL code
18
PHP – Retrieve Records (Pet Registry)
• Formulate Query
$query = 'SELECT * FROM pet'; // get all pets
https://www.cs.odu.edu/~mweigle/cs312/examples/#database
https://www.cs.odu.edu/~mweigle/cs312/rgrove/database/pet.php (source) 19
PHP – Retrieve Records (Pet Registry)
<table border="1"> Create an HTML table from a database table
<tr><th>Species</th><th>Name</th><th>Owner</th><th>DOB</th></tr>
<?php
$db = new SQLite3('pet.db'); // open the DBreturn sorted list
$query = 'SELECT * FROM pet'; // get all petsSELECT * FROM pet ORDER BY dob
ASC;
$result = $db->query($query); // execute the query
while ($pet = $result->fetchArray(SQLITE3_ASSOC) ) { // get next row
echo '<tr><td>' . $pet['species'] . '</td><td>' . $pet['name'] .
'</td><td>' . $pet['owner'] . '</td><td>' . $pet['dob'] . '</td></tr>';
}
$db->close(); // close the DB
?>
</table>
20
https://www.cs.odu.edu/~mweigle/cs312/rgrove/database/pet.php (source)
PHP – Insert Pet (Pet Registry)
<?php Insert a pet using form data
$species = $_POST['species'];
$name = $_POST['name'];
(addpet_handler.php)
...
$db = new SQLite3('pet.db'); // open the DB
// TO ADD: make sure not adding the same pet name
$command = "INSERT INTO pet VALUES('" . $species . "', '" . $name .
"', '" . $owner . "', '" . $dob . "')";
$result = $db->exec($command); // execute the command
if ($result) {
// ... row added ...
}
$db->close();
?>
21
https://www.cs.odu.edu/~mweigle/cs312/rgrove/database/addpet_handler.php (source)
PHP – Insert Pet (Pet Registry)
Make sure not adding the same pet name
(addpet_handler.php)
// check that primary key 'name' doesn't already exist in db
$query = "SELECT name FROM pet WHERE name='" . $name . "'";
$result = $db->query($query);
if ($result->fetchArray()[0] != null) {
// pet name already in database
$db->close();
require('pet.php');
return;
}
22
https://www.cs.odu.edu/~mweigle/cs312/rgrove/database/addpet_handler.php (source)
PHP – Insert Pet (Pet Registry)
Insert a pet using form data
(addpet_handler.php)
$command = "INSERT INTO pet VALUES('" . $species . "', '" . $name .
"', '" .
$owner . "', '" . $dob . "')";
$command:
INSERT INTO pet VALUES('Fido', 'D', 'Fred', '2019-05-04')
Form Data
23
https://www.cs.odu.edu/~mweigle/cs312/rgrove/database/addpet_handler.php (source)
Think, Discuss, Explain *
• How many rows of data will a SELECT statement return?
24
PHP – User Registration & Authorization
• Process Steps
1. Register new user
• generate salt, encrypt password, add user to database
2. Validate user login
• encrypt entered password, compare to stored value in database
• if successful, add authentication tokens to session
3. Validate request for secure resources
• check for authentication tokens in session
4. Logout user
• remove authentication tokens from session
25
PHP – Password Hash Function
• Generate a password "hash" one-way
• encrypted (password + salt) encryption:
$password = $_REQUEST['password']; // registration decryption is
$hash = password_hash($password, PASSWORD_DEFAULT); not possible
$2y$10$zffc9DxpzZmwMeh0D/7X4O0cyJu9UJ79ARu.1P1Hji2V/
ef7C6Ka2
alg cost salt hash (encrypted password+salt)
https://www.cs.odu.edu/~mweigle/cs312/examples/#database
https://www.cs.odu.edu/~mweigle/cs312/rgrove/userauth-db/index.php (source) 27
PHP – Register New User register_action.php
$userid = $_POST['userid'];
$password = $_POST['password'];
// ... input other fields; validate fields ...
// add to database
$command =
"INSERT INTO user VALUES('" . $userid . "', '" . $hash . "')";
$result = $db->exec($command);
if ($result) {
// registration success
$_SESSION['message'] = "New user registered";
require('index.php');
} else {
$_SESSION['message'] = "Registration failed";
require('register.php');
}
29
https://www.cs.odu.edu/~mweigle/cs312/rgrove/userauth-db/register_action.php (source)
PHP – Validate User Login login_action.php
$userid = $_POST['userid'];
$password = $_POST['password'];
// ... validate fields ...
// validate password
$valid = password_verify($password, $hash);
30
https://www.cs.odu.edu/~mweigle/cs312/rgrove/userauth-db/login_action.php (source)
PHP – Validate User Login login_action.php
if ($valid) { store
// valid password authorization
$_SESSION['userid'] = $userid; credentials in
$_SESSION['logged_in'] = TRUE;
the session
$_SESSION['message'] = $_SESSION['userid'] . " logged in";
$db->close();
require('index.php');
}
else {
// invalid password
unset($_SESSION['userid']);
unset($_SESSION['logged_in']);
$_SESSION['message'] = "Invalid credentials - please try
again";
$db->close();
require('login.php');
}
31
} https://www.cs.odu.edu/~mweigle/cs312/rgrove/userauth-db/login_action.php (source)
PHP – Validate Secure Resource Request
• login_check.php
if (empty($_SESSION['logged_in'] || ! $_SESSION['logged_in'] ) {
header ('Location: login.php'); // redirect to login page
}
• securepage.php
include('login_check.php');
32
PHP – Logout User
• logout_action.php
unset($_SESSION['userid']);
unset($_SESSION['logged_in']); // clear the
session
$_SESSION['message'] = "Logged Out";
header("Location: index.php"); // redirect to
home page
33
Process Steps
1. Register new user
4. Logout user
https://www.cs.odu.edu/~mweigle/cs312/examples/#database
https://www.cs.odu.edu/~mweigle/cs312/rgrove/userauth-db/index.php (source) 34
Think, Discuss, Explain *
• What is a password hash?
35
Recap
1. Introduction to RDBMS & SQL
2. Basic SQL Commands – define, view, update a table
3. SQLite Commands
4. PHP – Insert, Delete, Fetch (Pet Registry)
5. PHP – User Registration & Authorization
36