BUG352-NEIL2 #59

Merged
mrlan merged 16 commits from BUG352-NEIL2 into Hui-Organize 2024-01-08 18:25:01 +08:00
3 changed files with 244 additions and 26 deletions

View File

@ -9,7 +9,7 @@ include 'Header.php';
<?php
// Only Lecturer or Admin could access this page
//Only Lecturer or Admin could access this page
if ($_SESSION['user_type'] != "Lecturer" && $_SESSION['user_type'] != "Admin") {
die("Sorry. Nothing to see here.");
}
@ -34,7 +34,7 @@ if ($_SESSION['user_type'] != "Lecturer" && $_SESSION['user_type'] != "Admin") {
</li>
<li class="nav-item">
<a class="nav-link" href="#tab-ins-accounts">Create instructor account</a>
<a class="nav-link" href="#tab-ins-accounts" id="tab_ins_accounts">Create instructor account</a>
</li>
<li class="nav-item">
@ -65,33 +65,36 @@ if ($_SESSION['user_type'] != "Lecturer" && $_SESSION['user_type'] != "Admin") {
}
?>
<form method="post" action="Script.php" id="create_account_form">
<form method="post" action="Script.php" id="create_account_form">
<input type="hidden" name="form_createlecturrer" value="true" required="" />
Full name
<input type="text" name="fullname" placeholder="Full Name" class="form-control" required=""> <br>
Email
<input type="text" name="email" placeholder="Email / Student Number" class="form-control" required=""> <br>
Passport No. (used as the initial password)
<input type="text" class="form-control" name="passport" placeholder="Passport No" required=""> <br>
<input type="text" name="email" placeholder="Email / Student Number" class="form-control" > <br>
Initial password (Enter a strong password or leave it empty to let LRR generate one)
<input type="password" class="form-control" name="password" minlength="8" placeholder="Initial password" > <br>
User type:
<?php
if ($_SESSION['user_type'] == "Lecturer") {
echo ' <input type="radio" name="type" value="TA" required="" id="role_TA"> TA (Teaching Assistant) ';
} else if ($_SESSION['user_type'] == "Admin"){
echo " <input type='radio' name='type' value='Lecturer' required='' id='role_lecturer'> Lecturer ";
}
?>
<?php
if ($_SESSION['user_type'] == "Lecturer") {
echo ' <input type="radio" name="type" value="TA" required="" id="role_TA"> TA (Teaching Assistant) ';
} else if ($_SESSION['user_type'] == "Admin"){
echo " <input type='radio' name='type' value='Lecturer' required='' id='role_lecturer'> Lecturer ";
}
?>
<br><br>
<button type="submit" class="btn btn-primary" id="create_btn">Create</button>
<button type="submit" class="btn btn-primary" name="create_btn">Create</button>
<?php
error_reporting(E_ALL);
if (isset($_SESSION['info_Admin_Users'])) {
echo '<hr><div class="alert alert-info" role="alert">' . $_SESSION['info_Admin_Users'] . '</div>';
echo '<hr><div class="alert alert-warning" role="alert">' . $_SESSION['info_Admin_Users'] . '</div>';
$_SESSION['info_Admin_Users'] = null;
}
if (isset($_SESSION['info_Admin_Users'])) {
echo '<hr><div class="alert alert-info" role="alert">' . $_SESSION['info_Admin_Users'] . '</div>';
echo '<hr><div class="alert alert-warning" role="alert">' . $_SESSION['info_Admin_Users'] . '</div>';
$_SESSION['info_Admin_Users'] = null;
}
?>
@ -108,7 +111,6 @@ if ($_SESSION['user_type'] != "Lecturer" && $_SESSION['user_type'] != "Admin") {
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Passport / ID </th>
<th>Reset password </th>
<th>Block/Activate </th>
</tr>
@ -130,7 +132,7 @@ if ($_SESSION['user_type'] != "Lecturer" && $_SESSION['user_type'] != "Admin") {
}
while ($row = mysqli_fetch_assoc($result)) {
$pass = $row['Passport_Number'];
$pass = $row['Password'];
$btn = "<button class='btn btn-warning' onclick=\"updatePassword(" . $row['User_ID'] . ",'$pass')\">Reset</button>";
if ($row['Status'] == "Active") {
$newstatus = "Blocked";
@ -140,7 +142,7 @@ if ($_SESSION['user_type'] != "Lecturer" && $_SESSION['user_type'] != "Admin") {
$btnBlock = "<button class='btn btn-success' onclick=\"blockUser(" . $row['User_ID'] . ",'$newstatus')\" id=\"activate_account_1\">Activate</button>";
}
echo "<tr><td>" . $row['User_ID'] . "</td><td>" . $row['Full_Name'] . "</td><td>" . $row['Email'] . "</td> <td>" . $row['Passport_Number'] . "</td><td>$btn</td><td>$btnBlock</td></tr>";
echo "<tr><td>" . $row['User_ID'] . "</td><td>" . $row['Full_Name'] . "</td><td>" . $row['Email'] . "</td><td>$btn</td><td>$btnBlock</td></tr>";
}
?>
</table>

View File

@ -2,6 +2,7 @@
include 'NoDirectPhpAcess.php';
?>
<?php
/*
@ -12,7 +13,6 @@ session_start();
date_default_timezone_set('Asia/Shanghai');
// Connect to MySQL database
include "get_mysql_credentials.php";
$con = mysqli_connect("localhost", $mysql_username, $mysql_password, "lrr");
@ -264,30 +264,52 @@ if (!empty($_POST["form_reset_password"])) {
}
// ############################### CREATE Lecturer/TA USER ##################################
if (!empty($_POST["form_createlecturrer"])) {
if (!empty($_POST["form_createlecturrer"])){
$email = mysqli_real_escape_string($con, $_POST["email"]);
$fullname = mysqli_real_escape_string($con, $_POST["fullname"]);
$type = mysqli_real_escape_string($con, $_POST["type"]);
$password = mysqli_real_escape_string($con, $_POST["passport"]);
// check if email is taken
$password = mysqli_real_escape_string($con, $_POST["password"]);
$pass_len = strlen($password);
if ($pass_len == 0) {
$password = generateStrongPassword();
}
$result = mysqli_query(
$con,
"SELECT * FROM Users_Table WHERE email='$email'"
"SELECT * FROM users_table WHERE email='$email'"
);
if (mysqli_num_rows($result) != 0) {
$_SESSION["info_Admin_Users"] = "Email address : " . $email . " is already in use.";
header("Location: Admin.php");
exit;
}
$password_hash = password_hash("$password", PASSWORD_DEFAULT);
$sql = "INSERT INTO `users_table`(`Email`, `Password`, `Full_Name`, `UserType`) VALUES "
. "('$email','$password_hash','$fullname','$type')";
if ($con->query($sql) === TRUE) {
$_SESSION["info_Admin_Users"] = $type . " user created successfully. Use email " . $email . " as account name and $password as password.";
$_SESSION["info_Admin_Users"] = $type . " user created successfully. Use email " . $email . " as account name and ". $password ." as password.";
header("Location: Admin.php");
} else {
echo "Error: " . $sql . "<br>" . $con->error;
alert("Error: " . $sql . "<br>" . $con->error);
}
}
// ### FUNCTION TO GENERATE INITIAL PASSWORDS ###//
function generateStrongPassword() {
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_';
$password_length = 12;
$gen_password = '';
for ($i = 0; $i < $password_length; $i++) {
$random_index = mt_rand(0, strlen($characters) - 1);
$gen_password .= $characters[$random_index];
}
// Return the generated password
return $gen_password;
}
// #### FUNCTION CHECK FILE TYPES ////

View File

@ -0,0 +1,194 @@
# Each time you run the test script reset the database.
neil marked this conversation as resolved Outdated

@neil

Did not test the undesirable case that the Lecturer tries to create an existing TA account.

Please add a test function called test_create_an_existing_TA_account().

@neil Did not test the undesirable case that the Lecturer tries to create an existing TA account. Please add a test function called `test_create_an_existing_TA_account()`.
# For this test script you won't need it since it changes
# the Ta's email and name automatically
import re
import time
import pytest
from faker import Faker
from selenium import webdriver
from selenium.webdriver.common.by import By
neil marked this conversation as resolved

@neil

Why have @pytest.mark.generate_password_1 necessary? Likewise for @pytest.mark.generate_password_2.

It seems that this decorator causes PytestUnknownMarkWarning on the console.

@neil Why have `@pytest.mark.generate_password_1 necessary`? Likewise for `@pytest.mark.generate_password_2`. It seems that this decorator causes `PytestUnknownMarkWarning` on the console.
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
faker = Faker()
@pytest.mark.skip(reason="function to be used in the test_scripts")
def createTA(driver, TA_name, emails, password):
full_name = driver.find_element('name', 'fullname')
full_name.send_keys(TA_name)
email = driver.find_element('name', 'email')
email.send_keys(emails)
pas = driver.find_element('name', 'password')
pas.send_keys(password)
usr_type = driver.find_element('name', 'type')
usr_type.click()
click_create = driver.find_element('name', 'create_btn')
neil marked this conversation as resolved Outdated

@neil

The comment should be # login as a Lecturer.

@neil The comment should be `# login as a Lecturer`.
click_create.click()
def login_lecturer(drivers):
# Open the website
drivers.get("http://localhost/lrr/")
drivers.maximize_window()
neil marked this conversation as resolved

@neil

The print statement actually has no effect. It won't print things on console.

@neil The `print` statement actually has no effect. It won't print things on console.
username_input = drivers.find_element('name', "user")
password_input = drivers.find_element('name', "password")
login_button = drivers.find_element('id', "login_btn")
# login as a Lecturer
neil marked this conversation as resolved Outdated

@neil

Why not move this helper function createTA() out of test_createTA()?

Also, probably it is a good idea to create a helper function for logging in, to avoid code duplication.

@neil Why not move this helper function `createTA()` out of `test_createTA()`? Also, probably it is a good idea to create a helper function for logging in, to avoid code duplication.
username_input.send_keys("lanhui@qq.com")
password_input.send_keys("nil1234H@")
# Click the login button
neil marked this conversation as resolved

@neil

There should be a whitespace before the operator =.

Make sure that there is a whitespace before and after = in each assignment statement.

@neil There should be a whitespace before the operator `=`. Make sure that there is a whitespace before and after `=` in each assignment statement.
time.sleep(5)
login_button.click()
admin_tab = drivers.find_element('id', 'admin_tab')
admin_tab.click()
cte_instructor = drivers.find_element('id', 'tab_ins_accounts')
cte_instructor.click()
neil marked this conversation as resolved

@neil

Please sleep for 3 seconds before clicking the Create button.

@neil Please sleep for 3 seconds before clicking the Create button.
time.sleep(25)
def test_createTA():
driver_open = webdriver.Chrome()
driver_open.maximize_window()
login_lecturer(driver_open)
try:
fullname = faker.name()
email = faker.email()
password = "new1452345678"
createTA(driver_open, fullname, email,password) # CREATE A TA WITH FULLNAME lanhuitest email lanhuitest@test.com password lanhui12345678
get_output = WebDriverWait(driver_open, 10).until(
EC.element_to_be_clickable((By.ID, "tab_ins_accounts"))
)
get_output.click()
get_output_msg = driver_open.find_element(By.CLASS_NAME, "alert-warning")
txt_alert = get_output_msg.text
time.sleep(20)
if txt_alert.find("TA user created successfully") == 0:
logout_button = WebDriverWait(driver_open, 15).until(
EC.element_to_be_clickable(
(By.XPATH, "//a[contains(@class, 'nav-link') and contains(@href, 'logout.php')]"))
)
time.sleep(5)
logout_button.click()
time.sleep(10)
username_input = driver_open.find_element('name', "user")
password_input = driver_open.find_element('name', "password")
login_button = driver_open.find_element('id', "login_btn")
# login as the new TA
username_input.send_keys(email) # login with credentials of the created TA
password_input.send_keys(password)
# Click the login button
time.sleep(20)
login_button.click()
time.sleep(20)
elif txt_alert.find("Email address ") == 0:
time.sleep(22)
driver_open.quit()
else:
driver_open.quit()
neil marked this conversation as resolved

@neil
Do we still need to write to a file?

@neil Do we still need to write to a file?
time.sleep(5)
finally:
driver_open.quit()
def test_generate_password():
driver_open = webdriver.Chrome()
login_lecturer(driver_open)
try:
fullname = faker.name()
email = faker.email()
password = ""
createTA(driver_open, fullname, email,
password) # CREATE A TA WITH FULLNAME lanhuitest email lanhuitest@test.com password lanhui12345678
get_output = WebDriverWait(driver_open, 5).until(
EC.element_to_be_clickable((By.ID, "tab_ins_accounts"))
)
get_output.click()
get_output_msg = driver_open.find_element(By.CLASS_NAME, "alert-warning")
txt_alert = get_output_msg.text
time.sleep(20)
neil marked this conversation as resolved

# login as a Lecturer

`# login as a Lecturer`
if txt_alert.find("TA user created successfully") == 0:
time.sleep(20)
email_pattern = r"Use email (\S+) as account name"
password_pattern = r" (\S+)\ as password."
email_match = re.search(email_pattern, txt_alert)
password_match = re.search(password_pattern, txt_alert)
if email_match and password_match:
# Extract email and password from the matches
email = email_match.group(1)
password = password_match.group(1)
logout_button = WebDriverWait(driver_open, 10).until(
EC.element_to_be_clickable(
(By.XPATH, "//a[contains(@class, 'nav-link') and contains(@href, 'logout.php')]"))
)
logout_button.click()
time.sleep(15)
username_input = driver_open.find_element('name', "user")
password_input = driver_open.find_element('name', "password")
login_button = driver_open.find_element('id', "login_btn")
# login as the new TA
username_input.send_keys(email) # login with credentials of the created TA
password_input.send_keys(password)
# Click the login button
time.sleep(20)
login_button.click()
time.sleep(20)
elif txt_alert.find("Email address ") == 0:
time.sleep(22)
driver_open.quit()
else:
driver_open.quit()
time.sleep(5)
finally:
driver_open.quit()
def test_existingTA():
driver_open = webdriver.Chrome()
login_lecturer(driver_open)
try:
# Use email nreyes@example.com as account name and new1452345678 as password.
fullname = "Maria"
email = "nreyes@example.com"
password = "new1452345678"
createTA(driver_open, fullname, email,
password) # CREATE A TA WITH FULLNAME lanhuitest email lanhuitest@test.com password lanhui12345678
get_output = WebDriverWait(driver_open, 5).until(
EC.element_to_be_clickable((By.ID, "tab_ins_accounts"))
)
get_output.click()
get_output_msg = driver_open.find_element(By.CLASS_NAME, "alert-warning")
txt_alert = get_output_msg.text
time.sleep(20)
if txt_alert.find("TA user created successfully") == 0:
time.sleep(20)
elif txt_alert.find("Email address ") == 0:
time.sleep(22)
driver_open.quit()
else:
driver_open.quit()
time.sleep(5)
finally:
driver_open.quit()