Loading login data into another domain

Asked

Viewed 640 times

2

in the system I am making there are 3 panels, being a table of users for each panel and the public site. When the user logs in to any of the three panels, and re-accesses the public site, more information would appear. Summarizing is a "login to see". Each panel is in a domain and the public in the main. I am unable to return the information that this user is logged into the public site, and I honestly do not know if there is any way to do this.

HEAD.php

<?php
    $host = 'localhost';
    $usuario = 'psaude';
    $senha = '';
    $banco = 'psaude';
    $conn = @mysql_connect($host, $usuario, $senha) or die(mysql_error());
    $db = mysql_select_db($banco, $conn) or die(mysql_error());
    $charset = mysql_set_charset('utf8');
    function __autoload($class)
    {
        require_once(dirname(__FILE__) . "/../class/{$class}.class.php");
    }
    $objLogin = new Login();
    if (!$objLogin->verificar('/login'))
        exit;

    $query = mysql_query("SELECT * FROM users WHERE chns = {$objLogin->getID()}");
    $usuario = mysql_fetch_object($query);
    $user_mostra = $usuario->id;
    $user_nome = $usuario->nome;
    $user_cnhs = $usuario->chns;
?>

CLASS.php(Login.class.php)

<?php

class Login {

    private $tabela, $campoID, $campoLogin, $campoSenha, $campoStatus, $campoAtivo;

    function  __construct($tabela = 'users', $campoID = 'chns', $campoStatus = 'status', $campoAtivo = 'dob', $campoLogin = 'email', $campoSenha = 'senha') {

            // Iniciando sessão
            @session_start();

            // Definindo atributos
            $this->tabela = $tabela;
            $this->campoID = $campoID;
            $this->campoLogin = $campoLogin;
            $this->campoSenha = $campoSenha;
            $this->campoStatus = $campoStatus;
            $this->campoAtivo = $campoAtivo;
    }

    // ------------------------------------------------------------------------

    /**
     * Retornando login do usuário que está na sessão
     *
     * @access  public
     * @return  string
     */

    function getLogin() {
        return $_SESSION[$this->campoLogin];
    }

    // ------------------------------------------------------------------------

    /**
     * Retornando ID do usuário que está na sessão
     *
     * @access  public
     * @return  integer
     */

    function getID() {
        return $_SESSION[$this->campoID];
    }

    // ------------------------------------------------------------------------

    /**
     * Trata as informações recebidas, procura o usuário no banco de dados e, se encontrado,
         * registra as informações na sessão.
     *
     * @access  public
         * @param   string
     * @param   string
         * @param   string
     * @return  boolean
     */

    function logar($login, $senha, $status, $dob, $redireciona = null) {
        // Tratando as informações
        $login = mysql_real_escape_string($login);
        $senha = mysql_real_escape_string($senha);
        $status = mysql_real_escape_string($status);

        // Verifica se o usuário existe
        $query = mysql_query("SELECT {$this->campoID}, {$this->campoLogin}, {$this->campoSenha}, {$this->campoAtivo}
                             FROM {$this->tabela}
                             WHERE {$this->campoLogin} = '{$login}' AND {$this->campoSenha} = '{$senha}' AND {$this->campoAtivo} = 'ativo'");
        // $query_1 = mysql_query("UPDATE status = '$status' WHERE uid = '{$this->campoID}'");

        // Se encontrado um usuário
        if(mysql_num_rows($query) > 0)
        {
            // Instanciando usuário
            $usuario = mysql_fetch_object($query);

            // Registrando sessão
            $_SESSION[$this->campoID] = $usuario->{$this->campoID};
            $_SESSION[$this->campoLogin] = $usuario->{$this->campoLogin};
            $_SESSION[$this->campoSenha] = $usuario->{$this->campoSenha};
            $_SESSION[$this->campoAtivo] = $usuario->{$this->campoAtivo};

            // Se informado redirecionamento
            if ($redireciona !== null)
                header("Location: {$redireciona}");
            else
                return true;
        }
        else
            return false;
    }

    // ------------------------------------------------------------------------

    /**
     * Verifica se o usuário está logado
     *
     * @access  public
         * @param   string
     * @return  boolean
     */

    function verificar($redireciona = null) {
        // Se as sessões estiverem setadas
        if(isset($_SESSION[$this->campoID]) and isset($_SESSION[$this->campoLogin]) and isset($_SESSION[$this->campoSenha]))
            return true;
        else
        {
            if (headers_sent()) {
                die('<meta http-equiv="Refresh" content="0; url=../login">');
            }else{
                exit(header("Location: /user.php"));
            }
            // Se informado redirecionamento
            if ($redireciona !== null)
                header("Location: {$redireciona}");

            return false;    
        }

    }

    // ------------------------------------------------------------------------

    /**
     * Finaliza a sessão do usuário
     *
     * @access  public
         * @param   string
     * @return  void
     */

    function logout($redireciona = null) {
        // Limpa a Sessão
        $_SESSION = array();
        // Destroi a Sessão
        session_destroy();
        // Modifica o ID da Sessão
        session_regenerate_id();
        // Se informado redirecionamento
        if ($redireciona !== null)
            header("Location: {$redireciona}");
    }

}
?>

When entering the information in the form, send to the file logar via post

log in.php

<?php
require_once('../config/conn.php');
$objLogin = new Login();
$login = $_POST['email'];
$senha = $_POST['senha'];
$status = "";
$dob = "";
date_default_timezone_set('America/Sao_Paulo');
$data_login = date("d/m/Y");
$hora_login = date("h:i");
if ($objLogin->logar($login, $senha, $status, $dob))
    // Retornando falso
        echo false; 
    else{
        // Retornando mensagem de erro
        echo 'Login ou senha inválidos. <br>Caso o problema persista, tente redefinir sua senha.';
    }
    $executa = "UPDATE users SET status = 'online', data_login = '$data_login', hora_login = '$hora_login' WHERE email = '$login'";
    $executaQr = mysql_query($executa) or die;
    if ($executaQr){    echo false; }
?>

CONFIG.php

<?php
$host = 'localhost';
$usuario = 'root';
$senha = '';
$banco = 'psaude';
$conn = @mysql_connect($host, $usuario, $senha) or die(mysql_error());
$db = mysql_select_db($banco, $conn) or die(mysql_error());
$charset = mysql_set_charset('utf8');
function __autoload($class)
{
    require_once(dirname(__FILE__) . "/../class/{$class}.class.php");
}
?>
  • 1

    First I recommend you read: Why should we not use mysql type functions_*?.

  • mysql_ is Dead.

  • @vmsouza, I know the mysql_ is deprecated and is discontinued, so much so that in the Adm panel I use PDO to make the inclusions, exclusions and searches. But this login I use for years and never got problems with the mysql_. But I will be making future updates to customers' websites as soon as I update the code with PDO. But, returning the question, have to make this user return logged in the main domain even logged in a sub?

1 answer

1


You can use a cookie to verify that the user is logged in to the subdomino or main domain. To do this, simply create a token, save it in the database, and set it as a cookie for the browser. So every time you check the login on the main site, just check if the cookie received in the request exists in the database. The cookie must have this format:

setcookie("token", $valor, tempo de duracao em milisegundos, "/", "www.dominoprincipal.com");

For a reference of the setcookie function see the php.net.

Applying this to your case would look like this:

Login.class.php

function verificar($redireciona = null) {

        /*****************************************************************
         Check no banco se o token existe
        ******************************************************************/
        //a função tokenExiste faz uma consulta no banco e verifica 
        //se existe o campo token, e retorna um booleano
        $tokenExiste = tokenExiste($_COOKIE["token"]);
        if($tokenExiste){
             //se sim, set os dados da sessão
             return true;
        }

        // Se as sessões estiverem setadas
        if(isset($_SESSION[$this->campoID]) and isset($_SESSION[$this->campoLogin]) and isset($_SESSION[$this->campoSenha]))
            return true;
        else
        {
            if (headers_sent()) {
                die('<meta http-equiv="Refresh" content="0; url=../login">');
            }else{
                exit(header("Location: /user.php"));
            }
            // Se informado redirecionamento
            if ($redireciona !== null)
                header("Location: {$redireciona}");

            return false;    
        }
}

function logar($login, $senha, $status, $dob, $redireciona = null) {
        // Tratando as informações
        $login = mysql_real_escape_string($login);
        $senha = mysql_real_escape_string($senha);
        $status = mysql_real_escape_string($status);

        // Verifica se o usuário existe
        $query = mysql_query("SELECT {$this->campoID}, {$this->campoLogin}, {$this->campoSenha}, {$this->campoAtivo}
                             FROM {$this->tabela}
                             WHERE {$this->campoLogin} = '{$login}' AND {$this->campoSenha} = '{$senha}' AND {$this->campoAtivo} = 'ativo'");
        // $query_1 = mysql_query("UPDATE status = '$status' WHERE uid = '{$this->campoID}'");

        // Se encontrado um usuário
        if(mysql_num_rows($query) > 0)
        {
            // Instanciando usuário
            $usuario = mysql_fetch_object($query);

            // Registrando sessão
            $_SESSION[$this->campoID] = $usuario->{$this->campoID};
            $_SESSION[$this->campoLogin] = $usuario->{$this->campoLogin};
            $_SESSION[$this->campoSenha] = $usuario->{$this->campoSenha};
            $_SESSION[$this->campoAtivo] = $usuario->{$this->campoAtivo};

            /***********************************************************
             Configurando o cookie
            ************************************************************/
            //antes de imprimir qualquer conteudo html, set o cookie
            $valor = md5(uniqid(rand(), true));//gerar um valor unico

            setcookie("token", $valor, time()+3600, "/", "www.dominioprincipal.com");

            //salve a variavel $valor no banco de dados

            // Se informado redirecionamento
            if ($redireciona !== null)
                header("Location: {$redireciona}");
            else
                return true;
        }
        else
            return false;
}

Basically you need to create a new field in your user table. Then, whenever a user logs into a subdominal you create a cookie, generate a unique value for it (uniqid), saved in the database, and uses the setcookie function to return it to the user’s browser. This way, in later login checks, within the main domain, or within the subdominios, you can use the value of the cookie sent by the browser to verify if the user has previously logged in, and load the necessary session data. As is sensitive information you could use ssl on your site.

As extra information I cut out the parameters of the setcookie function, taken from php.net documentation:

name

O nome do cookie. value

O valor do cookie. Esse valor é guardado no computador do cliente; não guarde informação sensível. Supondo que o name seja

'docookie', the value can be read through $_COOKIE['docname'] expire

O tempo para o cookie expirar. Esse valor é uma timestamp Unix, portanto é o número de segundos desde a época (epoch). Em outras

words, you will probably use this with the function time() plus the number of seconds you want it to expire. Or you can use mktime(). time()+60*60*24*30 will set the cookie to expire in 30 days. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).

    Nota:

    Você pode ver que o parâmetro expire recebe uma timestamp Unix, ao contrário do formato de data Wdy, DD-Mon-YYYY HH:MM:SS GMT,

this is because PHP makes this conversion internally.

path

O caminho no servidor aonde o cookie estará disponível. Se configurado para '/', o cookie estará dosponível para todo o domain.

If set to the directory '/foo/', the cookie will be available only within the directory /foo/ and all subdirectories as /foo/bar from Domain. The default value is the current directory where the cookie is being configured. Domain

O (sub)domínio para qual o cookie estará disponível. Definindo para um subdomínio (como 'www.example.com') deixará o cookie

available for that subdomain and all other sub-domains below it (example w2.www.example.com). To leave the cookie available for the entire domain (including all subdomains), simply set the value for the domain name ('example.com', in that case).

Browsers antigos ainda implementam a » RFC 2109 e podem requerer um . no início para funcionar com todos os subdomínios. secure

Indica que o cookie só podera ser transimitido sob uma conexão segura HTTPS do cliente. Quando configurado para TRUE, o cookie será

sent only if a secure connection exists. On the server side, is on account of the programmer sending this type of cookie only under a secure connection (ex respecting $_SERVER["HTTPS"]). httponly

Quando for TRUE o cookie será acessível somente sob o protocolo HTTP. Isso significa que o cookie não será acessível por linguagens de

script, such as Javascript. It is said that this setting can help reduce or identify identity theft through type attacks XSS (however it is not supported by all browsers), but this information is constantly discussed. It was added in PHP 5.2.0. TRUE OR FALSE

  • Man, thank you so much, it’s gotten so much more dynamic now. I was using the url with a login generated Token and a Code that I put in all my projects as a keygen when entering something into the database, which is generated by time(), defined as chns in the table. The url basically looked like this "? a=chns&t=keygen", I used both to locate and confirm user data, now I am using the cookie for this and the url is clean, without "disclosing" this information to the user.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.