Selaa lähdekoodia

user create and login

master
Robin Thoni 10 vuotta sitten
vanhempi
commit
ede1ee5683
1 muutettua tiedostoa jossa 18 lisäystä ja 4 poistoa
  1. 18
    4
      user.php

+ 18
- 4
user.php Näytä tiedosto

@@ -4,7 +4,7 @@ require_once "utils.php";
4 4
 
5 5
 function hash_password($password)
6 6
 {
7
-  return md5($password);
7
+  return sha1($password);
8 8
 }
9 9
 
10 10
 function user_create()
@@ -18,16 +18,30 @@ function user_create()
18 18
     error(409, "Username already exists");
19 19
   database_exec("INSERT INTO users (`username`, `password`) ".
20 20
     "VALUES(:username, :password)", array(":username" => $username,
21
-    ":password" => hash_password($password)));
21
+      ":password" => hash_password($password)));
22 22
   user_login($username);
23 23
 }
24 24
 
25
-function user_login($username = false )
25
+function user_login($username = false)
26 26
 {
27
+  $args = null;
28
+  $query = "SELECT `id` FROM users WHERE `username` = :username";
27 29
   if ($username === false)
28 30
   {
29 31
     $username = get_post("username");
30
-    $password = get_post("password");
32
+    $args = array(":username" => $username,
33
+      ":password" => hash_password(get_post("password")));
34
+    $query = $query . " AND `password` = :password";
31 35
   }
36
+  else
37
+    $args = array(":username" => $username);
38
+  $u = database_exec($query, $args)->fetch();
39
+  if ($u === false)
40
+    error(401, "Wrong username or password");
41
+  $token = hash_password(uniqid(mt_rand(), true));
42
+  database_exec("INSERT INTO tokens (`token`, `user`) VALUES (:token, :user)",
43
+    array(":token" => $token, ":user" => $u['id']));
44
+  echo json_encode(array("username" => $username, "id" => $u["id"],
45
+    "token" => $token));
32 46
 }
33 47
 ?>

Loading…
Peruuta
Tallenna