Ejemplo n.º 1
0
    def test_crud(self):
        user = UserModel('Test', 'password')

        self.assertIsNone(
            user.find_by_username('Test'),
            "Found a user with name '{}', but expected not to.".format(
                user.username))
        self.assertIsNone(user.find_by_id(1),
                          "Found a user with id: 1, but expected not to.")

        user.save_to_db()

        self.assertIsNotNone(
            user.find_by_username('Test'),
            "Did not find a user with name '{}', but expected to.".format(
                user.username))
        self.assertIsNotNone(
            user.find_by_id(1),
            "Did not find a user with id: 1, but expected to.")

        user.delete_from_db()

        self.assertIsNone(
            user.find_by_username('Test'),
            "Found a user with name '{}', but expected not to.".format(
                user.username))
        self.assertIsNone(user.find_by_id(1),
                          "Found a user with id: 1, but expected not to.")
Ejemplo n.º 2
0
    def post(self):
        # make sure all required fields are present
        user_data = self.parser.parse_args()

        try:
            user = UserModel(**user_data)
            user.save_to_db()
        except Exception:
            return {"message": "Unable to create user"}, 500
        return {"message": "successfully created user", "payload": user.json()}, 201
Ejemplo n.º 3
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username',
                            help='This field cannot be blank',
                            location='json',
                            required=True)
        parser.add_argument('password',
                            help='This field cannot be blank',
                            location='json',
                            required=True)
        parser.add_argument('email',
                            help='This field cannot be blank',
                            location='json',
                            required=True)
        data = parser.parse_args()

        if not re.match(UserModel.USERNAME_FORMAT, data['username']):
            return {
                'message':
                'Username must consist of letters, numbers, hyphens and underscores'
            }

        if UserModel.find_by_username(username=data['username'],
                                      exclude_deleted=False):
            return {
                'message':
                'Username {} already exists'.format(data['username'])
            }

        if UserModel.find_by_email(email=data['email'], exclude_deleted=False):
            return {
                'message':
                'User with email {} already exists'.format(data['email'])
            }

        new_user = UserModel(
            username=data['username'],
            password=UserModel.generate_hash(data['password']),
            email=data['email'],
            deleted_at=None,
        )

        try:
            new_user.save_to_db()
            access_token = create_access_token(new_user.jwt_serialize())
            refresh_token = create_refresh_token(new_user.jwt_serialize())
            return {
                'message': 'User {} was created'.format(data['username']),
                'access_token': access_token,
                'refresh_token': refresh_token
            }
        except:
            return {'message': 'Something went wrong'}, 400
Ejemplo n.º 4
0
 def test_register_duplicate_user(self):
     user = UserModel('test', 'password')
     user.save_to_db()
     response = self.client.post(
         '/register',
         data=json.dumps({
             'username': '******',
             'password': '******'
         }),
         headers={'Content-Type': 'application/json'})
     self.assertEqual(response.status_code, 400)
     expected = {"message": "A user with that username already exists"}
     self.assertDictEqual(expected, json.loads(response.data))
Ejemplo n.º 5
0
def load_tables():
    if len(DryBreadModel.find_all()) == 0:
        print('Database does not exist/is empty. Creating from file...')
        data = dict()
        with open('tmp_database.json', 'r', encoding='utf-8') as f:
            data = json.loads(f.read())

        for e in data['suchary']:
            if e['type'] <= cfg['JOKE_TYPE']:
                db = DryBreadModel(e['q'], e['a'])
                db.save_to_db()

        print('drybreads loaded:', [x.json() for x in db.find_all()])

####users database
    from api.models.user import UserModel
    admin = UserModel('admin', 'admin', UserModel.ROLE_ADMIN)
    admin.save_to_db()
Ejemplo n.º 6
0
    def on_post(self, req, resp):

        data = req.context.get("json")

        if UserModel.find_by_username(data.get("username")):
            payload = {
                "message":
                f"User with username:{data.get('username')} already exists"
            }
            resp.body = json.dumps(payload, ensure_ascii=False)
            resp.status = falcon.HTTP_400
        else:

            user = UserModel(**data)
            user.save_to_db()

            payload = {"message": "User created sucessfully"}
            resp.body = json.dumps(payload, ensure_ascii=False)
            resp.status = falcon.HTTP_201
Ejemplo n.º 7
0
    def run(self):
        username = input("Username: "******"Email: ")
        is_admin = input("Is admin? [y/n]: ")
        password = getpass.getpass("Password: "******"admin"] if is_admin.lower() == 'y' else []

        try:
            new_user = UserModel(
                username = username,
                email = email,
                password = UserModel.generate_hash(password)
            )
            new_user.roles = roles
            new_user.save_to_db()

            print('\n+ User created')
            print('|_ Username: {}'.format(new_user.username))
            print('|_ Email:    {}'.format(new_user.email))
            print('|_ Roles:    {}'.format(new_user.roles))
        except:
            print('User wasn\'t saved')