Commits

ont committed d16fee8

(+) login: relogin and adding owns

Comments (0)

Files changed (4)

 import bottle
-import models
 from md5 import md5
+from models import Own, Card, User
 from tools import pw2js, auth, jsonify
 from beaker.middleware import SessionMiddleware
 
 @auth
 def login():
     s = bottle.request.environ.get('beaker.session')
-    return {'login' : s['login']}
+    return {'id' : s['id'], 'login' : s['login']}  ## hand-made User instance
 
 @bottle.post('/users/login')
 def login():
     passw = md5(passw + md5(passw).hexdigest()).hexdigest()
 
     try:
-        user = models.User.get( (models.User.login == login) & (models.User.passw == passw) )
+        user = User.get( (User.login == login) & (User.passw == passw) )
         s = bottle.request.environ.get('beaker.session')
         s['logged'] = True
         s['login'] = user.login
+        s['id'] = user.id
         s.save()
 
     except:
     return 'OK'
 
 
-@bottle.route('/owns')
+@bottle.route('/users/<id:int>/owns')
 @auth
 @jsonify
-def owns_list():
-    owns = list(models.Own.select().join(models.Card))
+def owns_list(id):
+    owns = Own.select().join(Card).switch(Own).join(User).where(User.id == id)
     return pw2js(owns, [
         #'when',
         ('card',['name','pict','cost','cnum','power','tough',('cset',['name'])]),
     ])
 
-@bottle.route('/owns', method='POST')
+@bottle.route('/users/<id:int>/owns', method='POST')
+@auth
 @jsonify
-def owns_add():
+def owns_add(id):
+    s = bottle.request.environ.get('beaker.session')
+
+    ## TODO: may be pack it into decorator @auth ?
+    if id != s['id']:
+        abort(401, "You can't edit non-own cards")
+
     json = bottle.request.json
     name = json.get('name')
     cset = json.get('cset')
     cnt  = json.get('cnt')
 
-    card = models.Card.search(name, cset).get()
+    card = Card.search(name, cset).get()
     card.fetch()
     card.save()
 
+    user = User.select().where(User.id == id)
+
     res = []
     for i in xrange(cnt):
-        own = models.Own(card = card)
+        own = Own(card = card, user=user)
         own.save()
         res.append(own)
 
     name = bottle.request.query['name']
 
     ## take all cards with names GLOB (case sensitive LIKE) to 'name'
-    cs = models.Card.search(name)
+    cs = Card.search(name)
 
     return pw2js(cs, [
         'name','pict',
                 </div>
             </div>
         </div>
-        <a class="close-reveal-modal">×</a>
+        <a ng-click="dlg_login_hide()" class="close-reveal-modal">×</a>
     </div>
 
     <div class="contain-to-grid sticky fixed">
             </ul>
             <ul class="right">
                 <li>
-                    <a ng-click="dlg_login=true" class="button">Login</a>
+                    <a ng-click="dlg_login_show()" class="button">Login</a>
                 </li>
             </ul>
         </nav>

js/controllers.js

 function MainCtrl($scope, $http, Restangular, mtg) {
     var prs = null;
-    var owns = Restangular.all('owns');
     var cards = Restangular.all('cards');
 
     $scope.dmode = 'thumb';
     $scope.dlg_login = false;
 
+    /// container for user (login) information
+    $scope.u = {
+        'user' : null,  // restangular instance
+    };
+
+    /// container for filtering and sorting params
     $scope.m = {
         'sort' : [null, null, null],
         'filter' : [],
         'join' : true,
     }
 
-    /// download original non-sorted "owns"
-    owns.getList().then(function(data){
-        $scope.owns = data;
-        $scope.process();  // do default sorting and grouping
-    });
-
     /// create command parser
     $http.get('/js/peg.tpl').then(function(res){
         prs = PEG.buildParser(res.data);
         console.log(cmd, prs.parse(cmd));
         res = prs.parse(cmd);
         if( res[0] == 'add' ) {
-            owns.post({'cnt': res[1], 'name': res[2][0], 'cset': res[2][1]})
-                .then(function(owns){
-                    _.each(owns, function(x){
-                        $scope.owns.push(x);
-                    });
 
-                    $scope.xxx = 'add 1 "';
+            $scope.u.user.all('owns').post({
+                'cnt' : res[1],
+                'name': res[2][0],
+                'cset': res[2][1]}
+            ).then(function(owns){
+                _.each(owns, function(x){
+                    $scope.owns.push(x);
                 });
+
+                $scope.xxx = 'add 1 "';
+
+                /// refresh groupped and filtered selection
+                $scope.owns_process();
+            });
+
         } else if( res[0] == 'del' ) {
         }
     }
     /*
      * Regroup and refilter owns by new filters.
      */
-    $scope.process = function(){
+    $scope.owns_process = function(){
         var res = _($scope.owns);   // container for sorted and grouped "owns"
 
         /// join owns for cards with equal names
     }
 
     /*
+     * Fillup $scope with basic non-sorted and non-filtered
+     * list of owns for particular user.
+     */
+    $scope.owns_reload = function( user ){
+        /// download original non-sorted "owns"
+        user.getList('owns').then(function(data){
+            $scope.owns = data;
+            $scope.owns_process();  // do default sorting and grouping
+        });
+    }
+
+    /*
      * Login form hooks.
      */
-    $scope.$on('event:auth-loginRequired',  function(){ $scope.dlg_login = true;  });
-    $scope.$on('event:auth-loginConfirmed', function(){ $scope.dlg_login = false; });
+    $scope.$on('event:auth-loginRequired',  function(){ $scope.dlg_login = true; });
     $scope.$on('event:auth-loginCancelled', function(){ $scope.dlg_login = false; });
+    $scope.$on('event:auth-loginConfirmed', function(){
+        $scope.dlg_login = false;
+    });
+
+    /*
+     * Login form global functions
+     */
+    $scope.dlg_login_show = function(){ $scope.dlg_login = true;  }
+    $scope.dlg_login_hide = function(){ $scope.dlg_login = false; }
 }
 
 function RightNumpadCtrl( $scope )
             return (x == name) ? null : x;
         });
         $scope.m.sort[idx] = name;
-        $scope.process();
+        $scope.owns_process();
     }
 }
 
 {
     var users = Restangular.all('users');  // build API root for user (info + login API)
 
-    $scope.user = users.one('info').get();
+    $scope.bootstrap = function(){
+        /// trying to get ourself and storing in global box "$scope.u"
+        users.get('info').then(function( user ){
+            $scope.u.user = user;
+            $scope.owns_reload(user);  /// now load our "owns"
+        });
+    }
 
+    /// try to login on server with data from form
     $scope.login = function(){
         $scope.user = users.customPOST($scope.post, 'login').then(function(){
-            authService.loginConfirmed();
+            $scope.bootstrap();            // if user manually relogin we must fetch new info
+            authService.loginConfirmed();  // WOW! server accepted our login/pass pair
         });
+    }
 
-        //$http.post('/login', $scope.post).success(function(user){
-        //    authService.loginConfirmed();
-        //});
-    }
+    $scope.bootstrap();  // try to feth info for current logged in user
 }
 
   = act:"del"i " "* cnt:cnt? " "* name:card_name {return [act, cnt, name]}
  
 card_name
-  = " "* '"' name:[A-Za-z' ]+ '|' set:[A-Za-z 0-9]+ '"' " "* { return [name.join(""), set.join("")] }
+  = " "* '"' name:[^|]+ '|' set:[^"]+ '"' " "* { return [name.join(""), set.join("")] }
  
 cnt
   = digits:[0-9]+ {return parseInt(digits.join(""), 10)}