1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- <?php
- require_once "sql.php";
- require_once "utils.php";
-
- function hash_password($password)
- {
- return sha1($password);
- }
-
- function user_create()
- {
- $username = get_post("username");
- $password = get_post("password");
- if (strlen($username) < 3)
- error(422, "Username too short");
- if (database_exec("SELECT id FROM users WHERE `username` = :username",
- array(":username" => $username))->fetch() !== false)
- error(409, "Username already exists");
- database_exec("INSERT INTO users (`username`, `password`) ".
- "VALUES(:username, :password)", array(":username" => $username,
- ":password" => hash_password($password)));
- user_login($username);
- }
-
- function user_login($username = false)
- {
- $args = null;
- $query = "SELECT `id` FROM users WHERE `username` = :username";
- if ($username === false)
- {
- $username = get_post("username");
- $args = array(":username" => $username,
- ":password" => hash_password(get_post("password")));
- $query = $query . " AND `password` = :password";
- }
- else
- $args = array(":username" => $username);
- $u = database_exec($query, $args)->fetch();
- if ($u === false)
- error(401, "Wrong username or password");
- $token = hash_password(uniqid(mt_rand(), true));
- database_exec("INSERT INTO tokens (`token`, `user`) VALUES (:token, :user)",
- array(":token" => $token, ":user" => $u['id']));
- echo json_encode(array("username" => $username, "id" => intval($u["id"]),
- "token" => $token));
- }
- ?>
|