<?php

function auth_init() {
  // define user right and id if new session
  if (!$_SESSION["user_id"] or !$_SESSION["user_right"]) {
    $_SESSION["user_id"] = 0;
    $_SESSION["user_right"] = 0;
  }

  // No logged user is allowed without https!
  if ($_SERVER['HTTPS'] != "on" && $_SESSION["user_id"] > 0)
    auth_disconnect();

  // Process auth if asked
  if ($_POST['connect']) {
    if (!auth_connect(stripslashes($_POST['user_login']),
		     stripslashes($_POST['user_pass'])))
      redirect('/?html=Connection&fail='.stripslashes($_POST['user_login']));
  }

  //Process disconnect if asked
  if ($_POST['disconnect'])
    auth_disconnect();
}

function auth_connect($login, $pass) {
  $md5_pass = md5($pass);
  $result = getOneUserByLogin($login);
  if (mysql_num_rows($result) > 0) {
    $user = mysql_fetch_array($result);
    if ($user["user_login"] == $login && $user["user_pass"] == $md5_pass) {
      $_SESSION["user_right"] = $user["user_right"];
      $_SESSION["user_id"] = $user["user_id"];
      return true;
    }
  }
  return false;
}

function auth_disconnect() {
  $_SESSION["user_id"] = 0;
  $_SESSION["user_right"] = 0;
}

?>