Esempio n. 1
0
    def test_crud(self):
        with self.app_context():
            user = UserModel('test', 'abcd')

            self.assertIsNone(UserModel.find_by_username('test'))
            self.assertIsNone(UserModel.find_by_id(1))

            user.save_to_db()

            self.assertIsNotNone(UserModel.find_by_username('test'))
            self.assertIsNotNone(UserModel.find_by_id(1))
Esempio n. 2
0
        def wrapped(*args, **kwargs):
            parser = RequestParser()
            parser.add_argument('class',
                                type=str,
                                help='This field cannot be blank',
                                required=True)

            g.data = data = parser.parse_args()

            # check if class is correct type
            if data['class'] not in ['people', 'landscape']:
                return {'message': 'class field should not be empty'}, 400

            # check if event exists
            g.event = event = EventModel.query.get(kwargs['event_id'])
            if not event:
                return {
                    'message':
                    'Event id {} does not exist'.format(kwargs['event_id'])
                }, 404

            # check if current_user has access to the group
            username = get_jwt_identity()
            g.current_user = current_user = UserModel.find_by_username(
                username)
            group = GroupModel.query.join(GroupModel.users).filter(
                UserModel.username == username,
                GroupModel.id == event.group.id).first()
            if not group:
                return {
                    'message':
                    'Group id {} does not exist'.format(kwargs['event_id'])
                }, 404

            return fn(*args, **kwargs)
Esempio n. 3
0
 def get(self):
     username = get_jwt_identity()
     current_user = UserModel.find_by_username(username)
     if not current_user:
         return {'message': 'Wrong access token'}, 401
     else:
         return {'id': current_user.id, 'username': current_user.username}
Esempio n. 4
0
    def put(self, username):
        data = UserInfo.parser.parse_args()

        user = UserModel.find_by_username(username)

        if user:
            if data['password']:
                data['password'] = UserModel.get_password_hash(
                    data['password'])
                user.password = data['password']
            if data['first_name']:
                user.first_name = data['first_name']
            if data['last_name']:
                user.last_name = data['last_name']
            if data['active']:
                user.active = data['active']
        else:
            if data['password']:
                data['password'] = UserModel.get_password_hash(
                    data['password'])
            user = UserModel(username, data['password'], data['first_name'],
                             data['last_name'], data['active'])

        user.save_to_db()

        return user.json()
Esempio n. 5
0
        def wrapped(*args, **kwargs):
            username = get_jwt_identity()

            g.current_user = current_user = UserModel.find_by_username(
                username)
            if not current_user:
                return {
                    'message': 'User {} does not exist'.format(username)
                }, 401

            # kwargs['event_id'] is always int, so we don't need try block
            g.event = event = EventModel.query.get(kwargs['event_id'])
            if not event:
                return {
                    'message':
                    'Event id {} does not exist'.format(kwargs['event_id'])
                }, 404

            # current user doesn't have access to the event
            user = list(
                filter(lambda x: x.id == current_user.id, event.group.users))
            if not user:
                return {
                    'message':
                    'Event id {} does not exist'.format(kwargs['event_id'])
                }, 404
            return fn(*args, **kwargs)
Esempio n. 6
0
    def post(self):
        data = EmployeeController.parser.parse_args()
        username = data['username']
        email = data['email']
        if (UserModel.find_by_username(username)
                or UserModel.find_by_email(email)):
            return {'message': "User already exists."}, 400
        # Because only admin can create employee
        admin_user = AdminModel.find_by_user_id(current_identity.id)
        if not admin_user:
            abort(403,
                  message="Please use admin or ask admin to crete company.")

        # Create a new Employee user
        employee = EmployeeModel(isAdmin=data['isAdmin'])
        user_data = data
        del user_data['isAdmin']
        user = UserModel(**user_data)
        user = user.hash_password()
        user.employee_id = employee
        employee.user_id = user

        # save the database
        try:
            db.session.add(user)
            db.session.add(employee)
            db.session.commit()
        except (ArgumentError, DataError):
            abort(500,
                  message="Server internal error due to invalid argument.")

        return employee.get_employee(user), 201
Esempio n. 7
0
 def wrapped(*args, **kwargs):
     username = get_jwt_identity()
     g.current_user = current_user = UserModel.find_by_username(
         username)
     if not current_user:
         return {
             'message': 'User {} does not exist'.format(username)
         }, 401
     return fn(*args, **kwargs)
Esempio n. 8
0
    def post(self):
        data = UserRegister.parser.parse_args()

        if UserModel.find_by_username(data["username"]):
            return {"message": "Error: username already exists"}, 409

        user = UserModel(**data)
        user.save()
        return {"message": "User registered successfully"}, 201
Esempio n. 9
0
    def post(self):
        data = UserRegister.parser.parse_args()

        if UserModel.find_by_username(data['username']):
            return {'message': 'This username already exists'}, 400

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

        return {'message': 'User created successfully'}, 201
Esempio n. 10
0
    def post(self):
        data = UserRegister.parser.parse_args()

        if UserModel.find_by_username(data['username']):
            return {"message": "User with that username already exists."}, 400

        user = UserModel(**data)  ## unpack the data, because its a dictionary
        user.save_to_db()

        return {"message": "User created successfully."}, 201
Esempio n. 11
0
def create_tables():
    db.create_all()
    db.session.commit()
    from app.models.user import UserModel
    if not UserModel.find_by_username("admin"):
        UserModel(username="******",
                  password="******",
                  firstName="admin",
                  lastName="admin",
                  phoneNumber="123467890").save_to_db()
Esempio n. 12
0
    def post(self):
        data = UserRegister.parser.parse_args()

        if UserModel.find_by_username(data['username']):
            return {
                'message': 'UserModel has already been created, aborting.'
            }, 400

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

        return {'message': 'user has been created successfully.'}, 201
Esempio n. 13
0
    def test_register_user(self):
        with self.app() as client:
            with self.app_context():
                response = client.post('/register',
                                       data={
                                           'username': '******',
                                           'password': '******'
                                       })

                self.assertEqual(response.status_code, 201)
                self.assertIsNotNone(UserModel.find_by_username('test'))
                self.assertDictEqual(json.loads(response.data),
                                     {'message': 'User created successfully'})
Esempio n. 14
0
    def post(self):
        _user_parser.add_argument('email',
                                  type=str,
                                  required=True,
                                  help="This field cannot be blank.")

        data = _user_parser.parse_args()

        if UserModel.find_by_username(data['username']):
            return {"message": "A user with that username already exists"}, 400

        user = UserModel(data['username'], data['email'], data['password'])
        db.session.add(user)
        db.session.commit()

        return {"message": "User created successfully."}, 201
Esempio n. 15
0
        def wrapped(*args, **kwargs):
            parser = RequestParser()
            parser.add_argument('username',
                                type=str,
                                help='This field cannot be blank',
                                required=True)
            parser.add_argument('password',
                                type=str,
                                help='This field cannot be blank',
                                required=True)

            g.data = data = parser.parse_args()
            g.current_user = current_user = UserModel.find_by_username(
                data['username'])
            if not current_user:
                return {'message': 'Wrong credentials'}, 401
            return fn(*args, **kwargs)
Esempio n. 16
0
    def post(self):
        data = _user_parser.parse_args()

        user = UserModel.find_by_username(data['username'])

        # this is what the `authenticate()` function did in security.py
        if user and check_password_hash(user.password,
                                        data['password']):  #modified 09/19
            # identity= is what the identity() function did in security.py—now stored in the JWT
            access_token = create_access_token(identity=user.id, fresh=True)
            refresh_token = create_refresh_token(user.id)
            return {
                'access_token': access_token,
                'refresh_token': refresh_token
            }, 200

        return {"message": "Invalid Credentials!"}, 401
Esempio n. 17
0
    def post(self):
        data = UserRegister.parser.parse_args()

        if UserModel.find_by_username(data['username']):
            return {
                "message": "A user with that username already exists."
            }, 400

        data['password'] = UserModel.get_password_hash(data['password'])
        user = UserModel(**data)

        try:
            user.save_to_db()
        except:
            return {
                'message': "An error occurred while inserting the user."
            }, 500

        return {"message": "User created successfully."}, 201
Esempio n. 18
0
    def post(self):
        data = parser.parse_args()
        current_user = UserModel.find_by_username(username=data.get("username"))

        if not current_user:
            return {"message": f"User {data.get('username')} doesnt exists"}

        if UserModel.verify_hash(data.get("password"), current_user.password):
            access_token = create_access_token(identity=data.get("username"))
            refresh_token = create_refresh_token(identity=data.get("username"))

            return {
                "message": f"User {data.get('username')} logged",
                "access_token": access_token,
                "refresh_token": refresh_token,
            }

        else:
            return {"message": "wrong credentials"}
Esempio n. 19
0
        def wrapped(*args, **kwargs):
            username = get_jwt_identity()

            current_user = UserModel.find_by_username(username)
            if not current_user:
                return {
                    'message': 'User {} does not exist'.format(username)
                }, 401

            # kwargs['group_id' is always int, so we don't need try and except block
            g.group = group = GroupModel.query.join(GroupModel.users).filter(
                UserModel.username == username,
                GroupModel.id == kwargs['group_id']).first()
            if not group:
                return {
                    'message':
                    'Group id {} does not exist'.format(kwargs['group_id'])
                }, 404

            return fn(*args, **kwargs)
Esempio n. 20
0
    def post(self):
        args = parser.parse_args(strict=True)
        username = args["username"]
        password = args["password"]
        first_name = args["first_name"]
        last_name = args["last_name"]
        phone_number = args["phone_number"]
        birth_date = args["birth_date"]
        user = UserModel.find_by_username(username)
        if user:
            return {"Message:": "this username is already taken"}, 409

        ret = UserModel(username=username,
                        password=password,
                        firstName=first_name,
                        lastName=last_name,
                        phoneNumber=phone_number,
                        birthDate=birth_date).save_to_db()
        if ret:
            return {"Message": "Created", "user_id": ret.id}, 201
        return {"Message": "Error", "user_id": ret.id}, 500
Esempio n. 21
0
    def post(self, username):
        if UserModel.find_by_username(username):
            return {
                'message':
                "A user with the username '{}' already exists.".format(
                    username)
            }, 400

        data = UserInfo.parser.parse_args()

        data['password'] = UserModel.get_password_hash(data['password'])

        user = UserModel(username, data['password'], data['first_name'],
                         data['last_name'], data['active'])

        try:
            user.save_to_db()
        except:
            return {
                'message': "An error occurred while inserting the user."
            }, 500

        return user.json(), 201
Esempio n. 22
0
        def wrapped(*args, **kwargs):
            parser = RequestParser()
            parser.add_argument('username',
                                type=str,
                                help='This field cannot be blank',
                                required=True)
            parser.add_argument('password',
                                type=str,
                                help='This field cannot be blank',
                                required=True)
            parser.add_argument('icon_url',
                                type=str,
                                help='This field cannot be blank',
                                required=True)

            g.data = data = parser.parse_args()

            if UserModel.find_by_username(data['username']):
                return {
                    'message':
                    'User {} already exists'.format(data['username'])
                }, 401
            return fn(*args, **kwargs)
Esempio n. 23
0
    def post(self):
        data = parser.parse_args()
        new_user = UserModel(
            username=data.get("username"),
            password=UserModel.generate_hash(data.get("password")),
            email=data.get("email"),
        )
        try:
            if UserModel.find_by_username(data.get("username")) or UserModel.find_by_email(data.get("email")):
                return {"message": f"User alread exists"}

            new_user.save_to_db()
            access_token = create_access_token(identity=data.get("username"))
            refresh_token = create_refresh_token(identity=data.get("username"))

            return {
                "message": f"User {data.get('username')} was created",
                "access_token": access_token,
                "refresh_token": refresh_token,
            }

        except:
            return {"message": "Something went wrong"}, 500
Esempio n. 24
0
 def delete(self, username):
     user = UserModel.find_by_username(username)
     if user:
         user.delete_from_db()
         return {'message': 'User deleted.'}
     return {'message': 'User not found.'}, 404
Esempio n. 25
0
def authenticate(username, password):
    user = UserModel.find_by_username(username)
    if user and safe_str_cmp(user.password, password):
        return user
Esempio n. 26
0
def authenticate(username, password):
    user = UserModel.find_by_username(username)
    if user and safe_str_cmp(user.password, UserModel.get_password_hash(password)) and user.active:
        return user
    return None
Esempio n. 27
0
 def get(self, username):
     user = UserModel.find_by_username(username)
     if user:
         return user.json()
     return {'message': "User not found"}, 404