Skip to content

Commit

Permalink
rref #5367
Browse files Browse the repository at this point in the history
rref #5366
ref #66
ref #65
  • Loading branch information
evrenesat committed Jun 22, 2016
1 parent 989d1f9 commit bfdfc10
Show file tree
Hide file tree
Showing 5 changed files with 140 additions and 78 deletions.
24 changes: 17 additions & 7 deletions zengine/management_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import six

from pyoko.exceptions import ObjectDoesNotExist
from pyoko.lib.utils import get_object_from_path
from pyoko.manage import *
from zengine.views.crud import SelectBoxCache

Expand Down Expand Up @@ -193,10 +194,19 @@ class PrepareMQ(Command):
HELP = 'Creates necessary exchanges, queues and bindings'

def run(self):
from zengine.wf_daemon import run_workers, Worker
worker_count = int(self.manager.args.workers or 1)
if worker_count > 1:
run_workers(worker_count)
else:
worker = Worker()
worker.run()
self.create_user_channels()
self.create_exchanges()

def create_user_channels(self):
from zengine.messaging.model import Channel
user_model = get_object_from_path(settings.USER_MODEL)
for usr in user_model.objects.filter():
ch, new = Channel.objects.get_or_create(owner=usr, is_private=True)
print("%s exchange: %s" % ('created' if new else 'existing', ch.name))

def create_channel_exchanges(self):
from zengine.messaging.model import Channel
for ch in Channel.objects.filter():
print("(re)creation exchange: %s" % ch.name)
ch.create_exchange()

3 changes: 2 additions & 1 deletion zengine/messaging/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import time
import six
from zengine.lib.cache import Cache, KeepAlive
from .model import Message


class Notify(Cache, ClientQueue):
"""
Expand Down Expand Up @@ -54,6 +54,7 @@ def _delayed_send(self, offline_messages):
self.remove_item(n)

def set_message(self, title, msg, typ, url=None, sender=None):
from .model import Message
message = {'title': title, 'body': msg, 'type': typ, 'url': url, 'id': uuid4().hex}
if sender and isinstance(sender, six.string_types):
sender = Message.sender.objects.get(sender)
Expand Down
95 changes: 90 additions & 5 deletions zengine/messaging/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,107 @@
#
# This file is licensed under the GNU General Public License v3
# (GPLv3). See LICENSE.txt for details.
import json

import pika
from passlib.handlers.pbkdf2 import pbkdf2_sha512

from pyoko.conf import settings
from zengine.client_queue import BLOCKING_MQ_PARAMS



class BaseUser(object):
connection = None
channel = None


def _connect_mq(self):
if not self.connection is None or self.connection.is_closed:
self.connection = pika.BlockingConnection(BLOCKING_MQ_PARAMS)
self.channel = selfconnection.channel()
self.channel = self.connection.channel()
return self.channel

def get_avatar_url(self):
"""
Bu metot kullanıcıya ait avatar url'ini üretir.
Returns:
str: kullanıcı avatar url
"""
return "%s%s" % (settings.S3_PUBLIC_URL, self.avatar)

def __unicode__(self):
return "User %s" % self.username

def set_password(self, raw_password):
"""
Kullanıcı şifresini encrypt ederek set eder.
Args:
raw_password (str)
"""
self.password = pbkdf2_sha512.encrypt(raw_password, rounds=10000,
salt_size=10)

def pre_save(self):
""" encrypt password if not already encrypted """
if self.password and not self.password.startswith('$pbkdf2'):
self.set_password(self.password)

def check_password(self, raw_password):
"""
Verilen encrypt edilmemiş şifreyle kullanıcıya ait encrypt
edilmiş şifreyi karşılaştırır.
Args:
raw_password (str)
Returns:
bool: Değerler aynı olması halinde True, değilse False
döner.
"""
return pbkdf2_sha512.verify(raw_password, self.password)

def get_role(self, role_id):
"""
Kullanıcıya ait Role nesnesini getirir.
Args:
role_id (int)
Returns:
dict: Role nesnesi
"""
return self.role_set.node_dict[role_id]

@property
def full_name(self):
return self.username

def send_message(self, title, message, sender=None, url=None, typ=1):
channel = self._connect_mq()
mq_msg = json.dumps(dict(sender=sender, body=message, msg_title=title, url=url, typ=typ))
channel.basic_publish(exchange=self.key, body=mq_msg)
"""
sends message to users private mq exchange
Args:
title:
message:
sender:
url:
typ:
"""
mq_channel = self._connect_mq()
mq_msg = dict(body=message, msg_title=title, url=url, typ=typ)
if sender:
mq_msg['sender_name'] = sender.full_name
mq_msg['sender_key'] = sender.key

mq_channel.basic_publish(exchange=self.key, body=json.dumps(mq_msg))
self._write_message(sender, message, title, url, typ)

def _write_message(self, sender, body, title, url, typ):
from zengine.messaging.model import Channel, Message
channel = Channel.objects.get(owner=self, is_private=True)
Message(channel=channel, sender=sender, msg_title=title,
body=body, receiver=self, url=url, typ=typ).save()
47 changes: 28 additions & 19 deletions zengine/messaging/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
UserModel = get_object_from_path(settings.USER_MODEL)



def get_mq_connection():
connection = pika.BlockingConnection(BLOCKING_MQ_PARAMS)
channel = connection.channel()
Expand All @@ -27,9 +26,9 @@ def get_mq_connection():

# CHANNEL_TYPES = (
# (1, "Notification"),
# (10, "System Broadcast"),
# (20, "Chat"),
# (25, "Direct"),
# (10, "System Broadcast"),
# (20, "Chat"),
# (25, "Direct"),
# )


Expand All @@ -45,8 +44,12 @@ class Channel(Model):
is_private = field.Boolean()
# is this a One-To-One channel
is_direct = field.Boolean()

# typ = field.Integer("Type", choices=CHANNEL_TYPES)

class Meta:
unique_together = (('is_private', 'owner'),)

class Managers(ListNode):
user = UserModel(reverse_name='managed_channels')

Expand All @@ -56,10 +59,11 @@ def add_message(self, body, title, sender=None, url=None, typ=2):
channel.basic_publish(exchange=self.code_name, body=mq_msg)
Message(sender=sender, body=body, msg_title=title, url=url, typ=typ, channel=self).save()

def _connect_mq(self):
if not self.connection is None or self.connection.is_closed:
self.connection, self.channel = get_mq_connection()
return self.channel
@classmethod
def _connect_mq(cls):
if cls.connection is None or cls.connection.is_closed:
cls.connection, cls.channel = get_mq_connection()
return cls.channel

def create_exchange(self):
"""
Expand All @@ -69,6 +73,10 @@ def create_exchange(self):
channel = self._connect_mq()
channel.exchange_declare(exchange=self.code_name, exchange_type='fanout', durable=True)

def pre_creation(self):
if not self.code_name:
self.code_name = self.key

def post_creation(self):
self.create_exchange()

Expand All @@ -86,16 +94,18 @@ class Subscription(Model):

# status = field.Integer("Status", choices=SUBSCRIPTION_STATUS)

def _connect_mq(self):
self.connection, self.channel = get_mq_connection()
return self.channel
@classmethod
def _connect_mq(cls):
if cls.connection is None or cls.connection.is_closed:
cls.connection, cls.channel = get_mq_connection()
return cls.channel

def create_exchange(self):
"""
Creates user's private exchange
Actually needed to be defined only once.
but since we don't know if it's exists or not
we always call it before
we always call it before binding it to related channel
"""
channel = self._connect_mq()
channel.exchange_declare(exchange=self.user.key, exchange_type='direct', durable=True)
Expand All @@ -117,9 +127,9 @@ def __unicode__(self):


MSG_TYPES = (
(1, "Info"),
(11, "Error"),
(111, "Success"),
(1, "Info Notification"),
(11, "Error Notification"),
(111, "Success Notification"),
(2, "Direct Message"),
(3, "Broadcast Message"),
(4, "Channel Message")
Expand All @@ -138,15 +148,14 @@ class Message(Model):
"""
Permission model
"""
channel = Channel()
sender = UserModel(reverse_name='sent_messages')
receiver = UserModel(reverse_name='received_messages')
typ = field.Integer("Type", choices=MSG_TYPES)
status = field.Integer("Status", choices=MESSAGE_STATUS)
msg_title = field.String("Title")
body = field.String("Body")
url = field.String("URL")
channel = Channel()
sender = UserModel(reverse_name='sent_messages')
# FIXME: receiver should be removed after all of it's usages refactored to channels
receiver = UserModel(reverse_name='received_messages')

def __unicode__(self):
content = self.msg_title or self.body
Expand Down
49 changes: 3 additions & 46 deletions zengine/models/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from pyoko import Model, field, ListNode
from passlib.hash import pbkdf2_sha512
from zengine.messaging.lib import BaseUser


class Permission(Model):
Expand Down Expand Up @@ -41,48 +42,20 @@ def get_permitted_roles(self):
return [rset.role for rset in self.role_set]


class User(Model):
class User(Model, BaseUser):
"""
Basic User model
"""
username = field.String("Username", index=True)
password = field.String("Password")
superuser = field.Boolean("Super user", default=False)
avatar = field.File("Avatar", random_name=True, required=False)

class Meta:
""" meta class
"""
list_fields = ['username', 'superuser']

def __unicode__(self):
return "User %s" % self.username

def __repr__(self):
return "User_%s" % self.key

def set_password(self, raw_password):
"""
Encrypts user password.
Args:
raw_password: Clean password string.
"""
self.password = pbkdf2_sha512.encrypt(raw_password,
rounds=10000,
salt_size=10)

def check_password(self, raw_password):
"""
Checks given clean password against stored encrtyped password.
Args:
raw_password: Clean password.
Returns:
Boolean. True if given password match.
"""
return pbkdf2_sha512.verify(raw_password, self.password)

def get_permissions(self):
"""
Expand All @@ -94,22 +67,6 @@ def get_permissions(self):
users_primary_role = self.role_set[0].role
return users_primary_role.get_permissions()

def get_role(self, role_id):
"""
Gets the first role of the user with given key.
Args:
role_id: Key of the Role object.
Returns:
:class:`Role` object
"""
return self.role_set.node_dict[role_id]

def send_message(self, title, message, sender=None):
from zengine.messaging import Notify
Notify(self.key).set_message(title, message, typ=Notify.Message, sender=sender)


class Role(Model):
"""
Expand Down

0 comments on commit bfdfc10

Please sign in to comment.