简体   繁体   English

在登录系统Php中实现用户帐户

[英]Implementing User Accounts into Login System Php

I want to establish and ENFORCE user permissions on my website. 我想在我的网站上建立并加强用户权限。

I have two user groups: buyers and merchants. 我有两个用户组:买家和商人。

For example, for buyers I have (under /login/ dir): 例如,对于我拥有的买家(在/ login /目录下):

<form method="post" action="check_buyer.php" id="LoggingInBuyer">
    <div style="width:265px;margin:0; padding:0; float:left;">
        <label>Username:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
             <span><a href="#">Forgot Username?</span></a>
        </label>
        <br />
        <input id="UserReg" style="width:250px;" type="text" name="userName" tabindex="1" class="required" />
    </div>
    <div style="width:265px;margin:0; padding:0; float:right;">
        <label>Password:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <span><a href="#">Forgot Password?</span></a></label>
        <br />
        <input id="UserReg" style="width:250px;" type="password"  name="userPass" tabindex="2" class="required" />
    </div>
    <div class="clearB"> </div>
    <input type="submit" style="width:100px; margin:10px 200px;" id="UserRegSubmit" name="submit" value="Login" tabindex="3" />
</form>

A php script check_buyer.php: 一个PHP脚本check_buyer.php:

<?php
session_start(); #recall session from index.php where user logged include()

function isLoggedIn()
{
    if(isset($_SESSION['valid']) && $_SESSION['valid'])
        header( 'Location: buyer/' ); # return true if sessions are made and login creds are valid
    echo "Invalid Username and/or Password";  
    return false;
}

require_once('../inc/db/dbc.php');

$connect = mysql_connect($h, $u, $p) or die ("Can't Connect to Database.");
mysql_select_db($db);

$LoginUserName = $_POST['userName'];
$LoginPassword = mysql_real_escape_string($_POST['userPass']);
//connect to the database here
$LoginUserName = mysql_real_escape_string($LoginUserName);
$query = "SELECT uID, uUPass, dynamSalt, uUserType FROM User WHERE uUName = '$LoginUserName';";

$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such USER exists
{
    echo "Invalid Username and/or Password";
}
$ifUserExists = mysql_fetch_array($result, MYSQL_ASSOC);

function validateUser() {
    $_SESSION['valid'] = 1;
    $_SESSION['uID'] = $uID;
    $_SESSION['uUserType'] = 1; // 1 for buyer - 2 for merchant
}

$dynamSalt = $ifUserExists['dynamSalt'];  #get value of dynamSalt in query above
$SaltyPass = hash('sha512',$dynamSalt.$LoginPassword); #recreate originally created dynamic, unique pass

if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
    echo "Invalid Username and/or Password";
}

else {
validateUser();
}
// If User *has not* logged in yet, keep on /login
if(!isLoggedIn())
{
    header('Location: index.php');
    die();
}
?>

If a valid user is entered.. it goes to /login/buyer dir 如果输入了有效用户,则转到/ login / buyer dir

<?php
session_start();
if($_SESSION['uUserType']!=1)
{ 
    echo 'the userid: ' . $userid . '<br>' . 'the type is ' . $userType . '<br>';
    die("You may not view this page. Access denied.");
}

function isLoggedIn()
{
    return (isset($_SESSION['valid']) && $_SESSION['valid']);
}

//if the user has not logged in
if(!isLoggedIn())
{
    header('Location: index.php');
    die();
}
?>

<?php 
    if($_SESSION['valid'] == 1){
        #echo "<a href='../logout.php'>Logout</a>";
        require_once('buyer_profile.php');
    }
    else{
        echo "<a href='../index.php'>Login</a>";
    }
?>

The problem is once logged in as a buyer , i can just type in: login/merchant and it will take me there, even though the field in the session $_SESSION['uUserType'] is constantly being re-validated to = 1 . 问题一旦以buyer身份登录,我可以输入: login/merchant ,它将带我到那里,即使会话$_SESSION['uUserType']的字段不断被重新验证为= 1

How do I stop users from just typing login/merchant in the url and they can get access to that? 如何阻止用户仅在URL中键入login/merchant ,他们就可以访问该URL?

First, you can't stop users form entering a certain url. 首先,您不能阻止用户表单输入特定的网址。 The only way to restrict certain scripts or code section to certain users is by code [or, well, certain Apache settings]. 将某些脚本或代码段限制为某些用户的唯一方法是通过代码[或者,某些Apache设置]。

This code is wrong, since it (likely) is written to check if a session exists, but it does not check if it is a BUYER session : 这段代码是错误的,因为它(可能)被编写来检查会话是否存在,但不会检查它是否是BUYER会话

function isLoggedIn()
{
    if(isset($_SESSION['valid']) && $_SESSION['valid'])
        header( 'Location: buyer/' ); # return true if sessions are made and login creds are valid
    echo "Invalid Username and/or Password";  
    return false;
}

You need to check $_SESSION['uUserType'] too. 您还需要检查$_SESSION['uUserType']

I'd encapsulate the whole stuff inside of a class: 我将所有内容封装在一个类中:

class CUserRole {

  const USER_NO_ROLE  = 'user.noRole';
  const USER_BUYER    = 'user.buyer';
  const USER_MERCHANT = 'user.merchant';

  const PAGE_LOGIN    = 'index.php';


  static 
  public function getCurrentUserRole() {

    if ( ! isset( $_SESSION )) {
       return self::USER_NO_ROLE;
    }

    switch( $_SESSION['uUserType'] ) {
      case 1:
       return self::USER_BUYER;

      case 2:
       return self::USER_MERCHANT;

      default:
        die( 'Inconsistent/Invalid uUserType' );
    }

  }

  static 
  public function forwardIfNotRole( $aRole, $forwardAddress = self::PAGE_LOGIN ) {

    if ( $aRole != self::getCurrentUserRole() ) {

      header( 'Location: ' . forwardAddress );
      exit;

    }

  }

  static 
  public function evaluateCredentials( ) {

    // checks passed login parameters against the DB
    // and sets up the session with appropriate values

  }

}

Wherever necessary, add this line at the beginning of your script: 如有必要,请在脚本开头添加以下行:

CUserRole::forwardIfNotRole( CUserRole::USER_BUYER, 'some/where/address' );  

Or simply this to forward to index.php: 或者简单地将其转发到index.php:

CUserRole::forwardIfNotRole( CUserRole::USER_BUYER );  

This solution encapsulates the main part of your role management in a separate class. 该解决方案将角色管理的主要部分封装在一个单独的类中。

Finally, I don't see a reason why to set this: 最后,我看不出设置此设置的原因:

$_SESSION['valid'] = 1;

Using static methods is a quite simple solution, using the singleton pattern design would be much better. 使用静态方法是一个非常简单的解决方案,使用单例模式设计会更好。

Do you have a 你有没有

session_start();
if( 2!== $_SESSION['uUserType'])
{ 
    ///login/merchant content goes here (login form, whole page, etc.)
} else {
   header("location: http://www.example.com/whatever/buyer_page.php"); 
    //redirect to whatever page you want
    //or instead of header you could do an 
    //echo "You're already logged in" or whatever message you want
}

On your merchant pages ? 在您的商家页面上? (Every page you don't want buyers to be able to access) (您不希望买家能够访问的每个页面)

It is important to note that there can be NO html outputted before you use header("location.... this includes whitespace outside of tags. so make sure there is no whitespace before your opening 重要的是要注意,在使用header(“ location....。其中包括标记外部的空格之前,不能输出任何html。因此请确保在打开之前没有空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM