Ejemplo n.º 1
0
def get_user(current_user, search_id):
    user = UserModel.get_user_by_id(current_user)
    if user['role'] != "admin":
        return jsonify(
            {"message": "You are not authorised to view this function"}), 401
    user = UserModel.get_user_by_id(search_id)
    return jsonify({'User': user}), 200
Ejemplo n.º 2
0
    def post(self):
        data = parser.parse_args()
        # lookup by username
        current_user = UserModel.find_by_username(data['username'])
        if not current_user:
            return {
                "message": "User {} doesn't exist".format(data['username'])
            }

        user_logging = UserLoggingModel(user_id=current_user.id)
        try:
            user_logging.save_to_db()
        except Exception:
            pass

        if UserModel.verify_hash(data['password'], current_user.password):
            access_token = create_access_token(identity=data['username'])
            refresh_token = create_refresh_token(identity=data['username'])
            return {
                "message": "Logged in as {}".format(current_user.username),
                'access_token': access_token,
                'refresh_token': refresh_token
            }
        else:
            return {"message": "Wrong password"}
Ejemplo n.º 3
0
    def post(self):
        data = UserRegister.parser.parse_args()
        item = UserModel.find_by_username(data["username"])
        if item:
            return {"message": "username already exists"}, 400

        user = UserModel(**data)
        user.save()
        return {"message": "user created successfully"}
Ejemplo n.º 4
0
def get_users(current_user):
    user = UserModel.get_user_by_id(current_user)
    if user['role'] != "admin":
        return jsonify(
            {"message": "You are not authorised to view this function"}), 401
    users_list = UserModel.get_users()
    return jsonify({
        'Users of ManagerStore':
        [make_public_user(user) for user in users_list]
    }), 200
Ejemplo n.º 5
0
def insert():
    """
    Validates and inserts user
    """
    new_user = request.json 
    user = UserModel(new_user)
    user.validate()
    unique_fields = [{"email"}]
    repository.insert_one_unique_fields(COLLECTION_NAME, user.to_dict(), unique_fields)
    return {"message": "success!"}, 201
Ejemplo n.º 6
0
 def post(self):
     try:
         requested_data = request.get_json()
         if UserModel.get_user_by_username(requested_data["username"]):
             return {"msg": "Username already exists"}, 400
         if UserModel.get_user_by_email(requested_data["email"]):
             return {"msg": "Email already exists"}, 400
         user_schema = UserSchema()
         result: dict = user_schema.load(requested_data)
         UserModel.register_user(**result)
         return {"msg": "Registration successful"}, 201
     except ValidationError as err:
         return jsonify(err.messages, 400)
def add_participant(workshop_id, data) -> (dict, int):
    workshop = WorkshopModel.find_by_id(workshop_id=workshop_id)
    # Check if given workshop_id exists in DB
    if workshop is None:
        raise EntityNotFoundError

    # Deserialize data
    schema = ParticipantSchema()
    data, err_msg, err_code = schema.loads_or_400(data)
    if err_msg:
        return err_msg, err_code

    # Check if there is already a participant with this email in DB
    user = UserModel.find_by_email(data.get("email"))
    if user is None:
        participant = UserModel(
            email=data.get("email"),
            firstName=data.get("firstName"),
            lastName=data.get("lastName"),
            role=[Roles.PARTICIPANT.value],
            workshopParticipations=[workshop_id],
        )

        status = WorkshopParticipantStatus.CREATED.value
    else:
        # If user already exists, check if it's a participant
        if Roles.PARTICIPANT.value in user.role:
            # Raise error if participant already registred in workshop
            if user.userId in [p.user.id for p in workshop.participants]:
                raise InvalidDataError(
                    msg="Participant already registered for this workshop"
                )
            status = WorkshopParticipantStatus.EXISTING.value
        else:
            # add participant role otherwise
            user.add_participant_role()
            status = WorkshopParticipantStatus.CREATED.value

        participant = user
        participant.workshopParticipations.append(workshop_id)

    # Append participant to workshop
    workshop.participants.append(
        WorkshopParticipantModel(user=participant.userId, status=status)
    )

    # Persist in DB
    participant.save()
    workshop.save()

    return schema.dump(participant), 200
Ejemplo n.º 8
0
 def get(self, _id: str):
     user = UserModel.get_user_by_id(_id)
     if user:
         user_schema = UserSchema()
         result: dict = user_schema.dump(user)
         return result, 200
     return {"msg": "User Not found"}, 404
Ejemplo n.º 9
0
def test_create_admin(cli_runner, db, request):
    first_name = "admin first name"
    last_name = "admin last name"
    email = "*****@*****.**"
    password = "******"

    input_stream = ""
    input_stream += first_name + "\n"  # First name
    input_stream += last_name + "\n"  # Last name
    input_stream += email + "\n"  # Email
    input_stream += password + "\n"  # Password
    input_stream += password + "\n"  # Password confirmation

    cli_runner.invoke(create_admin, input=input_stream)

    user = UserModel.find_by_email("*****@*****.**")

    assert user is not None
    assert user.firstName == first_name
    assert user.lastName == last_name
    assert check_password_hash(pwhash=user.password, password=password)

    def teardown():
        user.delete()

    request.addfinalizer(teardown)
Ejemplo n.º 10
0
def current_user_route():
    """
    look up user information in the database
    """
    user = UserModel.find_user(g.current_user)

    return jsonify(user)
Ejemplo n.º 11
0
    def signup(self):
        from werkzeug.security import generate_password_hash

        pprint("Auth.singup()")
        signupform = LoginForm()
        context = {"signupform": signupform}

        if signupform.validate_on_submit():
            username = signupform.username.data
            password = signupform.password.data

            userdoc = FirestoreService().get_user(username)

            if userdoc.to_dict() is None:
                passwordhash = generate_password_hash(password)
                userdata = UserData(username, passwordhash)
                FirestoreService().user_put(userdata)
                user = UserModel(userdata)
                login_user(user)
                self.set_msg_succes("Bienvenido")
                return self.redirect("todo_list")
            else:
                self.set_msg_error("El usuario ya existe")

        return self.render("signup.html", **context)
Ejemplo n.º 12
0
    def post(self):
        username = request.form.get('username', None)
        password = request.form.get('password', None)
        email = request.form.get('email', None)

        validation = Validation()

        validation.add_rule('User Name', username, 'required|min_length=2')
        validation.add_rule('Password', password, 'required|min_length=5')
        validation.add_rule('Email', email, 'required|is_email')

        if validation.check():
            is_email = UserModel.query \
                .filter(UserModel.email == email) \
                .count()

            if not is_email:
                user = UserModel(username=username,
                                 password=generate_password_hash(password),
                                 email=email)
                db.session.add(user)
                db.session.commit()

                return None, status.HTTP_201_CREATED
            else:
                return 'Email already exists.', status.HTTP_400_BAD_REQUEST

        return validation.error, status.HTTP_400_BAD_REQUEST
Ejemplo n.º 13
0
def login():
    if (not request.json or not 'email' in request.json
            or not 'password' in request.json):
        return jsonify({"message": "wrong params"})
    data = request.get_json() or {}
    validate = ValidateInput.validate_login_input()
    if not validate(data):
        return make_response("\n Email*"
                             "\n\t\t\t\t- Required"
                             "\n\t\t\t\t- Must begin with any character"
                             "\n\t\t\t\t- Must be a valid mail"
                             "\n Password* "
                             "\n\t\t\t\t- Required"
                             "\n\t\t\t\t- Must be a string "
                             "\n\t\t\t\t- Minlength : 5 characters"
                             "\n\t\t\t\t- Must begin with a character"), 422
    user = UserModel.check_if_is_valid_user(data['email'])

    if not user:
        return make_response('could not verify the user'), 401

    if not check_password_hash(user[3], data['password']):
        return jsonify({"message": "Wrong password"}), 422

    return jsonify({
        'id': user[0],
        'name': user[1],
        'email': user[2],
        'password': user[3],
        'message': "Login successful",
        "token": generate_token(user[0]),
    }), 200
Ejemplo n.º 14
0
def participant(db, request):
    participant = UserModel(
        email="*****@*****.**",
        firstName="participant_first_name_1",
        lastName="participant_last_name_1",
        role=[Roles.PARTICIPANT.value],
    )

    participant.save()

    # Delete participant at the end
    def teardown():
        participant.delete()

    request.addfinalizer(teardown)
    return participant
Ejemplo n.º 15
0
    def find_all_users() -> list:
        users = UserModel.get_all_users()

        for user in users:
            user.pop("password")

        return users
Ejemplo n.º 16
0
 def get(self, user_id: str):
     user = UserModel.get_user_by_id(user_id)
     if user:
         schema = OrderSchema(many=True)
         orders: List[OrderModel] = OrderModel.get_orders_by_user(user)
         result = schema.dump(orders)
         return result, 200
     return {"msg": "No user found"}, 404
Ejemplo n.º 17
0
def get_coach(coach_id) -> (dict, int):
    coach = UserModel.find_coach_by_id(user_id=coach_id)

    # Check if given coach_id exists in DB
    if coach is None:
        raise EntityNotFoundError

    return CoachSchema().dump(coach), 200
Ejemplo n.º 18
0
def register():
    session = current_app.db.session

    res = request.get_json()
    nickname = res.get("nickname")
    first_name = res.get("first_name")
    last_name = res.get("last_name")
    biography = res.get("biography")
    created_at = res.get("created_at")
    email = res.get("email")
    password = res.get("password")

    verify_user: UserModel = UserModel.query.filter_by(email=email).first()

    if verify_user:
        return {"error": f"{email} already exists"}, HTTPStatus.FORBIDDEN

    new_user = UserModel(
        nickname=nickname,
        email=email,
        first_name=first_name,
        last_name=last_name,
        biography=biography,
        created_at=created_at,
    )
    new_user.password = password
    session.add(new_user)

    session.commit()

    access_token = create_access_token(
        identity=new_user.id, expires_delta=timedelta(days=7)
    )

    return {
        "user": {
            "email": new_user.email,
            "nickname": new_user.nickname,
            "first_name": new_user.first_name,
            "last_name": new_user.last_name,
            "biography": new_user.biography,
            "created_at": new_user.created_at,
            "access_token": access_token,
        }
    }, HTTPStatus.CREATED
Ejemplo n.º 19
0
 def post(self):
     requested_data = request.get_json()
     user = UserModel.get_user_by_username(requested_data["username"])
     if user:
         if compare_digest(requested_data["password"], user.password):
             return {"msg": "Login successful"}, 200
         else:
             return {"msg": "Bad username or password"}, 400
     return {"msg": "Invalid username or password"}, 400
Ejemplo n.º 20
0
def coach(db, request):
    coach = UserModel(
        firstName="coach_first_name",
        lastName="coach_last_name",
        email="*****@*****.**",
        password=generate_password_hash("password"),
        role=[Roles.COACH.value],
        city=Cities.PARIS.value,
    )

    coach.save()

    # Delete coach at the end
    def teardown():
        coach.delete()

    request.addfinalizer(teardown)
    return coach
Ejemplo n.º 21
0
def get_coach_action_card_batches(coach_id: str) -> (dict, int):
    # Check if given coach_id exists in DB
    coach = UserModel.find_coach_by_id(user_id=coach_id)
    if coach is None:
        raise EntityNotFoundError

    # Retrieve data
    data = ActionCardBatchModel.find_action_card_batches_by_coach(coach_id)
    return ActionCardBatchSchema(many=True).dump(data), 200
Ejemplo n.º 22
0
    def register_user(name: str, email: str, password: str, age: int) -> dict:
        user_id = UserModel.id_generator()

        new_user = {
            "id": user_id,
            "name": name,
            "email": email,
            "password": password,
            "age": age
        }

        if UserModel.check_user(email):
            return None

        UserModel.register_user(new_user)

        new_user.pop("password")

        return new_user
Ejemplo n.º 23
0
 def post(self):
     headers = request.headers
     requested_data = request.get_json()
     user = UserModel.get_user_by_id(headers["User"])
     if user:
         sketch = SketchModel.get_sketch_by_id(requested_data["sketch"])
         if sketch:
             OrderModel.create_order(user, sketch)
             return {"msg": "Order created"}, 201
         return {"msg": "Sketch not found"}, 404
     return {"msg": "User not found"}, 404
Ejemplo n.º 24
0
def delete_coach(coach_id: str) -> (dict, int):
    coach = UserModel.find_coach_by_id(user_id=coach_id)

    # Check if given coach_id exists in DB
    if coach is None:
        raise EntityNotFoundError

    # Delete user in DB
    coach.delete()

    return {}, 204
Ejemplo n.º 25
0
def update_coach_action_card_batches(coach_id: str,
                                     data: bytes) -> (dict, int):
    # Check if given coach_id exists in DB
    coach = UserModel.find_coach_by_id(user_id=coach_id)
    if coach is None:
        raise EntityNotFoundError(msg="Coach does not exist")

    # Prevent another coach from updating another coach action card batches
    if coach_id != get_jwt_identity():
        raise PermissionDeniedError(
            msg="You can't update the action card batches of another coach !")

    # Validate and serialize data
    schema = ActionCardBatchSchema(many=True)
    data, err_msg, err_code = schema.loads_or_400(data)
    if err_msg:
        return err_msg, err_code

    # Retrieve current action card batches
    current_action_card_batches = {
        o.actionCardBatchId: o
        for o in ActionCardBatchModel.find_action_card_batches_by_coach(
            coach_id)
    }

    # Process provided data
    output = []
    for d in data:
        if ("actionCardBatchId" in d
                and d["actionCardBatchId"] in current_action_card_batches):
            # Update action card batch if already existing
            action_card_batch = current_action_card_batches[
                d["actionCardBatchId"]]
            for k, v in d.items():
                setattr(action_card_batch, k, v)
            action_card_batch.updatedAt = datetime.utcnow()
        else:
            # Create new object otherwise
            action_card_batch = ActionCardBatchModel(
                **{k: v
                   for k, v in d.items() if k != "actionCardId"})

        action_card_batch.coachId = coach_id
        action_card_batch.save()
        output.append(action_card_batch)

    new_ids = {o.id: None for o in output}
    # Delete current action card batches that are not in provided data
    for o_id, action_card_batch in current_action_card_batches.items():
        if o_id not in new_ids:
            action_card_batch.delete()

    return ActionCardBatchSchema(many=True).dump(output), 200
Ejemplo n.º 26
0
async def post_user_service(user_data: UserModel):
    new_user = await save_user_repository(user_data.dict())

    if new_user:
        return UserResponse(
            data=[new_user],
            message="User added successfully.",
        )
    return UserErrorResponse(
        error="An error occurred",
        message="Repeated ID.",
    )
Ejemplo n.º 27
0
    def login_user(email: str, password: str) -> dict:
        users = UserModel.get_all_users()

        for user in users:
            print(user)
            print(email, user["email"], email == user["email"])
            print(password, user["password"], password == user["password"])
            if user["email"] == email and user["password"] == password:
                user.pop("password")
                return user

        return None
Ejemplo n.º 28
0
def test_reset_password(client, coach):
    data = {"password": "******"}

    token = coach.send_reset_password_mail()

    response = client.post(
        "/api/v1/reset_password",
        data=json.dumps(data),
        query_string={"access_token": token},
    )
    coach = UserModel.find_by_id(user_id=coach.id)
    assert response.status_code == 204
    assert check_password_hash(pwhash=coach.password, password="******")
Ejemplo n.º 29
0
def create_user():
    session = current_app.db.session

    body = request.get_json()
    username = body.get("username")
    email = body.get("email")
    password = body.get("password")

    user_existence = UserModel.query.filter_by(email=email).first()

    if user_existence != None:
        return {"msg": "User already exists!"}, HTTPStatus.UNPROCESSABLE_ENTITY

    new_user = UserModel(username=username, email=email)
    new_user.password = password

    user_schema = UserSchema()

    session.add(new_user)
    session.commit()

    return user_schema.dump(new_user), HTTPStatus.CREATED
Ejemplo n.º 30
0
def admin(db, request):
    """
    Create an admin for the scope of a function
    Remove it at the end
    """
    admin = UserModel(
        firstName="admin_first_name",
        lastName="admin_last_name",
        email="*****@*****.**",
        password=generate_password_hash("password"),
        role=[Roles.ADMIN.value, Roles.COACH.value],
        city=Cities.PARIS.value,
    )

    admin.save()

    # Delete admin at the end
    def teardown():
        admin.delete()

    request.addfinalizer(teardown)
    return admin