MongoDB Tutorial 3: Port and password

From The Uniform Server Wiki
Jump to navigation Jump to search

 

MongoDB Production Standalone
UniServer 6-Carbo.

MongoDB

Introduction

On the previous page we converted MongoDB to accept only authenticated connections. Server is usable however a user still needs to edit files should they wish to reconfigure the server. Similarly changing admin password requires several steps.

Our application’s user interface is intentional a little sparse. This page covers adding more functionality changing server port and admin password. These could be implemented by adding separate buttons to our application. Trouble with this approach application quickly starts to look overwhelmingly complex.

Added to this hard coded buttons are difficult to implement by this I mean you have a perfectly good button layout and want to add that little bit of extra functionality. It requires only a single button but where do you place it!

My approach; ignore all cosmetics until you have all your functionality components in place.

Top

Pop-up Template

I like pop-up because these are self-contained windows applications that are initiated by either a button (disadvantage explained above) or drop down menu.

WinBinder makes this extremely easy as far as its concerned just another function to run. Remember there are only five steps to creating a window, wrap this in a function and that window can be openened when you want.

//=== Create window ====================================================
function create_port_change_window($parent){

//=== 1) Create main window --------------------------------------------

$port_change = wb_create_window($parent, ModalDialog,
 "MongoDB Server configuration", 265, 175);

//=== 2) Create controls for the main window ---------------------------

//=== 3) Assign handler function to child window  ----------------------
  wb_set_handler($port_change, "process_port_change");
  wb_set_image($port_change, getcwd()."/images/utray.ico");  // Add logo   

//=== 5) Enter application loop ----------------------------------------
//wb_main_loop();                                  

}//=============================================== End Create window ===
//=== 4) Handler Function ==============================================
function process_port_change($window, $id){

  switch($id){

   case IDCLOSE:                      // Constant IDCLOSE (8) predefined 
    wb_destroy_window($window);       // Destroy the window
   break; 
  }
}
//=========================================== END 4) Handler Function ==

Create wrapper function

  • First create a wrapper function create_port_change_window($parent).
  • We are creating a child window hence $parent reference is passed to this function

Create Window

  • There are five steps to creating a window
  1. Create a ModelDialog window (cannot be minimised or maximised) Add window title text, set width and height
  2. Create controls. Buttons labels etc we will add these later
  3. Assign handler function. Processes button clicks and close window. Must have a unique name. Optionally add a logo (top left of window)
  4. Handler function see below
  5. Enter application loop. This is a child window and wb_main_loop() has already been called from main application hence this step is not required.

Handler function

  • Handler function has a common format is has been assigned to the child window in step 3. Any events generated in the child window are direct to this function for processing.

Test 1

Save the above template to a new file z_mongo\mongodb_1\control\window_port_pass.inc.php

For testing we will hijack the Help and Information button.

Edit file z_mongo\mongodb_1\control\mongo_db.php

Change this section To
   //=== Display help info ==========================
   case ID_HELP_BUTTON:          // Button 

     wb_exec('Notepad',INFO_TXT);

   break; 
   //======================= END Display help info ===

   //=== Display help info ===========================
   case ID_HELP_BUTTON:          // Button 

    create_port_change_window($window);
//    wb_exec('Notepad',INFO_TXT);

   break; 
   //======================== END Display help info ===

We need to load our template into this script navigate to the includes section add this line:

 include_once "window_port_pass.inc.php"; // Window port and password change

Run

  • Run Run_mongo_db.bat
  • Click "Help and Information" button
  • Result shown on right

With a working pop-up we add buttons and text fields.

Top

Add components

  • Create constants for buttons and edit boxes id must be unique
  • Create common variable
  • Add components to section 2
  • At the end of section 3 we call an initialisation function
  • Create an empty initialisation function

Code shown blow:

<?php

//-- Constants ----------------------------------------------------------------

define('ID_CHANGE_MONGO_PORT',      2010);
define('ID_CHANGE_ADMIN_PASSWORD',  2020);
define('ID_CHANGE_E_MONGO_PORT',    2030);
define('ID_CHANGE_E_ADMIN_PASS',    2040);

// Common variables
 global $port_change;          // Window pop up
 global $old_mongo_port;       // Port from config file
 global $old_admin_password;   // Pasword from file

//=== Creat window ============================================================
function create_port_change_window($parent){
   global $port_change;
   global $statusbar_port_change;

//=== 1) Create main window ---------------------------------------------------

$port_change = wb_create_window($parent, ModalDialog, "MongoDB Server configuration", 265, 175);

//=== 2) Create controls for the main window ----------------------------------

wb_create_control($port_change, Frame, 'Mongo Port', 5, 5, 245, 54, 0, 0, 0, 0);

wb_create_control($port_change, PushButton, 'Set MongoDB port ', 15, 25, 130, 25, ID_CHANGE_MONGO_PORT, 0, 0, 0);
wb_create_control($port_change, EditBox, '', 150,  27, 90, 20, ID_CHANGE_E_MONGO_PORT, WBC_NUMBER, 0, 0);

wb_create_control($port_change, Frame, 'Admin Password', 5, 64, 245, 54, 0, 0, 0, 0);

wb_create_control($port_change, PushButton, 'Set Admin password', 15, 84, 130, 25, ID_CHANGE_ADMIN_PASSWORD, 0, 0, 0);
wb_create_control($port_change, EditBox, '', 150, 86, 90, 20, ID_CHANGE_E_ADMIN_PASS,           0, 0, 0);

$statusbar_port_change = wb_create_control($port_change, StatusBar, "  Change server port or Admin password.");

//=== 3) Assign handler function to child window  -----------------------------
  wb_set_handler($port_change, "process_port_change");
  wb_set_image($port_change, getcwd()."/images/utray.ico");  // Add logo   

  main_init2(); // Inital status

//=== 5) Enter application loop -----------------------------------------------
//wb_main_loop();                                  

}//====================================================== End Create window ===

//=== 4) Handler Function =====================================================
function process_port_change($window, $id){
 global $statusbar_port_change;           // Status bar
 global $port_change;
 global $old_admin_password;

  switch($id){

   case IDCLOSE:                          // Constant IDCLOSE (8) predefined 
    wb_destroy_window($window);           // Destroy the window
   break; 
  }
}
//================================================== END 4) Handler Function ==

//=== Initialise Main =========================================================
function main_init2(){
 global $port_change;
 global $old_mongo_port;
 global $old_admin_password;

}//=================================================== END Initialise Main ===
?>

Top

Test 2

Save the above changes.

Run

  • Run Run_mongo_db.bat
  • Click "Help and Information" button
  • Result shown on right

With a working pop-up we add functionality.

Top

Initialisation function

A user can display this pop-up at any time. Buttons and text fields are enabled according to server status.

  • Password button and text field enabled only when server is running
  • Port button and text field only enabled when server stopped.
//=== Initialise Main =========================================================
function main_init2(){
 global $statusbar_port_change;           // Status bar
 global $port_change;
 global $old_mongo_port;
 global $old_admin_password;

 // Mongo port - Read from config file and display to user
 $old_mongo_port = (int)get_mongo_port_auth(); 
 wb_set_text(wb_get_control($port_change, ID_CHANGE_E_MONGO_PORT),$old_mongo_port);


 // Admin password - Read from config file and display to user
 $npwd =  get_name_pwd_array();       // Get name and password
 $old_admin_password = $npwd[1];      // Get passwordget_mysql_password();
 wb_set_text(wb_get_control($port_change, ID_CHANGE_E_ADMIN_PASS),$old_admin_password);


 // Check service status enable disable button text box accordingly 

 if(mongodb_running()){ // Server running

 wb_set_enabled(wb_get_control($port_change, ID_CHANGE_ADMIN_PASSWORD), TRUE); // Enable Password button 
 wb_set_enabled(wb_get_control($port_change, ID_CHANGE_E_ADMIN_PASS), TRUE);   // Enable Password Text 

 wb_set_enabled(wb_get_control($port_change, ID_CHANGE_MONGO_PORT), FALSE);    // Disable Port button 
 wb_set_enabled(wb_get_control($port_change, ID_CHANGE_E_MONGO_PORT), FALSE);  // Disable Port Text 

 wb_set_text($statusbar_port_change, "  Note: To change port Sop server");

 }
 else{                  // Server not running

 wb_set_enabled(wb_get_control($port_change, ID_CHANGE_MONGO_PORT), TRUE);     // Enable Port button 
 wb_set_enabled(wb_get_control($port_change, ID_CHANGE_E_MONGO_PORT), TRUE);   // Enable Port Text 

 wb_set_enabled(wb_get_control($port_change, ID_CHANGE_ADMIN_PASSWORD), FALSE); // Disable Password button 
 wb_set_enabled(wb_get_control($port_change, ID_CHANGE_E_ADMIN_PASS), FALSE);   // Disable Password Text 

 wb_set_text($statusbar_port_change, "  Note: To change passord Start server");

 }

}//=================================================== END Initialise Main ===

Top

Buttons and edit boxes

A user enters data into an edit box and clicks corresponding button.

Data is read from the edit box and validated, purpose of validation is to check for errors or data out of range. Unlike Internet forms we are not concerned with injection.

If data fails to validate alert user and display problem in status bar. Button action was performed successfully provide user with positive feedback such as a pop-up

Port

Port edit box was created with parameter WBC_NUMBER this forces all data entered to be numeric.

We don’t want to be too draconian with validation or treat a user as an idiot. However we do want to pickup silly typos and genuine ports that are not allowed. Strange as this may seem an empty field is valid data; if accepted will kill our application hence validation should ensure there is a value.

 //=== Change Mongo port ======================================================

 case ID_CHANGE_MONGO_PORT:         // Set MongoDB Listen port  (Default 27017)

 // Get user input
 $mongo_port = wb_get_text(wb_get_control($port_change, ID_CHANGE_E_MONGO_PORT)); 

 if($mongo_port =="" ){    // Must have an entry
   wb_play_sound (WBC_WARNING); // Alert user
   wb_set_text($statusbar_port_change, "  Please enter a port");
   break;
 }

 if($mongo_port =="80" || $mongo_port =="8080"){ // Default Apache ports do not use
   wb_play_sound (WBC_WARNING); // Alert user
   wb_set_text($statusbar_port_change, "  Invalid port 80 or 8080 ");
   break;
 }

 if( !($mongo_port >="1" && $mongo_port <= "65535") ){ // Range check 
   wb_play_sound (WBC_WARNING); // Alert user
   wb_set_text($statusbar_port_change, "  Valid port range 1 through 65535");
   break;
 }

    set_mongo_port_auth($mongo_port);  // Update port
    wb_set_text($statusbar_port_change, "  Mongo listen port changed");
    wb_message_box($window, "Mongo port was changed.","MongoDB Port", WBC_INFO); 

 break;
 //================================================== END Change Mongo port ===
  • Button click is passed to the handler function
  • Port button is detected by a case statement using ID_CHANGE_MONGO_PORT
  • User data entered in edit box is read using function wb_get_text
  • Validation checks for empty content. If empty alert user, display message in status bar and breaks out of the case. Not empty continue to next check.
  • Port 80 and 8080 are Apache default ports. If either entered alert user, display message in status bar and breaks out of the case. Neither value entered continue to next check.
  • Final check, is data within valid range. If not alert user, display message in status bar and breaks out of the case. Valid range continue to action implementation
  • Update configuration file with new port.
  • Alert user update was successful

Top

Admin Password

The admin password edit box is general purpose and accepts any character.

Again our validation is not draconian. We want to pickup silly typos, any trailing spaces. Set a minimum password length and range of valid characters.

Sounds like a lot of hard work! Not really the function preg_match() meets all the above.

 //=== Set Admin password =====================================================

 case ID_CHANGE_ADMIN_PASSWORD:          // Set Admin password
  
 // Get user input
 $new_password = wb_get_text(wb_get_control($port_change, ID_CHANGE_E_ADMIN_PASS)); 

 // Validate - require six or more alphanumeric characters
 if (!(preg_match("/^[A-Za-z0-9]{6,}$/", $new_password)) ) {
  wb_play_sound (WBC_WARNING); // Alert user
  wb_set_text($statusbar_port_change, "  Enter six or more alphanumeric characters");
  break;
 }

 $db_name = "admin";                  // When logged on select this db 
 $npwd =  get_name_pwd_array();       // Get name and password
 $user_name = $npwd[0];               // We want to change this users password
 $user_password = $new_password;      // Validated password 

 // Next function is multi-purpose 
 // Create a new database if it does not exist or select an existing one
 // Add a new user if that user does not exist or select named user 
 // Create a new password or update existing one for that usr 

  create_db_auth($db_name,$user_name,$user_password);

  set_name_pwd($user_name,$user_password);   // Update file
 
  wb_set_text($statusbar_port_change, "  Admin password updated");
  wb_message_box($window, "Admin password updated","Admin Password", WBC_INFO); 
 
  break; 

 //================================================= END Set Admin password ===
  • Button click is passed to the handler function
  • Admin button is detected by a case statement using ID_CHANGE_ADMIN_PASSWORD
  • User data entered in edit box is read using function wb_get_text
  • Validation check uses function preg_match
    • ^$ These two characters signify start and end of the input string to be tested. The entire string must be matched.
    • [A-Za-z0-9] First character must match one of those enclosed in square brackets
    • {6,} As a minimum six characters must match the previous character. More characters can match previous character
      Note: In other words the entire string must be composed of alphanumeric characters. If you can add additional valid characters.
  • On validation the password is updated using the multi-purpose function create_db_auth
  • Name password file is updated accordingly.

Top

Complete Script

Complete script shown below:

<?php

//-- Constants ----------------------------------------------------------------

define('ID_CHANGE_MONGO_PORT',      2010); // Button
define('ID_CHANGE_ADMIN_PASSWORD',  2020); // Button
define('ID_CHANGE_E_MONGO_PORT',    2030); // Edit box
define('ID_CHANGE_E_ADMIN_PASS',    2040); // Edit box

// Common variables
 global $port_change;            // Window pop up
 global $old_mongo_port;         // Port from config file
 global $old_admin_password;     // Pasword from file
 global $statusbar_port_change;  // Status bar

//=== Creat window ============================================================
function create_port_change_window($parent){
   global $port_change;
   global $statusbar_port_change;

//=== 1) Create main window ---------------------------------------------------

$port_change = wb_create_window($parent, ModalDialog, "MongoDB Server configuration", 265, 175);

//=== 2) Create controls for the main window ----------------------------------

wb_create_control($port_change, Frame, 'Mongo Port', 5, 5, 245, 54, 0, 0, 0, 0);

wb_create_control($port_change, PushButton, 'Set MongoDB port ', 15, 25, 130, 25, ID_CHANGE_MONGO_PORT, 0, 0, 0);
wb_create_control($port_change, EditBox, '', 150,  27, 90, 20, ID_CHANGE_E_MONGO_PORT, WBC_NUMBER, 0, 0);

wb_create_control($port_change, Frame, 'Admin Password', 5, 64, 245, 54, 0, 0, 0, 0);

wb_create_control($port_change, PushButton, 'Set Admin password', 15, 84, 130, 25, ID_CHANGE_ADMIN_PASSWORD, 0, 0, 0);
wb_create_control($port_change, EditBox, '', 150, 86, 90, 20, ID_CHANGE_E_ADMIN_PASS,           0, 0, 0);

$statusbar_port_change = wb_create_control($port_change, StatusBar, "  Change server port or Admin password.");

//=== 3) Assign handler function to child window  -----------------------------
  wb_set_handler($port_change, "process_port_change");
  wb_set_image($port_change, getcwd()."/images/utray.ico");  // Add logo   

  main_init2(); // Inital status

//=== 5) Enter application loop -----------------------------------------------
//wb_main_loop();                                  

}//====================================================== End Create window ===

//=== 4) Handler Function =====================================================
function process_port_change($window, $id){
 global $statusbar_port_change;           // Status bar
 global $port_change;
 global $old_admin_password;

  switch($id){

 //=== Change Mongo port ======================================================

 case ID_CHANGE_MONGO_PORT:         // Set MongoDB Listen port  (Default 27017)

 $mongo_port = wb_get_text(wb_get_control($port_change, ID_CHANGE_E_MONGO_PORT)); // Get user input

 if($mongo_port =="" ){    // Must have an entry
   wb_play_sound (WBC_WARNING); // Alert user
   wb_set_text($statusbar_port_change, "  Please enter a port");
   break;
 }

 if($mongo_port =="80" || $mongo_port =="8080"){ // Default Apache ports do not use
   wb_play_sound (WBC_WARNING); // Alert user
   wb_set_text($statusbar_port_change, "  Invalid port 80 or 8080 ");
   break;
 }

 if( !($mongo_port >="1" && $mongo_port <= "65535") ){ // Range check 
   wb_play_sound (WBC_WARNING); // Alert user
   wb_set_text($statusbar_port_change, "  Valid port range 1 through 65535");
   break;
 }

    set_mongo_port_auth($mongo_port);  // Update port
    wb_set_text($statusbar_port_change, "  Mongo listen port changed");
    wb_message_box($window, "Mongo port was changed.","MongoDB Port", WBC_INFO); 

 break;
 //================================================== END Change Mongo port ===

 //=== Set Admin password =====================================================

 case ID_CHANGE_ADMIN_PASSWORD:          // Set Admin password
  
 // Get user input
 $new_password = wb_get_text(wb_get_control($port_change, ID_CHANGE_E_ADMIN_PASS)); 

 // Validate - require six or more alphanumeric characters
 if (!(preg_match("/^[A-Za-z0-9]{6,}$/", $new_password)) ) {
  wb_play_sound (WBC_WARNING); // Alert user
  wb_set_text($statusbar_port_change, "  Enter six or more alphanumeric characters");
  break;
 }

 $db_name = "admin";                  // When logged on select this db 
 $npwd =  get_name_pwd_array();       // Get name and password
 $user_name = $npwd[0];               // We want to change this users password
 $user_password = $new_password;      // Validated password 

 // Next function is multi-purpose 
 // Create a new database if it does not exist or select an existing one
 // Add a new user if that user does not exist or select named user 
 // Create a new password or update existing one for that usr 

  create_db_auth($db_name,$user_name,$user_password);

  set_name_pwd($user_name,$user_password);   // Update file
 
  wb_set_text($statusbar_port_change, "  Admin password updated");
  wb_message_box($window, "Admin password updated","Admin Password", WBC_INFO); 

 
  break; 

 //================================================= END Set Admin password ===

   case IDCLOSE:                          // Constant IDCLOSE (8) predefined 
    wb_destroy_window($window);           // Destroy the window
   break; 
  }
}
//================================================== END 4) Handler Function ==

//=== Initialise Main =========================================================
function main_init2(){
 global $statusbar_port_change;           // Status bar
 global $port_change;
 global $old_mongo_port;
 global $old_admin_password;

 // Mongo port - Read from config file and display to user
 $old_mongo_port = (int)get_mongo_port_auth(); 
 wb_set_text(wb_get_control($port_change, ID_CHANGE_E_MONGO_PORT),$old_mongo_port);

 // Admin password - Read from config file and display to user
 $npwd =  get_name_pwd_array();       // Get name and password
 $old_admin_password = $npwd[1];      // Get passwordget_mysql_password();
 wb_set_text(wb_get_control($port_change, ID_CHANGE_E_ADMIN_PASS),$old_admin_password);

 // Check service status enable disable button text box accordingly 

 if(mongodb_running()){ // Server running

 wb_set_enabled(wb_get_control($port_change, ID_CHANGE_ADMIN_PASSWORD), TRUE); // Enable Password button 
 wb_set_enabled(wb_get_control($port_change, ID_CHANGE_E_ADMIN_PASS), TRUE);   // Enable Password Text 

 wb_set_enabled(wb_get_control($port_change, ID_CHANGE_MONGO_PORT), FALSE);    // Disable Port button 
 wb_set_enabled(wb_get_control($port_change, ID_CHANGE_E_MONGO_PORT), FALSE);  // Disable Port Text 

 wb_set_text($statusbar_port_change, "  Note: To change port Sop server");

 }
 else{                  // Server not running

 wb_set_enabled(wb_get_control($port_change, ID_CHANGE_MONGO_PORT), TRUE);     // Enable Port button 
 wb_set_enabled(wb_get_control($port_change, ID_CHANGE_E_MONGO_PORT), TRUE);   // Enable Port Text 

 wb_set_enabled(wb_get_control($port_change, ID_CHANGE_ADMIN_PASSWORD), FALSE); // Disable Password button 
 wb_set_enabled(wb_get_control($port_change, ID_CHANGE_E_ADMIN_PASS), FALSE);   // Disable Password Text 

 wb_set_text($statusbar_port_change, "  Note: To change passord Start server");

 }
}//=================================================== END Initialise Main ===
?>

Top

Test

Save the above script.

Run

  • Run Run_mongo_db.bat
  • Click "Help and Information" button
  • Result shown on right
  • Enter a new port
  • Close pop-up window

  • Start MongoDB server
  • Click "Help and Information" button
  • Result shown on right
  • Enter a new password.
  • Close pop-up
  • Run Momgo-client

Result:

  • Server runs on new port
  • Client uses this port and new password to access the server.

Top

Summary

That completes this pop-up interestingly the script is generic and can be used in the plugin version.

The script is useful of importance it allows the Admin password to be easily changed.

Next script covers creating a database and assigning a user.

Top