Beispiel #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.")
Beispiel #2
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)
        data = parser.parse_args()

        if not re.match(UserModel.USERNAME_FORMAT, data['username']):
            return {'message': 'User not found'}

        current_user = UserModel.find_by_username(username=data['username'],
                                                  exclude_deleted=True)
        if not current_user or current_user.deleted_at != None:
            return {'message': 'User {} not found'.format(data['username'])}

        if UserModel.verify_hash(data['password'], current_user.password):
            access_token = create_access_token(current_user.jwt_serialize())
            refresh_token = create_refresh_token(current_user.jwt_serialize())
            return {
                'message': 'Logged in as {}'.format(current_user.username),
                'access_token': access_token,
                'refresh_token': refresh_token
            }
        else:
            return {'message': 'Wrong credentials'}
Beispiel #3
0
 def post(cls):
     data = _user_parser.parse_args()
     user = UserModel.find_by_username(data['username'])
     data_password_hashed = sha512(
         data['password'].encode('utf-8')).hexdigest()
     if user and safe_str_cmp(data_password_hashed, user.password):
         access_token = create_access_token(identity=user.id)
         return {'access_token': access_token}
     return {'message': 'Invalid credentials'}, 401
Beispiel #4
0
 def test_register_user(self):
     response = self.client.post(
         '/register',
         data=json.dumps({
             'username': '******',
             'password': '******'
         }),
         headers={'Content-Type': 'application/json'})
     self.assertEqual(response.status_code, 201)
     self.assertIsNotNone(UserModel.find_by_username('test'))
     expected = {"message": "User created successfully."}
     self.assertDictEqual(expected, json.loads(response.data))
Beispiel #5
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
Beispiel #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
Beispiel #7
0
def authenticate_user(username, password):
    user = UserModel.find_by_username(username)
    if user and safe_str_cmp(user.password, password):
        return user.username