Полностью новая версия веб-интерфейса на базе chart.js
[weathermon.git] / web / auth.php
1 <?php
2
3 if (!function_exists('com_create_guid')) {
4   function com_create_guid() {
5     return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
6         mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
7         mt_rand( 0, 0xffff ),
8         mt_rand( 0, 0x0fff ) | 0x4000,
9         mt_rand( 0, 0x3fff ) | 0x8000,
10         mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
11     );
12   }
13 }
14
15 include('config_local.php');
16
17 if (! ($db = new PDO("mysql:host=$mysql_host;port=$mysql_port;dbname=$mysql_schema",$mysql_user,$mysql_pwd,array( PDO::ATTR_PERSISTENT => false)))) {
18   die($err);
19 }  
20
21 $db -> exec('SET CHARACTER SET utf8');
22
23 $auth_token = $_COOKIE["auth-token"];
24
25 $timestamp = 0;
26
27 if ($auth_token) {
28
29   $sql = "
30     SELECT UNIX_TIMESTAMP(MAX(expires)) timestamp FROM tokens WHERE str=:s and expires>now()
31   ";
32   
33   $q = $db -> prepare( $sql );
34   $q -> bindParam(':s',$auth_token,PDO::PARAM_INT);
35   $q -> execute();
36
37   $res = [];
38
39   $row = $q -> fetch(PDO::FETCH_ASSOC);
40   $timestamp = $row['timestamp'];
41
42
43
44 if ($timestamp) {
45   setcookie("auth-token",$auth_token,$timestamp);
46 } else {
47   $auth_token = com_create_guid();
48   $timestamp = time()+86400*365;
49   setcookie("auth-token",$auth_token,$timestamp);
50   $sql = "
51     INSERT INTO tokens(str,description,expires) VALUES (:token,:descr,FROM_UNIXTIME(:expires)) 
52   ";
53   $q = $db -> prepare( $sql );
54   $q -> bindParam(':token',$auth_token,PDO::PARAM_STR);
55   $descr = $_SERVER["PHP_AUTH_USER"]." from ".$_SERVER["REMOTE_ADDR"]." at ".date('m/d/Y h:i:s a', time());
56   $q -> bindParam(':descr',$descr,PDO::PARAM_STR);
57   $q -> bindParam(':expires',$timestamp,PDO::PARAM_INT);
58   $db -> beginTransaction();
59   $q -> execute();
60   $db -> commit();
61   
62 }
63
64 print $auth_token;
65
66 ?>