Finished working on login functionality and fixed some bugs
[speedfreak] / Server / application / controllers / api.php
1 <?php defined('SYSPATH') OR die('No direct access allowed.');
2 /*
3  * API controller for communicating with mobile clients
4  * 
5  * @author      Artem Daniliants <artem@daniliants.com>
6  * @copyright   (c) 2010 Speed Freak team
7  * @license     http://opensource.org/licenses/gpl-license.php GNU Public License
8  */
9
10 class Api_Controller extends Controller{
11     
12         /*
13          * Default action when no parameters are given to controller
14          */
15         public function index(){
16         url::redirect(Kohana::config('api.default_redirect'),301);
17     }
18     
19     /*
20      * New user registration
21      */
22     public function register(){
23         $xml = $this->get_xml();
24         try {
25            $user = new User_Model($xml->login, $xml->password, $xml->email);
26            echo "OK";
27         }
28         catch (Exception $e) {
29             echo $e->getMessage() . "\n";
30             die;
31         } 
32     }
33     
34     /*
35      * Returns XML file supplied by client
36      */
37     private function get_xml(){
38         if (isset($_POST['xml'])){
39             $xml = simplexml_load_string($_POST['xml']);
40         }
41         elseif (isset($_FILES['xml'])){
42             $xml = simplexml_load_file($_FILES['xml']['tmp_name']);
43         }
44         else{
45             header("HTTP/1.1 400 Bad Request");
46             echo "Please supply required parameters";
47             die;
48         }
49         return $xml;
50     }
51     
52     /*
53      * Check that supplied credentials are valid using basic authentication
54      *
55      */
56     public function login(){
57         if (isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])){
58                 $user = new User_Model();
59                 if ($user->login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']))
60                   print "OK";
61                 else {
62                   header('HTTP/1.0 401 Unauthorized');
63                   print "Invalid credentials";
64                   die;
65                 } 
66         }
67         else {
68                 header('HTTP/1.0 401 Unauthorized');
69             print "No credentials supplied";
70             die;
71         }
72            
73     }
74 }