2013-10-03 17:58:07 +03:00
|
|
|
import rethinkdb as rdb
|
|
|
|
from flask import session
|
|
|
|
from flask.ext.login import login_user
|
2013-10-02 04:50:48 +03:00
|
|
|
from rethinkORM import RethinkModel
|
2013-10-03 17:58:07 +03:00
|
|
|
from reimagine import conn, bcrypt
|
2013-09-29 00:09:02 +03:00
|
|
|
|
2013-10-03 17:58:07 +03:00
|
|
|
|
|
|
|
def to_dict(cur, first=False):
|
|
|
|
ret = []
|
|
|
|
for row in cur:
|
|
|
|
ret.append(row)
|
|
|
|
if ret and first:
|
|
|
|
return ret[0]
|
|
|
|
else:
|
|
|
|
return ret
|
2013-10-02 07:32:53 +03:00
|
|
|
|
2013-09-29 00:09:02 +03:00
|
|
|
|
2013-10-02 04:50:48 +03:00
|
|
|
class BaseModel(RethinkModel):
|
2013-09-29 00:09:02 +03:00
|
|
|
|
2013-10-02 04:50:48 +03:00
|
|
|
def __init__(self, **kwargs):
|
|
|
|
if not kwargs.get('conn'):
|
|
|
|
kwargs['conn'] = conn
|
|
|
|
super(BaseModel, self).__init__(**kwargs)
|
2013-09-29 00:09:02 +03:00
|
|
|
|
|
|
|
@classmethod
|
2013-10-02 04:50:48 +03:00
|
|
|
def create(cls, **kwargs):
|
|
|
|
return super(BaseModel, cls).create(**kwargs)
|
2013-09-29 00:09:02 +03:00
|
|
|
|
2013-10-03 17:58:07 +03:00
|
|
|
def get_all(self, arg, index):
|
|
|
|
return rdb.table(self.table).get_all(arg, index=index).run(self._conn)
|
|
|
|
|
|
|
|
def get_one(self, arg, index):
|
|
|
|
return rdb.table(self.table).get_all(arg, index=index).limit(1).run(self._conn)
|
|
|
|
|
2013-09-29 00:09:02 +03:00
|
|
|
|
|
|
|
class Site(BaseModel):
|
2013-10-02 04:50:48 +03:00
|
|
|
table = 'sites'
|
2013-09-29 00:09:02 +03:00
|
|
|
|
2013-10-02 04:50:48 +03:00
|
|
|
|
2013-10-03 17:58:07 +03:00
|
|
|
class CurrentUser():
|
|
|
|
id = None
|
|
|
|
|
|
|
|
def __init__(self, id):
|
|
|
|
self.id = id
|
|
|
|
|
|
|
|
def get_id(self):
|
|
|
|
return self.id
|
|
|
|
|
|
|
|
def is_active(self):
|
|
|
|
return True
|
|
|
|
|
|
|
|
def is_anonymous(self):
|
|
|
|
return False if self.id else True
|
|
|
|
|
|
|
|
def is_authenticated(self):
|
|
|
|
return True if self.id else False
|
|
|
|
|
|
|
|
|
2013-10-02 04:50:48 +03:00
|
|
|
class User(BaseModel):
|
|
|
|
table = 'users'
|
|
|
|
|
2013-10-03 17:58:07 +03:00
|
|
|
def get_by_email(self, email):
|
|
|
|
return to_dict(self.get_one(email, 'email'), True)
|
|
|
|
|
|
|
|
def get_by_username(self, username):
|
|
|
|
return to_dict(self.get_one(username, 'username'), True)
|
2013-10-02 04:50:48 +03:00
|
|
|
|
|
|
|
def login(self, login, password):
|
2013-10-03 17:58:07 +03:00
|
|
|
pass
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get(cls, id):
|
|
|
|
print id
|
|
|
|
return cls(id=id)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def auth(cls, username, password):
|
|
|
|
u = User()
|
|
|
|
data = u.get_by_email(username)
|
|
|
|
if not data:
|
|
|
|
return False
|
|
|
|
|
|
|
|
if bcrypt.check_password_hash(data['password'], password):
|
|
|
|
login_user(CurrentUser(data['id']))
|
|
|
|
session['user'] = data
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|