mercredi 23 mars 2016

If statement for User Authorisation

I have created an if statement for my code for a login and im trying to get the button to use an if statement so that if the Users details are authorised then they can be given access to the page.

Here is my code:

 <?php

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
     if ((isset($_POST['email']))  && (isset($_POST['password'])) ) {
        if (isAuthenticate($_POST['email'], $_POST['password']))
         header("Location: roster3101.php");
         exit();
    }
    }

    header("Location: index.php");

    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta content="width=device-width, initial-scale=1" name="viewport">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta content="" name="description">
    <meta content="" name="author">
    <link href="../../favicon.ico" rel="icon">
    <script src="http://ift.tt/1YWdgTw">
    </script>
    <title>Shifts</title><!-- Bootstrap core CSS -->
    <link href="bootstrap.min.css" rel="stylesheet">
    <!-- Custom styles for this template -->
    <link href="softwareproject.css" rel="stylesheet">
    <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
    <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->  

    <script src="ie-emulation-modes-warning.js">
    </script>
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="http://ift.tt/1xwklwE"></script>
      <script src="http://ift.tt/1qIredN"></script>
    <![endif]-->
</head>
<body background="dark.jpg">

    <br>
    <br>
    <br>
    <br>
    <br>
    <center>
        <table border="0" cellpadding="20px">
            <tr>
                <td>
                    <center>
                        <img height="375" src="logo10.png" width="375">
                    </center>
                </td>
                <td>
                    <form id="frmLogin" role="form">
         <h2><font color="white">The Online Roster</font></h2>

        <div class="form-group">
            <label for="txtEmail"><font color="white">Email address</font></label>
            <input type="email" class="form-control" id="txtEmail" placeholder="Enter email" name="email" />
        </div>
        <div class="form-group">
            <label for="txtPass"><font color="white">Password</font></label>
            <input type="password" class="form-control" id="txtPass" placeholder="Password" name="password" />
        </div><center>
        <button type="submit" class="rosterclicks">Login</button></center>


    </form>


                    <!-- <form class="form-signin">
                        <center>
                            <h2 class="form-signin-heading">The OnlineRoster</h2>
                        </center>
                        <label class="sr-only" for="inputEmail"></label>
                        <input autofocus="" class="form-control" id="inputEmail" placeholder="Email address" required="" type="email">
                        <label class="sr-only" for="inputPassword"></label>
                        <input class="form-control" id="inputPassword" placeholder="Password" required="" type="password">
                        <div class="checkbox">
                            <label><input type="checkbox" value="remember-me">Remember me</label>
                        </div>
                    </form> -->
                    <center>
                        <table border="0">
                            <tr>
                                <td>
                                    <!-- <form action="roster3101.php">
                                        <input class="rosterclicks" type=
                                        "submit" value="Login">
                                    </form> -->
                                </td>
                            </tr>
                        </table>
                    </center>
                </td>
            </tr>
        </table>
    </center>
    <script>

    var ref = new Firebase("http://ift.tt/1MD8Mu2");
    ref.createUser({
  email    : "admin@shiftsapp.com",
  password : "password"
}, function(error, userData) {
  if (error) {
    console.log("Error creating user:", error);
  } else {
    console.log("Successfully created user account with uid:", userData.uid);
  }
});

var ref = new Firebase("http://ift.tt/1MD8Mu2");
ref.authWithPassword({
  "email": "admin@shiftsapp.com",
  "password": "password"
}, function(error, authData) {
  if (error) {
    console.log("Login Failed!", error);
  } else {
    console.log("Authenticated successfully with payload:", authData);
  }
});

var routeMap = {
         '#/roster3101.php': {
             form: 'frmLogin',
        },
};

   // (function (jQuery, Firebase, Path) {
   //  "use strict";

   //  // the main firebase reference
   //  var rootRef = new Firebase('http://ift.tt/1MD8Mu2');

   //  // pair our routes to our form elements and controller
   //  var routeMap = {
   //      '#/test': {
   //          form: 'frmLogin',
   //          controller: 'login'
   //      },
   //          '#/logout': {
   //          form: 'frmLogout',
   //          controller: 'logout'
   //      },
   //          '#/register': {
   //          form: 'frmRegister',
   //          controller: 'register'
   //      },
   //          '#/profile': {
   //          form: 'frmProfile',
   //          controller: 'profile',
   //          authRequired: true // must be logged in to get here
   //      },
   //  };

    // create the object to store our controllers
    var controllers = {};

    // store the active form shown on the page
    var activeForm = null;

    var alertBox = $('#alert');

    function routeTo(route) {
        window.location.href = '#/' + route;
    }

    // Handle third party login providers
    // returns a promise
    function thirdPartyLogin(provider) {
        var deferred = $.Deferred();

        rootRef.authWithOAuthPopup(provider, function (err, user) {
            if (err) {
                deferred.reject(err);
            }

            if (user) {
                deferred.resolve(user);
            }
        });

        return deferred.promise();
    };

    // Handle Email/Password login
    // returns a promise
    function authWithPassword(userObj) {
        var deferred = $.Deferred();
        console.log(userObj);
        rootRef.authWithPassword(userObj, function onAuth(err, user) {
            if (err) {
                deferred.reject(err);
            }

            if (user) {
                deferred.resolve(user);
            }

        });

        return deferred.promise();
    }

    // create a user but not login
    // returns a promsie
    function createUser(userObj) {
        var deferred = $.Deferred();
        rootRef.createUser(userObj, function (err) {

            if (!err) {
                deferred.resolve();
            } else {
                deferred.reject(err);
            }

        });

        return deferred.promise();
    }

    // Create a user and then login in
    // returns a promise
    function createUserAndLogin(userObj) {
        return createUser(userObj)
            .then(function () {
            return authWithPassword(userObj);
        });
    }

    // authenticate anonymously
    // returns a promise
    function authAnonymously() {
        var deferred = $.Deferred();
        rootRef.authAnonymously(function (err, authData) {

            if (authData) {
                deferred.resolve(authData);
            }

            if (err) {
                deferred.reject(err);
            }

        });

        return deferred.promise();
    }

    // route to the specified route if sucessful
    // if there is an error, show the alert
    function handleAuthResponse(promise, route) {
        $.when(promise)
            .then(function (authData) {

            // route
            routeTo(route);

        }, function (err) {
            console.log(err);
            // pop up error
            showAlert({
                title: err.code,
                detail: err.message,
                className: 'alert-danger'
            });

        });
    }

    // options for showing the alert box
    function showAlert(opts) {
        var title = opts.title;
        var detail = opts.detail;
        var className = 'alert ' + opts.className;

        alertBox.removeClass().addClass(className);
        alertBox.children('#alert-title').text(title);
        alertBox.children('#alert-detail').text(detail);
    }

    /// Controllers
    ////////////////////////////////////////

    controllers.login = function (form) {

        // Form submission for logging in
        form.on('submit', function (e) {

            var userAndPass = $(this).serializeObject();
            var loginPromise = authWithPassword(userAndPass);
            e.preventDefault();

            handleAuthResponse(loginPromise, 'profile');

        });

        // Social buttons
        form.children('.bt-social').on('click', function (e) {

            var $currentButton = $(this);
            var provider = $currentButton.data('provider');
            var socialLoginPromise;
            e.preventDefault();

            socialLoginPromise = thirdPartyLogin(provider);
            handleAuthResponse(socialLoginPromise, 'profile');

        });

        form.children('#btAnon').on('click', function (e) {
            e.preventDefault();
            handleAuthResponse(authAnonymously(), 'profilex');
        });

    };

    // logout immediately when the controller is invoked
    controllers.logout = function (form) {
        rootRef.unauth();
    };

    controllers.register = function (form) {

        // Form submission for registering
        form.on('submit', function (e) {

            var userAndPass = $(this).serializeObject();
            var loginPromise = createUserAndLogin(userAndPass);
            e.preventDefault();

            handleAuthResponse(loginPromise, 'profile');

        });

    };

    controllers.profile = function (form) {
        // Check the current user
        var user = rootRef.getAuth();
        var userRef;

        // If no current user send to register page
        if (!user) {
            routeTo('register');
            return;
        }

        // Load user info
        userRef = rootRef.child('users').child(user.uid);
        userRef.once('value', function (snap) {
            var user = snap.val();
            if (!user) {
                return;
            }

            // set the fields
            form.find('#txtName').val(user.name);
            form.find('#ddlDino').val(user.favoriteDinosaur);
        });

        // Save user's info to Firebase
        form.on('submit', function (e) {
            e.preventDefault();
            var userInfo = $(this).serializeObject();

            userRef.set(userInfo, function onComplete() {

                // show the message if write is successful
                showAlert({
                    title: 'Successfully saved!',
                    detail: 'You are still logged in',
                    className: 'alert-success'
                });

            });
        });

    };

    /// Routing
    function isAuthenticate(email, passwd) {
        var ref = new Firebase("http://ift.tt/1MD8Mu2");
ref.authWithPassword({
  "email": email,
  "password": passwd
}, function(error, authData) {
  if (error) {
    console.log("Login Failed!", error);
    return false;
  } else {
    console.log("Authenticated successfully with payload:", authData);
    return true;
  }
});
    }


    // Handle transitions between routes
    function transitionRoute(path) {
        // grab the config object to get the form element and controller
        var formRoute = routeMap[path];
        var currentUser = rootRef.getAuth();

        // if authentication is required and there is no
        // current user then go to the register page and
        // stop executing
        if (formRoute.authRequired && !currentUser) {
            routeTo('register');
            return;
        }

        // wrap the upcoming form in jQuery
        var upcomingForm = $('#' + formRoute.form);

        // if there is no active form then make the current one active
        if (!activeForm) {
            activeForm = upcomingForm;
        }

        // hide old form and show new form
        activeForm.hide();
        upcomingForm.show().hide().fadeIn(750);

        // remove any listeners on the soon to be switched form
        activeForm.off();

        // set the new form as the active form
        activeForm = upcomingForm;

        // invoke the controller
        controllers[formRoute.controller](activeForm);
    }

    // Set up the transitioning of the route
    function prepRoute() {
        transitionRoute(this.path);
    }


    /// Routes
    ///  #/         - Login
    //   #/logout   - Logut
    //   #/register - Register
    //   #/profile  - Profile

    Path.map("#/roster3101.php").to(prepRoute);
    Path.map("#/logout").to(prepRoute);
    Path.map("#/register").to(prepRoute);
    Path.map("#/profile").to(prepRoute);

    Path.root("#/");

    /// Initialize
    ////////////////////////////////////////

    $(function () {

        // Start the router
        Path.listen();

        // whenever authentication happens send a popup
        rootRef.onAuth(function globalOnAuth(authData) {

            if (authData) {
                showAlert({
                    title: 'Logged in!',
                    detail: 'Using ' + authData.provider,
                    className: 'alert-success'
                });
            } else {
                showAlert({
                    title: 'You are not logged in',
                    detail: '',
                    className: 'alert-info'
                });
            }

        });

    });

// }(window.jQuery, window.Firebase, window.Path))
</script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    </script>
</body>
</html>

Aucun commentaire:

Enregistrer un commentaire