Ejemplo n.º 1
0
    def post(self):
        if request.json is None:
            abort(400, message=u"Пустые параметры")
        from services.userservice import UserService
        login = request.json.get('login')
        email = request.json.get('email')
        password = request.json.get('password')
        retypepassword = request.json.get('retypepassword')
        if login is None or email is None or password is None or \
                        retypepassword is None:
            abort(400, message=u"Недостаточно данных")
        if password != retypepassword:
            abort(400, message=u"Пароли не совпадают")

        if not UserService.check_duplicate(login, email):
            abort(400, message=u"Дупликат")

        user = UserService.registration(login, email, password)

        db.session.add(user)
        db.session.commit()

        return jsonify({
            'token': user.generate_auth_token().decode('ascii')
        })
Ejemplo n.º 2
0
def create_superuser():
    from services.userservice import UserService
    with app.app_context():
        if UserService.check_duplicate('admin'):
            user = UserService.registration(
                'admin', '*****@*****.**', 'admin', is_superuser=True,
                first_name='Админов', last_name='Админ', role=['admin'])
            db.session.add(user)
            db.session.commit()
        else:
            debug(u'Error - has admin.')
            raise Exception(u"Has admin.")
Ejemplo n.º 3
0
    def pre_save(self, obj, data):
        if obj.id is None:
            password = data.get('password')
            retypepassword = data.get('retypepassword')
            if password is None or retypepassword is None:
                raise UserCanon.UserCanonExc(u"Не заполнены пароли.")
            if password != retypepassword:
                raise UserCanon.UserCanonExc(u"Пароли не совпадают!")
            obj.password = password

        roles = data.get('roles')

        login = data.get('login')
        email = data.get('email')

        if login is None or email is None:
            raise UserCanon.UserCanonExc(
                u"Не заполнены логин или почтовый ящик.")

        if not roles:
            raise UserCanon.UserCanonExc(
                u"Не выбраны роли для пользователя.")
        obj._roles = [x['name'] for x in roles]

        if not UserService.check_duplicate(login, email, id):
            raise UserCanon.UserCanonExc(
                u"В системе уже есть запись с именем '%s'" % login)
        return obj
Ejemplo n.º 4
0
    def get(self):
        from services.userservice import UserService
        token = request.authorization['username']

        user = UserService.user_to_token(token)
        if user:
            return jsonify({'identity': [x.name for x in user.roles]})
        abort(401)
Ejemplo n.º 5
0
def change_password(username, password):
    from services.userservice import UserService

    with app.app_context():
        user = UserService.change_password(username, password)

        db.session.add(user)
        db.session.commit()
Ejemplo n.º 6
0
    def __initialize(self):
        """
        Инициализация БД. Нужен как минимум один пользователь.
        """

        from services.userservice import UserService

        with self.application.app_context():
            user = UserService.registration('I', '*****@*****.**', 'I')
            self.db.session.add(user)
            self.db.session.commit()
Ejemplo n.º 7
0
    def post(self):
        """
        Синхронизация Рабочего Места с сервером.

        Для синхронизации требуется помещать в заголовки DeviceId.


        """
        try:
            deviceId = request.headers.environ.get("HTTP_DEVICEID")

            workday_items = request.json['data']['items']

            sync = SyncSession()
            sync.datetime = datetime.datetime.now()
            sync.deviceId = deviceId
            db.session.add(sync)

            for workday_item in workday_items:
                user = UserService.get_by_name(workday_item['username'])
                datetime_start = parser.parse(workday_item['date_start'])

                workday = SyncService.get_or_create(user.id, datetime_start)

                if not workday.id:
                    workday.sync_start = sync

                if workday_item['date_end']:
                    workday.datetime_end = parser.parse(
                        workday_item['date_end'])
                    workday.sync_end = sync
                workday.username = workday_item['username']
                db.session.add(workday)

                for item in workday_item['items']:
                    dt = parser.parse(item['datetime'])
                    bc = item['barcode']
                    op = item['operation']
                    cnt = item['count']

                    s_item = SyncItemSession()
                    s_item.sync = sync
                    s_item.workday = workday
                    s_item.barcode = bc
                    s_item.datetime = dt
                    s_item.operation = op
                    s_item.count = cnt
                    db.session.add(s_item)
            db.session.commit()
            return "ok"
        except Exception as exc:
            abort(400, message="BLA")
Ejemplo n.º 8
0
    def save_model(self, obj):
        if obj.id is None:
            return UserService.registration(
                obj.login, obj.email, obj.password, obj.is_superuser,
                obj.first_name, obj.last_name, obj._roles)
        _roles = [role.name for role in obj.roles]

        for rol in list(set(_roles).difference(obj._roles)):
            user_datastore.remove_role_from_user(obj, rol)
        for rol in list(set(obj._roles).difference(_roles)):
            user_datastore.add_role_to_user(obj, rol)

        db.session.add(obj)
        return obj
Ejemplo n.º 9
0
    def get(self, id):
        from services.userservice import UserService
        user = UserService.get_by_id(id)

        fname = user.first_name or ""
        lname = user.last_name or ""
        position = u"Администратор" if user.is_superuser else u"Пользователь"

        name = " ".join([fname, lname]) if fname or lname else "Без имени"

        return jsonify({
            'id': user.id,
            'name': name,
            'position': position,
            'iconUrl': "/static/images/users/empty.png",
            'is_superuser': user.is_superuser
        })
Ejemplo n.º 10
0
    def get(self):
        from services.userservice import UserService
        token = request.authorization['username']

        user = UserService.user_to_token(token)
        if user:
            fname = user.first_name or ""
            lname = user.last_name or ""
            position = u"Администратор" if user.is_superuser \
                else u"Пользователь"

            name = " ".join([fname, lname]) if fname or lname else "Без имени"

            return jsonify({
                'id': user.id,
                'name': name,
                'position': position,
                'iconUrl': "/static/images/users/empty.png",
                'is_superuser': user.is_superuser
            })
        else:
            abort(401)