您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

user.php 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. require_once "sql.php";
  3. require_once "utils.php";
  4. function hash_password($password)
  5. {
  6. return sha1($password);
  7. }
  8. function user_create()
  9. {
  10. $username = get_post("username");
  11. $password = get_post("password");
  12. if (strlen($username) < 3)
  13. error(422, "Username too short");
  14. if (database_exec("SELECT id FROM users WHERE `username` = :username",
  15. array(":username" => $username))->fetch() !== false)
  16. error(409, "Username already taken");
  17. database_exec("INSERT INTO users (`username`, `password`) ".
  18. "VALUES(:username, :password)", array(":username" => $username,
  19. ":password" => hash_password($password)));
  20. user_login($username);
  21. }
  22. function user_login($username = false)
  23. {
  24. $args = null;
  25. $query = "SELECT `id` FROM users WHERE `username` = :username";
  26. if ($username === false)
  27. {
  28. $username = get_post("username");
  29. $args = array(":username" => $username,
  30. ":password" => hash_password(get_post("password")));
  31. $query = $query . " AND `password` = :password";
  32. }
  33. else
  34. $args = array(":username" => $username);
  35. $u = database_exec($query, $args)->fetch();
  36. if ($u === false)
  37. error(401, "Bad credentials");
  38. $token = hash_password(uniqid(mt_rand(), true));
  39. database_exec("INSERT INTO tokens (`token`, `user`) VALUES (:token, :user)",
  40. array(":token" => $token, ":user" => $u['id']));
  41. echo json_encode(array("id" => intval($u["id"]),
  42. "username" => $username,
  43. "token" => $token));
  44. }
  45. ?>