Add login for Razer Forge TV
[stouyapi.git] / www / api / v1 / sessions.php
1 <?php
2 /**
3  * Store the desired username during the login process
4  *
5  * It will be read by the ouya when calling api/v1/gamers/me.
6  *
7  * @author Christian Weiske <cweiske@cweiske.de>
8  * @see    api/v1/sessions
9  * @see    api/v1/gamers/me
10  */
11 $dbFile  = __DIR__ . '/../../../data/usernames.sqlite3';
12
13 if (!isset($_POST['username'])) {
14     header('HTTP/1.0 400 Bad Request');
15     header('Content-type: application/json');
16     echo '{"error":{"message":"Username missing","code": 2001}}' . "\n";
17     exit(1);
18 }
19 $username = $_POST['username'];
20
21 $ip = $_SERVER['REMOTE_ADDR'];
22 if ($ip == '') {
23     header('HTTP/1.0 400 Bad Request');
24     header('Content-type: application/json');
25     echo '{"error":{"message":"Cannot detect your IP address","code": 2002}}'
26         . "\n";
27     exit(1);
28 }
29
30 try {
31     $db = new SQLite3($dbFile, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE);
32 } catch (Exception $e) {
33     header('HTTP/1.0 500 Internal server error');
34     header('Content-type: application/json');
35     echo '{"error":{"message":"Cannot open username database","code": 2003}}'
36         . "\n";
37     echo $e->getMessage() . "\n";
38     exit(2);
39 }
40
41 $res = $db->querySingle(
42     'SELECT name FROM sqlite_master WHERE type = "table" AND name = "usernames"'
43 );
44 if ($res === null) {
45     //table does not exist yet
46     $db->exec(
47         <<<SQL
48         CREATE TABLE usernames (
49             id INTEGER PRIMARY KEY AUTOINCREMENT,
50             username TEXT NOT NULL,
51             ip TEXT NOT NULL,
52             created_at TEXT DEFAULT CURRENT_TIMESTAMP
53         )
54 SQL
55     );
56 }
57
58 //clean up old usernames
59 $db->exec(
60     'DELETE FROM usernames'
61     . ' WHERE created_at < \'' . gmdate('Y-m-d H:i:s', time() - 86400) . '\''
62 );
63
64 //clean up previous logins
65 $stmt = $db->prepare('DELETE FROM usernames WHERE ip = :ip');
66 $stmt->bindValue(':ip', $ip, SQLITE3_TEXT);
67 $stmt->execute()->finalize();
68
69 //store the username
70 $stmt = $db->prepare('INSERT INTO usernames (ip, username) VALUES(:ip, :username)');
71 $stmt->bindValue(':ip', $ip);
72 $stmt->bindValue(':username', $username);
73 $res = $stmt->execute();
74 if ($res === false) {
75     header('HTTP/1.0 500 Internal server error');
76     header('Content-type: application/json');
77     echo '{"error":{"message":"Cannot store username","code": 2004}}'
78         . "\n";
79     exit(3);
80 }
81 $res->finalize();
82
83 header('HTTP/1.0 200 OK');
84 header('Content-type: application/json');
85 require __DIR__ . '/sessions';
86 ?>