Thanks for the help provided to me with my last question on recursive scripts. Got another one here on logins.

Here's what I'm trying to do:

I have a number of scripts I want protected. As such, I've written a series of functions designed to log in a user, check whether a user is logged in, etc.-- a series of session-related functions that I want to apply to a number of different scripts.

The functions work like this:

Right now I have an included file containing my session-related functions. One of the first thing any script I want protected will do, is to run a function checking to see if the user is logged in. If not, another function is run which creates a login form. The login form then POSTs the data to "login.php", a script that verifies the entered data against an authentication database, and creates session variables if everything checks out.

Here's my problem:

I need some way to tell the original script to hold its horses until the login process is done. As it is, either it runs the login form and then proceeds to run the rest of the script (which I don't want to run unless the user is logged in), or it runs the login process and then stops because the login functions have no way of knowing which script called them originally (not that I know of, anyway). I tried using a while loop but all that did was print the login form until I manually stopped it.

If I had some way to run the original script, do the login crap if the user isn't logged in, and then call the original script again, that would be fine. But that would mean my functions would have to know what script called them, and I don't know if that's even possible.

Anyone have any ideas?

-Nij

    what i did was.. make a file like process.php which processed the information.. if the user existed i started the session with there username..

    from there i made a small sessions file which gets included to all the pages that im protecting.. Now of course its not that stable, if i were a hacker id be in straight away, but i dont think anyone wants to hack it...

    Anyway.... you should post some script.. it seems to me your registering the session and checking the session in the same file... thats a big no no.

      Originally posted by planetsim
      Anyway.... you should post some script.. it seems to me your registering the session and checking the session in the same file... thats a big no no.

      The session variables get registered in "login.php". As requested lemme get to posting some script...

      We would start with one script. It includes a header script and the login crap script, then it tries to check and see if the user is logged in.

      <?
      
      require_once("header.php");
      require_once("login_funs.php");
      
      if (logged_in() == false) {
      login_form();
      function_i_need();
      /* function_i_need() represents 
      whatever function it is I need
       that will allow me
       to cut this script short until the login is done
       and then come back to it afterward...
       will I do this in a function call? 
      Will I do it some other way?; I dunno
       but you get the idea... */
      } 
      
      /* run the rest of the script if everything is cool */
      
      ?>

      Here's "login_funs.php"...

      <?
      require_once("header.php");
      
      function logged_in() {
      if (isset($_SESSION[user]) and isset($_SESSION[rank]))
      	return true;
      else
      	return false;
      }
      
      function login_form() {
      
      print_header("Login");
      
      ?>
      
      <form method="POST" action="login.php">
      
      <h1>Login</h1>
      
      <p>You are not logged in.
      <br>Please log in.</p>
      
      <p>Username:
      <br><input type="text" name="username" size=15>
      
      <p>Password:
      <br><input type="password" name="password" size=15>
      
      <p><input type="submit" value="Login">
         <input type="reset" value="Clear Form">
      
      </form>
      
      <?
      
      }
      
      ?>
      

      ...and "login.php", which processes all the crap from the login form and then (if I can find some way to do this!) re-runs the original script.

      <?
      
      require_once("header.php");
      require_once("login_funs.php");
      
      session_start();
      
      if (!isset($username) and !isset($password)) {
      	login_form();
      	exit; }
      
      $sql = "select username, rank from
       some table somewhere where 
      username = '$username' and password
       = password('$password')";
      
      @ $db = mysql_connect("insert 
      unbelievably important stuff here");
      
      if (!$db)
      {
         print_header("Couldn't connect to the database");
         echo "Could not connect to the database.\n<br>Try again later.";
         exit;
      }
      
      mysql_select_db("insert database here");
      
      $result = mysql_query($sql, $db);
      
      if (mysql_num_rows($result) > 0) {
      	$result = mysql_fetch_array($result);
      	$_SESSION[user] = $result[username];
      	$_SESSION[rank] = $result[rank];
      
      exit;
      }
      
      print_header("Incorrect Username or Password");
      echo "<h1>Uh-Oh...</h1>\n".
           "<p>You have specified an inaccurate username or password.".
           "<br>It is possible that you misspelled something.".
           "<br>Go back and try again.";
      unset($username);
      unset($password);
      ?>
      

      Sorry for posting all this code, but I hope it's helpful. Even if it isn't, I appreciate your consideration.

      -Nij

        hmm... this seems wierd.. although its entirely different to what i thought....

        Now still why do you need the to requires.. make it simple if thats what your protecting will turn false for some reason.. not sure why but sometimes it thinks its been registered twice...

        What i did was.. have your login form then process.php which processed the form, to make sure it was perfect.. if true then we get sent to the first file which is protected eg. index.php if it returns false eg 0 then we get redirected to login form with the error...

        Say we logged in.. In my code i put an include.. exactly the same as require pretty much, but instead of requiring two files to check all the stuff..

        I just used 1.. kinda the same way you did.. to see if the session exists.. etc etc... what it looks like in my view is your way to protective of your files, if its a really big issue security.. then having 2files is not a good option.. id reckon youd be sent back to login everytime you logged in... maybe try my approach or a different approach..

        Try making it really simple... No offence but if this is your first login script.. Its way over the top.. Some of it i see not nessacary...

        Ok.. i hope you can understand something there.. i kinda blabbed a lot sorry

          Originally posted by planetsim
          Try making it really simple... No offence but if this is your first login script.. Its way over the top.. Some of it i see not nessacary...

          How is it over the top? It checks if the session is active; if not, it goes to log in. The login script authenticates the user; if the user is authenticated, it registers the session variables. I'm trying to design this in such a way that I can secure a number of different scripts with this, so that just by calling a function or two I can force users to login before being able to access the script.

          In the end, though, I don't need any help with my login script, I just need to know if there's some way to re-run the original script once the login process is finished.

          Oh, well... I suppose I can accomplish this by passing a variable around and using a meta redirect tag.

          -Nij

            Use header('Location:') instead. It's much more transparent to the browser. I use a similar mechanism on one of my sites.

            I call
            authenticate();
            at the top of each page to check session and cookie data, basically to ensure that a session is loaded if cookie data checks out, but there is no existing session for transparent login. It is equivalent to your login.php, but it returns true if the user is logged in, else false. If the page requires a user to be logged in I call:

            if ( ! authenticate() ) {
            redirectToLogin(redirect=$PHP_SELF);
            }

            where redirect(url) is equivalent to header('Location: http://mydom.com/login.php?redirect=page/to/go/back/to/if/login/works')

            login.php does all the form processing, display and cookie business, then, if login is successful, it redirects back to where it came from.

            If you include a login form on every page pointing to login.php, you just get sent right back after you click "Login". It's a nice idiom, and works really well. I got the idea from looking at how a few big websites work.

            I think you are definitely doing this the right way. Here's my authenticate.inc.php:

            function authenticate_from_password( $user, $psswd )
            {
            	global $DBPREFIX;
            	$query = "SELECT username, password FROM ". $DBPREFIX ."users WHERE
            	username=\"$user\" AND password = PASSWORD( '$psswd' )";
            	$res = mysql_query( $query ) or mysqlError();
            	if ( mysql_num_rows( $res ) == 0 ) {
            		return false;
            	} else {
            		load_user( $user );
            		return true;
            	}
            }
            
            /**
            * Provides authentification from cookies.
            *
            * Authenticates user from security code cookie. If value and user match database entry, and
            * the code is not too old, authentication will suceed. Returns true on success, false on failure.
            * Function is public, but it is better to call authenticate(), which looks at session vars as well.
            *
            * @access public
            * @param string $user Username.
            * @param string $security Cookie value.
            * @return Boolean
            * @see authenticate()
            */
            function authenticate_from_cookie( $user, $security )
            {
            	// authenticate against security values in the DB
            	global $DBPREFIX, $COOKIELIMIT;
            	// first we delete all entries older than cookie limit
            	$user = trim($user);
            	$query = "DELETE FROM ". $DBPREFIX ."security WHERE ( UNIX_TIMESTAMP() - $COOKIELIMIT ) > time";
            	$res = mysql_query( $query ) or mysqlError();	
            	$query = "SELECT id FROM ". $DBPREFIX ."security WHERE username = \"$user\"";
            	$res = mysql_query( $query ) or mysqlError();	
            	if ( mysql_num_rows( $res ) == 0 ) {
            		return false;
            	}
            	$row = mysql_fetch_row( $res );
            	$res = $row[0];
            	if ( $res == $security ) {
            		return true;
            	} else {         // not all cookies are present
            		return false;
            	}
            }
            
            /**
            * Generate new security id.
            *
            * Creates a new security id for cookies, enters it into the database
            * and returns it for setting in a cookie.
            *
            * @access public
            * @param string $user Username
            * @return string 
            */
            function new_security_key( $user )
            {
            	global $DBPREFIX;
            	$id = md5( mt_rand(0, 9999999999) );
            	// delete old entry if there is one
            	$query = 'DELETE FROM '. $DBPREFIX .'security WHERE username = "'. $user .'"';
            	mysql_query( $query ) or mysqlError();	
            	$query = "INSERT INTO ". $DBPREFIX ."security  
            ( username, time, id ) VALUES ( \"$user\", UNIX_TIMESTAMP(), \"$id\" )"; mysql_query( $query ) or mysqlError(); return $id; } /** * Loads user information from the database into session variables. * * Calls mysqlError() if query fails. * * @access public * @param string $user Username. * @return NULL */ function load_user( $user ) { global $DBPREFIX; $query = "SELECT id AS uid, realname, username AS user, type, owner, email, popserver, popport, popuser, poppsswd, signature FROM ". $DBPREFIX ."users WHERE username = '$user'"; $res = mysql_query( $query ) or mysqlError(); $arr = mysql_fetch_array( $res, MYSQL_ASSOC ); foreach ( $arr as $key=>$val ) { $_SESSION[ $key ] = $val; } } /** * If no session and security cookie exists, starts a session automatically. * * Checks for username in session vars and then in cookie vars. If found, it authenticates the user. * Returns 1 on succesful authentication, 0 on failure. * * @access public * @return Boolean */ function authenticate() { global $db, $COOKIELIMIT; if ( !( $_SESSION[ 'user' ] ) ) { // check for security cookie if ( $_COOKIE[ 'security' ] && $_COOKIE[ 'user' ] ) { if ( !$db ) { // open the database connection $db = db_connect(); } $res = authenticate_from_cookie( $_COOKIE[ 'user' ], $_COOKIE[ 'security' ] ); if ( $res ) { // successful authentication load_user( $_COOKIE[ 'user'] ); // refresh security cookie //setcookie( 'security', $_COOKIE[ 'security' ], time() + $COOKIELIMIT, '/' ); return true; } else { // unsuccessful return false; } } } else { // user already logged in return true; } } ?>
              Write a Reply...