def get_one(self):
     response = None
     if self._method == 'POST':
         if not self._json_data:
             self.make_message('Required params is absent')
             return
         else:
             action = self._json_data.get('action')
             if action:
                 config = Config.get('get_one.' + action, 'admin')
                 if config.get('model') and config.get('field'):
                     field = config.get('field')
                     if self._json_data.get(field) is not None:
                         arr = config.get('model').strip().split(':')
                         model_name = arr[0]
                         formatter = arr[1]
                         model = getattr(
                             importlib.import_module(
                                 'app.models.' + model_name, model_name),
                             model_name)
                         model_result = model.where(
                             field, '=',
                             self._json_data.get(field)).first()
                         if model_result is not None:
                             response = getattr(model_result, formatter)()
                         else:
                             response = {}
                     else:
                         raise Exception('Param "' + field +
                                         '" is required')
                 else:
                     raise Exception(
                         'Params "model" and "field" are required')
             else:
                 self.make_message('Action is not defined')
                 return
     self.make_response(response)
 def validate_email(attr, value):
     import re
     result = re.match(Config.get('email_regexp'), value)
     return False if result is None else True
def setup_middlewares(App):
    print('errors setup')
    error_middleware = error_handler(Config.get("errors"))
    App.middlewares.append(error_middleware)
async def handle(request):
    try:
        # request.rel_url is instance of "URL" object
        # remove hash from url
        url = str(request.rel_url).replace('#', '')
        url_params = url.split('?')
        get_params = None
        # if we have get params
        if len(url_params) > 1:
            # cut get params from main route
            url = url_params[0]
            # get string of get params
            parsed_url = urlparse(url_params[1])
            # convert get params from string to dictionary
            get_params = parse_qsl(parsed_url.path)

        # print(request.match_info)

        # set current_route as it was added in request_object
        current_route = url.split('/')
        action = current_route.pop()
        # if we using not /api/v1/controller/action and just controller/action (for frontend)
        if len(current_route) >= 3:
            version = current_route[2]
        else:
            version = 'v1'
        handler = request_object.get(url)
        if handler is not None:
            current_route = '/'.join(current_route) + '/' + action
        else:
            current_route = '/'.join(current_route) + '/{action}'

        handler = request_object.get(current_route)

        # if controller.action exists
        if handler is not None and len(handler) in range(1, 3):
            controller_class = handler[0]

            # create controller object
            instance = controller_class(request)
            # init get parameters
            instance.set_get_params(get_params)
            # check if controller is upload - we need other handler

            # check for existing controller's action
            versionized_action_exists = hasattr(instance,
                                                action + '_' + version)
            action_exists = hasattr(instance, action)
            if action_exists or versionized_action_exists:
                if versionized_action_exists:
                    is_async = asyncio.iscoroutinefunction(
                        getattr(instance, action + '_' + version))
                else:
                    is_async = asyncio.iscoroutinefunction(
                        getattr(instance, action))

                if is_async is False:
                    json_data = None
                    post_params = await request.post()
                    try:
                        json_data = await request.json()
                    except Exception:
                        pass

                    # init parameters
                    instance.set_post_params(post_params)
                    instance.set_json_data(json_data)

                    # execute middlewares
                    if len(handler) == 2:
                        if instance.get_request().method != 'OPTIONS':
                            middlewares = handler[1]
                            for middleware in middlewares:
                                middleware_module = importlib.import_module(
                                    'app.middlewares.' + middleware,
                                    middleware)
                                middleware_obj = getattr(
                                    middleware_module, middleware)(instance)
                                middleware_obj.handle()
                                if middleware_obj.get_next() is False:
                                    return send_response(
                                        web, middleware_obj.get_controller())
                        # execute controller action from route
                        if hasattr(instance, '_before'):
                            getattr(instance, '_before')()
                        result = getattr(instance, 'index')(action, version)
                        # return web.HTTPFound('http://absolute.url/and/path/if/you/want')
                        if result is not None:
                            return result
                else:
                    # middlewares ???
                    await getattr(instance, 'index_async')(action, version)
            else:
                # call handle_404 from middlewares/HandleErrors
                return web.Response(status=404)
        else:
            raise Exception('Can not find route for url ' + url)
        log_text = "<div><ul><li style='color: blue;'>" + datetime.datetime.now(
        ).strftime("%Y-%m-%d %H:%M:%S") + "</li>"
        headers_str = '<ul>'
        for header in request.headers:
            headers_str += "<li><strong>{0}</strong>: {1}</li>".format(
                header, request.headers[header])
        log_text += "<li><i>" + str(request.rel_url) + "</i></li>"
        log_text += "<li>" + headers_str + "</ul></li>"
        log_text += "<li>" + str(instance.json()) + "</li>"
        log_text += "<li>" + str(instance.get_response()) + "</li></ul></div>"
        log_filename = expanduser(
            "~"
        ) + "/dev/static_" + settings.CUR_APP_NAME + "/apilog/" + datetime.datetime.now(
        ).strftime("%Y-%m-%d") + ".html"
        logfile = open(log_filename, 'a')
        logfile.write(log_text)
        logfile.close()
        return send_response(web, instance)

    except Exception as exception:
        from app.helpers.Mailer import Mailer
        from time import gmtime, strftime
        import traceback
        import random
        import string

        for email in Config.get('admin_emails'):
            mailer = Mailer()
            mailer.to(email)
            mailer.subject('Exception Error')
            raw_html = ''
            for raw in traceback.format_exc().splitlines():
                raw_html += raw + '</br >'
            html = '<html><body>' + raw_html + '</body></html>'
            s = string.ascii_lowercase + string.digits
            filename = strftime("%Y-%m-%d_%H:%M:%S_", gmtime()) + ''.join(
                random.sample(s, 10)) + '.html'
            file_exception = open(
                '/home/dev/dev/static_' + settings.CUR_APP_NAME +
                '/exceptions/' + filename, 'w')
            file_exception.write(html)
            file_exception.close()
            html_msg = '<html><body><a href="http://46.101.254.89/static_' + settings.CUR_APP_NAME + '/exceptions/' \
                       + filename + '">' + str(exception) + '</a></body></html>'
            mailer.html(html_msg)
            mailer.send()
        return web.Response(status=500)
              title="FLIC")

# App.router.add_get('/', handle)
# App.router.add_get('/{name}', handle)


# add middlewares for appliction
def setup_middlewares(App):
    print('errors setup')
    error_middleware = error_handler(Config.get("errors"))
    App.middlewares.append(error_middleware)


# application entry point
setup_middlewares(App)
# web.run_app(App, port=8001)

loop = asyncio.get_event_loop()


async def init_redis(port):
    from app.helpers.Redis import Redis
    conn = await aioredis.create_connection(('localhost', port), loop=loop)
    Redis.set_connection(conn)
    # conn.close()
    # await conn.wait_closed()


redis_port = Config.get('redis.port')
loop.run_until_complete(init_redis(redis_port))
 def __init__(self, config_name='mail'):
     self.__config = Config.get(config_name, 'main')
 def set_api_token_error_status(self):
     self.get_controller().set_status(
         Config.get('response_codes.api_token_error'))
 def send_message(self, message):
     self.set_next(False)
     self.get_controller().set_status(Config.get('response_codes.message'))
     self.get_controller().make_response({}, message=message)
 def send_actions(self, actions):
     self.set_next(False)
     self.get_controller().set_status(Config.get('response_codes.error'))
     self.get_controller().make_response({}, actions=actions)
Beispiel #10
0
 def __check_device(self, device_os):
     return device_os in Config.get('user_pushes.device_types')
 def make_message(self, message, actions=[]):
     self.set_status(Config.get('response_codes.message'))
     self.make_response({}, message=message, actions=actions)
 def make_actions(self, actions):
     self.set_status(Config.get('response_codes.error'))
     self.make_response({}, actions=actions)
    def update_profile(self):
        user = self.get_user()
        new_password = self._json_data.get('new_password')
        old_password = self._json_data.get('old_password')

        if new_password and old_password:
            if not user.is_social:
                if user.password_correct(old_password):
                    user.set_password(new_password)
                    user.save()
                    self.make_response(user.format_default())
                else:
                    self.make_message('Incorrect old password.')
            else:
                self.make_message('Please signup to change your password.')
        else:
            attrs = ['first_name', 'last_name', 'name', 'email', 'photo']
            not_empty_keys = ['email']
            for key in attrs:
                new_value = self._json_data.get(key)
                if new_value is not None and new_value:
                    if key == 'email':
                        if re.match(Config.get('email_regexp'), new_value):
                            email_exists = User.where('id', '<>',
                                                      user.id).where(
                                                          'email', '=',
                                                          new_value).exists()
                            if not email_exists:
                                user.email = new_value
                            else:
                                self.make_message("This email already taken.")
                                return
                        else:
                            self.make_message("Invalid email format.")
                            return
                    elif key == 'photo':
                        from app.models.UploadedFile import UploadedFile
                        file_object = UploadedFile.get_by_urls(new_value,
                                                               is_single=True)
                        if file_object is not None:
                            user.photo = file_object.file
                            file_object.delete()
                    elif key == 'name':
                        names = new_value.strip().split(' ')
                        if len(names) == 1:
                            user.first_name = names[0]
                        elif len(names) == 2:
                            user.first_name = names[0]
                            user.last_name = names[1]
                        elif len(names) > 2:
                            user.first_name = names[0]
                            names.pop(0)
                            user.last_name = ' '.join(names)
                    else:
                        setattr(user, key, new_value)
                elif key not in not_empty_keys and new_value is not None:
                    if key is 'name':
                        user.first_name = ''
                        user.last_name = ''
                    elif key is 'photo':
                        # remove file physically
                        setattr(user, key, '')
                    else:
                        setattr(user, key, '')
            user.save()
            self.make_response(user.format_default())
    def login_social(self):
        # self._json_data
        # social_alias = self.post('social_alias')
        # token = self.post('token')
        token = self._json_data.get('token')
        social_alias = self._json_data.get('social_alias')
        is_agree = True if self._json_data and self._json_data.get(
            'is_agree') else False
        # if is_agree is not True:
        #     self.make_message('Please confirm terms agreement.')
        if social_alias:
            from core.helpers.Social import Social
            if token or social_alias == 'twitter':
                # response = Social.get_facebook_user(token)
                response = Social.get_user(social_alias, token,
                                           self._json_data)
                # if social_alias == 'twitter':
                # @TODO: make method in Social helper for getting user avatar
                if response is not None:
                    social_config = Social.get_config()
                    user_social = None
                    for field in Social.get_social_fields(social_alias):
                        if field[0] == 'social_ident':
                            ident_key = field[1]
                            ident_value = Config.get(ident_key, response)
                            user_social = UserSocial.find_by_ident(
                                ident_value, social_alias)
                    if user_social is None:
                        if is_agree is not True:
                            self.make_message(
                                'Please confirm terms agreement.',
                                ['goto_auth'])
                        else:
                            user_social = UserSocial()
                            user = User()
                            user_social.alias = social_alias
                            for field in Social.get_social_fields(
                                    social_alias):
                                social_key = field[1] if len(
                                    field) >= 2 else field[0]
                                # value = response.get(social_key)
                                value = Config.get(social_key, response)
                                # execute all function defined in fields
                                if len(field) > 2:
                                    for i, func in enumerate(field):
                                        if i > 1:
                                            value = func(value)

                                if value is not None:
                                    setattr(user_social, field[0], value)
                                    user_field_val = social_config[
                                        social_alias]['social_to_user'].get(
                                            field[0])
                                    if user_field_val is not None:
                                        setattr(user, user_field_val, value)
                            # social media returned not empty user unique identifier
                            if hasattr(user_social, 'social_ident'
                                       ) and user_social.social_ident:
                                user.generate_token()
                                from core.models.Connection import Connection
                                with Connection.get_db().transaction():
                                    user.is_social = True
                                    user.save()
                                    if user.add_role_group('api'):
                                        user_social.user_id = user.id
                                        user_social.save()
                                        self.make_response(
                                            user_social.user.format_default())
                                    else:
                                        user.delete()
                                        raise Exception(
                                            'cant create user role.')
                            else:
                                self.make_message(
                                    'Cant get social media user unique identifier.'
                                )
                    else:
                        # user already exists. wee need return existing user
                        self.make_response(user_social.user.format_default())
                else:
                    self.make_actions(['invalid_oauth2_token'])
            else:
                self.make_actions(['parameter_token_required'])
        else:
            self.make_actions(['parameter_social_alias_required'])
#import app.config.db as db_config
import core.models.Connection as Connection
import datetime, time
from core.models.Position import Position
from core.helpers.Config import Config

ConnStaticClass = Connection.Connection
postgres = Config.get('postgres', 'db_config')
ConnStaticClass.init({'postgres': postgres})
ConectionModel = ConnStaticClass.get_model()


class ModelCore(ConectionModel):

    date_format = 'unix_timestamp'
    _array_fields = []

    # left only specified keys in dictionary
    def _left_keys(self, keys):
        data = self.to_dict()
        new_dict = {}
        if data:
            for key in keys:
                key_to_set = data.get(key)
                if key_to_set is not None:
                    new_dict[key] = data[key]
                else:
                    new_dict[key] = ""
        return new_dict

    # remove specified keys from dictionary