Guest User

Developr Example Login Script

a guest
Oct 11th, 2012
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 14.81 KB | None | 0 0
  1. <?php
  2.  
  3.     // First we execute our common code to connection to the database and start the session
  4.     require("common.php");
  5.  
  6.     // This variable will be used to re-display the user's username to them in the
  7.     // login form if they fail to enter the correct password.  It is initialized here
  8.     // to an empty value, which will be shown if the user has not submitted the form.
  9.     $submitted_username = '';
  10.  
  11.     // This variable will hold the error, if any
  12.     $error = false;
  13.  
  14.     // If login form submitted
  15.     if (isset($_POST['username']))
  16.     {
  17.         // Check fields
  18.         if (empty($_POST['username']))
  19.         {
  20.             $error = 'Please enter your user name';
  21.         }
  22.         elseif (empty($_POST['password']))
  23.         {
  24.             $error = 'Please enter your password';
  25.         }
  26.         else
  27.         {
  28.             // This query retreives the user's information from the database using
  29.             // their username.
  30.             $query = "
  31.                 SELECT
  32.                     id,
  33.                     username,
  34.                     password,
  35.                     salt
  36.                 FROM users
  37.                 WHERE
  38.                     username = :username
  39.             ";
  40.  
  41.             $query_params = array(
  42.                 ':username' => $_POST['username']
  43.             );
  44.  
  45.             try
  46.             {
  47.                 // Execute
  48.                 $stmt = $db->prepare($query);
  49.                 $stmt->execute($query_params);
  50.  
  51.                 // Check if one row was found with the username
  52.                 $row = $stmt->fetch();
  53.                 if($row)
  54.                 {
  55.                     // Check password with secure hash and salt
  56.                     $check_password = hash('sha256', $_POST['password'] . $row['salt']);
  57.                     if($check_password === $row['password'])
  58.                     {
  59.                         // Bingo! Remove hash and salt to increase security and store user in session
  60.                         unset($row['salt']);
  61.                         unset($row['password']);
  62.                         $_SESSION['user'] = $row;
  63.                     }
  64.                     else
  65.                     {
  66.                         // Wrong password
  67.                         $error = 'Wrong username/password, please try again';
  68.                     }
  69.                 }
  70.                 else
  71.                 {
  72.                     // Wrong password
  73.                     $error = 'Wrong username, please try again';
  74.                 }
  75.             }
  76.             catch(PDOException $ex)
  77.             {
  78.                 $error = 'Failed to run query: ' . $ex->getMessage();
  79.             }
  80.  
  81.             // Check if AJAX request
  82.             $ajax = (isset($_SERVER['HTTP_X_REQUESTED_WITH']) and strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
  83.             if ($ajax)
  84.             {
  85.                 header('Cache-Control: no-cache, must-revalidate');
  86.                 header('Expires: '.date('r', time()+(86400*365)));
  87.                 header('Content-type: application/json');
  88.  
  89.                 echo json_encode(array(
  90.                     'logged' => !$error,
  91.                     'error' => $error
  92.                 ));
  93.                 exit();
  94.             }
  95.             elseif (!$error)
  96.             {
  97.                 header('Location: dashboard.php');
  98.                 exit();
  99.             }
  100.  
  101.             // Show them their username again so all they have to do is enter a new
  102.             // password.  The use of htmlentities prevents XSS attacks.  You should
  103.             // always use htmlentities on user submitted values before displaying them
  104.             // to any users (including the user that submitted them).  For more information:
  105.             // http://en.wikipedia.org/wiki/XSS_attack
  106.             $submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
  107.         }
  108.     }
  109.  
  110. ?><!DOCTYPE html>
  111.  
  112. <!--[if IEMobile 7]><html class="no-js iem7 oldie linen"><![endif]-->
  113. <!--[if (IE 7)&!(IEMobile)]><html class="no-js ie7 oldie linen" lang="en"><![endif]-->
  114. <!--[if (IE 8)&!(IEMobile)]><html class="no-js ie8 oldie linen" lang="en"><![endif]-->
  115. <!--[if (IE 9)&!(IEMobile)]><html class="no-js ie9 linen" lang="en"><![endif]-->
  116. <!--[if (gt IE 9)|(gt IEMobile 7)]><!--><html class="no-js linen" lang="en"><!--<![endif]-->
  117.  
  118. <head>
  119.     <meta charset="utf-8">
  120.     <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  121.  
  122.     <title>Stevens Fine Homes</title>
  123.     <meta name="description" content="">
  124.     <meta name="author" content="">
  125.  
  126.     <!-- http://davidbcalhoun.com/2010/viewport-metatag -->
  127.     <meta name="HandheldFriendly" content="True">
  128.     <meta name="MobileOptimized" content="320">
  129.     <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  130.  
  131.     <!-- For all browsers -->
  132.     <link rel="stylesheet" href="css/reset.css?v=1">
  133.     <link rel="stylesheet" href="css/style.css?v=1">
  134.     <link rel="stylesheet" href="css/colors.css?v=1">
  135.     <link rel="stylesheet" media="print" href="css/print.css?v=1">
  136.     <!-- For progressively larger displays -->
  137.     <link rel="stylesheet" media="only all and (min-width: 480px)" href="css/480.css?v=1">
  138.     <link rel="stylesheet" media="only all and (min-width: 768px)" href="css/768.css?v=1">
  139.     <link rel="stylesheet" media="only all and (min-width: 992px)" href="css/992.css?v=1">
  140.     <link rel="stylesheet" media="only all and (min-width: 1200px)" href="css/1200.css?v=1">
  141.     <!-- For Retina displays -->
  142.     <link rel="stylesheet" media="only all and (-webkit-min-device-pixel-ratio: 1.5), only screen and (-o-min-device-pixel-ratio: 3/2), only screen and (min-device-pixel-ratio: 1.5)" href="css/2x.css?v=1">
  143.  
  144.     <!-- Additional styles -->
  145.     <link rel="stylesheet" href="css/styles/form.css?v=1">
  146.     <link rel="stylesheet" href="css/styles/switches.css?v=1">
  147.  
  148.     <!-- Login pages styles -->
  149.     <link rel="stylesheet" media="screen" href="css/login.css?v=1">
  150.  
  151.     <!-- JavaScript at bottom except for Modernizr -->
  152.     <script src="js/libs/modernizr.custom.js"></script>
  153.  
  154.     <!-- For Modern Browsers -->
  155.     <link rel="shortcut icon" href="img/favicons/favicon.png">
  156.     <!-- For everything else -->
  157.     <link rel="shortcut icon" href="img/favicons/favicon.ico">
  158.     <!-- For retina screens -->
  159.     <link rel="apple-touch-icon-precomposed" sizes="114x114" href="img/favicons/apple-touch-icon-retina.png">
  160.     <!-- For iPad 1-->
  161.     <link rel="apple-touch-icon-precomposed" sizes="72x72" href="img/favicons/apple-touch-icon-ipad.png">
  162.     <!-- For iPhone 3G, iPod Touch and Android -->
  163.     <link rel="apple-touch-icon-precomposed" href="img/favicons/apple-touch-icon.png">
  164.  
  165.     <!-- iOS web-app metas -->
  166.     <meta name="apple-mobile-web-app-capable" content="yes">
  167.     <meta name="apple-mobile-web-app-status-bar-style" content="black">
  168.  
  169.     <!-- Startup image for web apps -->
  170.     <link rel="apple-touch-startup-image" href="img/splash/ipad-landscape.png" media="screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape)">
  171.     <link rel="apple-touch-startup-image" href="img/splash/ipad-portrait.png" media="screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait)">
  172.     <link rel="apple-touch-startup-image" href="img/splash/iphone.png" media="screen and (max-device-width: 320px)">
  173.  
  174.     <!-- Microsoft clear type rendering -->
  175.     <meta http-equiv="cleartype" content="on">
  176.  
  177.     <!-- IE9 Pinned Sites: http://msdn.microsoft.com/en-us/library/gg131029.aspx -->
  178.     <meta name="application-name" content="Developr Admin Skin">
  179.     <meta name="msapplication-tooltip" content="Cross-platform admin template.">
  180.     <meta name="msapplication-starturl" content="http://www.display-inline.fr/demo/developr">
  181.     <!-- These custom tasks are examples, you need to edit them to show actual pages -->
  182.     <meta name="msapplication-task" content="name=Agenda;action-uri=http://www.display-inline.fr/demo/developr/agenda.html;icon-uri=http://www.display-inline.fr/demo/developr/img/favicons/favicon.ico">
  183.     <meta name="msapplication-task" content="name=My profile;action-uri=http://www.display-inline.fr/demo/developr/profile.html;icon-uri=http://www.display-inline.fr/demo/developr/img/favicons/favicon.ico">
  184. </head>
  185.  
  186. <body>
  187.  
  188.     <div id="container">
  189.  
  190.         <hgroup id="login-title" class="large-margin-bottom">
  191.             <h1 class="login-title-image">Stevens Fine Homes</h1>
  192.         </hgroup>
  193.  
  194.         <?php
  195.  
  196.         if ($error)
  197.         {
  198.         ?><p class="message red-gradient"><?php echo htmlentities($error); ?><span class="close show-on-parent-hover">✕</span><span class="block-arrow bottom"><span></span></span></p>
  199.  
  200.         <?php
  201.         }
  202.  
  203.         ?><div id="form-block" class="scratch-metal">
  204.             <form method="post" action="index.php" id="form-login" class="input-wrapper blue-gradient glossy" title="Login">
  205.                 <ul class="inputs black-input large">
  206.                     <!-- The autocomplete="off" attributes is the only way to prevent webkit browsers from filling the inputs with yellow -->
  207.                     <li><span class="icon-user mid-margin-right"></span><input type="text" name="username" id="username" value="<?php echo $submitted_username; ?>" class="input-unstyled" placeholder="Login" autocomplete="off"></li>
  208.                     <li><span class="icon-lock mid-margin-right"></span><input type="password" name="password" id="password" value="" class="input-unstyled" placeholder="Password" autocomplete="off"></li>
  209.                 </ul>
  210.  
  211.                 <p class="button-height">
  212.                     <button type="submit" class="button glossy float-right" id="login">Login</button>
  213.                     <input type="checkbox" name="remind" id="remind" value="1" checked="checked" class="switch tiny mid-margin-right with-tooltip" title="Enable auto-login">
  214.                     <label for="remind">Remember</label>
  215.                 </p>
  216.             </form>
  217.         </div>
  218.  
  219.     </div>
  220.  
  221.     <!-- JavaScript at the bottom for fast page loading -->
  222.  
  223.     <!-- Scripts -->
  224.     <script src="js/libs/jquery-1.7.2.min.js"></script>
  225.     <script src="js/setup.js"></script>
  226.  
  227.     <!-- Template functions -->
  228.     <script src="js/developr.input.js"></script>
  229.     <script src="js/developr.message.js"></script>
  230.     <script src="js/developr.notify.js"></script>
  231.     <script src="js/developr.tooltip.js"></script>
  232.  
  233.     <script>
  234.  
  235.         /*
  236.          * How do I hook my login script to this?
  237.          * --------------------------------------
  238.          *
  239.          * This script is meant to be non-obtrusive: if the user has disabled javascript or if an error occurs, the login form
  240.          * works fine without ajax.
  241.          *
  242.          * The only part you need to edit is the login script between the EDIT SECTION tags, which does inputs validation
  243.          * and send data to server. For instance, you may keep the validation and add an AJAX call to the server with the
  244.          * credentials, then redirect to the dashboard or display an error depending on server return.
  245.          *
  246.          * Or if you don't trust AJAX calls, just remove the event.preventDefault() part and let the form be submitted.
  247.          */
  248.  
  249.         $(document).ready(function()
  250.         {
  251.             /*
  252.              * JS login effect
  253.              * This script will enable effects for the login page
  254.              */
  255.                 // Elements
  256.             var doc = $('html').addClass('js-login'),
  257.                 container = $('#container'),
  258.                 formBlock = $('#form-block'),
  259.  
  260.                 // If layout is centered
  261.                 centered;
  262.  
  263.             /******* EDIT THIS SECTION *******/
  264.  
  265.             /*
  266.              * AJAX login
  267.              * These functions will handle the login process through AJAX
  268.              */
  269.             $('#form-login').submit(function(event)
  270.             {
  271.                 // Values
  272.                 var username = $.trim($('#username').val()),
  273.                     password = $.trim($('#password').val());
  274.  
  275.                 // Check inputs
  276.                 if (username.length === 0)
  277.                 {
  278.                     // Display message
  279.                     displayError('Please fill in your username');
  280.                     return false;
  281.                 }
  282.                 else if (password.length === 0)
  283.                 {
  284.                     // Remove empty username message if displayed
  285.                     formBlock.clearMessages('Please fill in your username');
  286.  
  287.                     // Display message
  288.                     displayError('Please fill in your password');
  289.                     return false;
  290.                 }
  291.                 else
  292.                 {
  293.                     // Remove previous messages
  294.                     formBlock.clearMessages();
  295.  
  296.                     // Show progress
  297.                     displayLoading('Checking credentials...');
  298.  
  299.                     // Stop normal behavior
  300.                     event.preventDefault();
  301.  
  302.                     // AJAX call
  303.                     $.ajax(this.action, {
  304.                         type: this.method.toUpperCase(),
  305.                         data: {
  306.                             username:   username,
  307.                             password:   password
  308.                         },
  309.                         success: function(data)
  310.                         {
  311.                             if (data.logged)
  312.                             {
  313.                                 document.location.href = 'dashboard.php';
  314.                             }
  315.                             else
  316.                             {
  317.                                 formBlock.clearMessages();
  318.                                 displayError(data.error || 'Invalid username/password, please try again');
  319.                             }
  320.                         },
  321.                         error: function()
  322.                         {
  323.                             formBlock.clearMessages();
  324.                             displayError('Error while contacting server, please try again');
  325.                         }
  326.                     });
  327.                 }
  328.             });
  329.  
  330.             /******* END OF EDIT SECTION *******/
  331.  
  332.             // Handle resizing (mostly for debugging)
  333.             function handleLoginResize()
  334.             {
  335.                 // Detect mode
  336.                 centered = (container.css('position') === 'absolute');
  337.  
  338.                 // Set min-height for mobile layout
  339.                 if (!centered)
  340.                 {
  341.                     container.css('margin-top', '');
  342.                 }
  343.                 else
  344.                 {
  345.                     if (parseInt(container.css('margin-top'), 10) === 0)
  346.                     {
  347.                         centerForm(false);
  348.                     }
  349.                 }
  350.             };
  351.  
  352.             // Register and first call
  353.             $(window).bind('normalized-resize', handleLoginResize);
  354.             handleLoginResize();
  355.  
  356.             /*
  357.              * Center function
  358.              * @param boolean animate whether or not to animate the position change
  359.              * @param string|element|array any jQuery selector, DOM element or set of DOM elements which should be ignored
  360.              * @return void
  361.              */
  362.             function centerForm(animate, ignore)
  363.             {
  364.                 // If layout is centered
  365.                 if (centered)
  366.                 {
  367.                     var siblings = formBlock.siblings(),
  368.                         finalSize = formBlock.outerHeight();
  369.  
  370.                     // Ignored elements
  371.                     if (ignore)
  372.                     {
  373.                         siblings = siblings.not(ignore);
  374.                     }
  375.  
  376.                     // Get other elements height
  377.                     siblings.each(function(i)
  378.                     {
  379.                         finalSize += $(this).outerHeight(true);
  380.                     });
  381.  
  382.                     // Setup
  383.                     container[animate ? 'animate' : 'css']({ marginTop: -Math.round(finalSize/2)+'px' });
  384.                 }
  385.             };
  386.  
  387.             // Initial vertical adjust
  388.             centerForm(false);
  389.  
  390.             /**
  391.              * Function to display error messages
  392.              * @param string message the error to display
  393.              */
  394.             function displayError(message)
  395.             {
  396.                 // Show message
  397.                 var message = formBlock.message(message, {
  398.                     append: false,
  399.                     arrow: 'bottom',
  400.                     classes: ['red-gradient'],
  401.                     animate: false                  // We'll do animation later, we need to know the message height first
  402.                 });
  403.  
  404.                 // Vertical centering (where we need the message height)
  405.                 centerForm(true, 'fast');
  406.  
  407.                 // Watch for closing and show with effect
  408.                 message.bind('endfade', function(event)
  409.                 {
  410.                     // This will be called once the message has faded away and is removed
  411.                     centerForm(true, message.get(0));
  412.  
  413.                 }).hide().slideDown('fast');
  414.             }
  415.  
  416.             /**
  417.              * Function to display loading messages
  418.              * @param string message the message to display
  419.              */
  420.             function displayLoading(message)
  421.             {
  422.                 // Show message
  423.                 var message = formBlock.message('<strong>'+message+'</strong>', {
  424.                     append: false,
  425.                     arrow: 'bottom',
  426.                     classes: ['blue-gradient', 'align-center'],
  427.                     stripes: true,
  428.                     darkStripes: false,
  429.                     closable: false,
  430.                     animate: false                  // We'll do animation later, we need to know the message height first
  431.                 });
  432.  
  433.                 // Vertical centering (where we need the message height)
  434.                 centerForm(true, 'fast');
  435.  
  436.                 // Watch for closing and show with effect
  437.                 message.bind('endfade', function(event)
  438.                 {
  439.                     // This will be called once the message has faded away and is removed
  440.                     centerForm(true, message.get(0));
  441.  
  442.                 }).hide().slideDown('fast');
  443.             }
  444.         });
  445.  
  446.     </script>
  447.  
  448. </body>
  449. </html>
Add Comment
Please, Sign In to add comment