Exemplo n.º 1
0
def create_admin():
    user = User\
    (
        firstname='Richard',
        lastname='Stallman',
        email='*****@*****.**',
        avatar_url='https://stallman.org/Portrait_-_Denmark_DTU_2007-3-31.jpg',
        password=encrypt('admin'),
        master=1,
        token=generate_token()
    )

    old_user = sess.query(User).filter(User.email==user.email).first()

    if old_user is not None:
        return False

    sess.add(user)
    sess.commit()

    return True
Exemplo n.º 2
0
    def register(self, data, token):
        ids = []

        if 'users' not in data:
            return throw_error(422, 'JSON missing users array')

        for user in data['users']:

            existing_user = sess.query(User).filter(User.email==user['email']).first()
            if existing_user is not None:
                return throw_error(202, 'User already exists')

            try:
                u = User(\
                    firstname=user['firstname'],\
                    lastname=user['lastname'],\
                    email=user['email'],\
                    avatar_url=user['avatar_url'],\
                    password=encrypt(user['password']),\
                    master=user['master'],\
                    token=token
                )
            except KeyError:
                return throw_error(422, 'Invalid data')

            # Validating the password, is it equal to the confirmation password?
            if u.password != encrypt(user['password_confirm']):
                return throw_error(202, 'Passwords does not match!')

            # Validating each field of the user
            for attr, value in u.__dict__.items():
                if value is '' or value is ' ' or value is None:
                    return throw_error(422, 'Value of {attribute} is empty.'.format(attribute=attr))
            
            # adding user to database
            sess.add(u)

            # flushing the session
            sess.flush()

            # refreshing the user object to obtain the new id
            sess.refresh(u)

            # collecting the id of the user
            ids.append(u.id)

            # Adding custom_fields if there are any
            if 'custom_fields' in user:
                print(user['custom_fields'])
                for field in user['custom_fields']:

                    try:
                        customfield = CustomField(
                            key=field['key'],
                            value=field['value'], user_id=u.id\
                        )
                    except (TypeError, KeyError):
                        return throw_error(422, 'custom_fields is malformed')

                    sess.add(customfield)

            # Finally, we are saving the user
            sess.commit()

        return {'status' : 201, 'ids' : ids, "errors" : None}