123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- <?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("id" => intval($u["id"]),
- "username" => $username,
- "token" => $token));
- }
- ?>
|