Esempio n. 1
0
    async def get(self):
        ws = web.WebSocketResponse()
        await ws.prepare(self.request)

        session = await get_session(self.request)
        user = UserMySQL(id=session.get('user'))
        user = await user.get_user_by_id()

        for _ws in self.request.app['websockets']:
            _ws.send_str('%s joined' % user.login)
        self.request.app['websockets'].append(ws)

        async for msg in ws:
            if msg.tp == MsgType.text:
                if msg.data == 'close':
                    await ws.close()
                else:
                    message = MessageMySQL(user_id=session['user'],
                                           room_id=session['room_id'])
                    message = await message.insert_message_to_db(msg=msg.data)
                    log.debug('result:%s' % message)
                    for _ws in self.request.app['websockets']:
                        _ws.send_str('(%s) %s' % (user.login, msg.data))
            elif msg.tp == MsgType.error:
                log.debug('ws connection closed with exception %s' %
                          ws.exception())

        self.request.app['websockets'].remove(ws)
        for _ws in self.request.app['websockets']:
            _ws.send_str('%s disconected' % user.login)
        log.debug('websocket connection closed')

        return ws
Esempio n. 2
0
 async def get(self, *args, **kwargs):
     session = await get_session(self.request, )
     if session.get('user'):
         user = UserMySQL(id=session['user'], )
         return {'content': 'Please create or select room',
                 'user': await user.get_user_by_id(),
                 'rooms': RoomMySQL.select(), }
     else:
         raise web.HTTPForbidden(body=b'Forbidden', )
Esempio n. 3
0
    async def get(self, *args, **kwargs):
        session = await get_session(self.request)
        if session.get('user'):
            user = UserMySQL(id=session['user'], )
            user = await user.get_user_by_id()

            if isinstance(user, bool):
                del session['user']
                redirect(self.request, 'login')

            if user.is_admin:
                redirect(self.request, 'admin')
            else:
                redirect(self.request, 'rooms')
        else:
            redirect(self.request, 'login')
Esempio n. 4
0
    async def post(self, **kw):
        data = await self.request.post()
        user = UserMySQL(**data, )
        result = await user.create_user()
        if isinstance(result, UserMySQL):

            session = await get_session(self.request)
            set_session(session=session, user=result.id, )

            dict_response = {'content_type': 'application/json',
                             'status': 200,
                             'charset': 'utf-8', }

            dict_response.update({'text': json.dumps({'result': 'Ok', 'redirect': '/login/', }, ), }, )
            return web.Response(**dict_response)
        else:

            return web.Response(content_type='application/json', text=convert_json(result))
Esempio n. 5
0
    async def post(self, *args, **kwargs):
        """ AJAX """
        data = await self.request.post()

        user = UserMySQL(**data)
        result = await user.check_user()

        dict_response = {'content_type': 'application/json',
                         'status': 200,
                         'charset': 'utf-8', }

        if isinstance(result, UserMySQL, ):
            session = await get_session(self.request, )
            set_session(session=session, user=result.id, )

            if result.is_admin:
                dict_response.update({'text': json.dumps({'result': 'Ok', 'redirect': '/admin/', }, ), }, )
            else:
                dict_response.update({'text': json.dumps({'result': 'Ok', 'redirect': '/rooms/', }, ), }, )

        else:
            dict_response.update({'text': convert_json(result, ), }, )

        return web.Response(**dict_response)
Esempio n. 6
0
import peewee_async
import peewee as pw
from settings import DB_HOST,DB_PORT, DB_LOGIN, DB_PASSWD, DB_NAME,\
    ADMIN_LOGIN, ADMIN_PASSWD, ADMIN_EMAIL

db = peewee_async.MySQLDatabase(host=DB_HOST, port=DB_PORT,
                                user=DB_LOGIN, password=DB_PASSWD,
                                database=DB_NAME, )


class BaseMySQLModel(pw.Model):
    """A base model that will use our MySQL database"""
    class Meta:
        database = db


__all__ = [BaseMySQLModel, ]

# Connect to our database.
db.connect()

from auth.models import UserMySQL
from chat.models import RoomMySQL, MessageMySQL

# Only create the tables if they do not exist.
db.create_tables([UserMySQL, RoomMySQL, MessageMySQL, ], safe=True)

user = UserMySQL(login=ADMIN_LOGIN, password=ADMIN_PASSWD, email=ADMIN_EMAIL, is_admin=True)
user.create_user()