Example #1
0
    async def post(self):
        """ Check is email unique and create new User """
        cleaned_data = await self._validate()
        email = cleaned_data["email"]
        password_1 = cleaned_data["password_1"]
        password_2 = cleaned_data["password_2"]
        invite_token = cleaned_data.get("token")
        db_objects = self.request.app.objects
        self._password_match(password_1, password_2)

        user_invite = await self._get_user_invite(db_objects, invite_token)
        if not user_invite:
            details = "Invitation link is expired or unavailable"
            logger.error("Couldn't signup user token: %s | details: %s", invite_token, details)
            raise InvalidParameterError(details=details)

        if await db_objects.count(User.select().where(User.email ** email)):
            raise InvalidParameterError(details=f"User with email '{email}' already exists")

        user = await User.async_create(
            db_objects, email=email, password=User.make_password(password_1),
        )
        user_invite.user = user
        user_invite.is_applied = True
        await user_invite.async_update(db_objects)
        await Podcast.create_first_podcast(self.request.app.objects, user.id)
        self._login(user)
        return {"redirect_url": self._get_url("index")}, http.HTTPStatus.OK
    def test_reset_password__ok(self, client, user, mocked_auth_send, dbs):
        request_user = user
        await_(request_user.update(dbs, is_superuser=True))
        target_user = await_(
            User.async_create(dbs,
                              db_commit=True,
                              email=self.email,
                              password="******"))

        client.login(user)
        response = client.post(self.url, json={"email": target_user.email})
        response_data = self.assert_ok_response(response)
        token = response_data.get("token")

        assert response_data["user_id"] == target_user.id
        assert token is not None, response_data
        assert decode_jwt(response_data["token"])["user_id"] == target_user.id

        link = f"{settings.SITE_URL}/change-password/?t={token}"
        expected_body = (
            f"<p>You can reset your password for {settings.SITE_URL}</p>"
            f"<p>Please follow the link </p>"
            f"<p><a href={link}>{link}</a></p>")
        mocked_auth_send.assert_awaited_once_with(
            recipient_email=target_user.email,
            subject=f"Welcome back to {settings.SITE_URL}",
            html_content=expected_body,
        )
Example #3
0
def update_or_create_admin(email, password):
    """ Find existing user or create new user """
    user = User.query.filter(User.email == email).first()
    if not user:
        print(" * [DASPANEL] Creating admin user: "******" * [DASPANEL] Reseting admin user password: " + email)
        user.password = generate_password_hash(password)
        db.session.add(user)
        db.session.flush()

    return user
 def _create_user(self, db_session, is_active=True):
     self.user = await_(
         User.async_create(
             db_session,
             db_commit=True,
             email=self.email,
             password=self.encoded_password,
             is_active=is_active,
         ))
Example #5
0
    async def post(self, request):
        """ Check is email unique and create new User """
        cleaned_data = await self._validate(request)
        user, _, _ = await LoginRequiredAuthBackend(request).authenticate_user(
            jwt_token=cleaned_data["token"],
            token_type=TOKEN_TYPE_RESET_PASSWORD,
        )
        new_password = User.make_password(cleaned_data["password_1"])
        await user.update(self.db_session, password=new_password)

        token_collection = await self._create_session(user)
        return self._response(token_collection)
Example #6
0
    async def post(self):
        """ Check is email unique and create new User """
        cleaned_data = await self._validate()
        password_1 = cleaned_data["password_1"]
        password_2 = cleaned_data["password_2"]
        jwt_token = cleaned_data["token"]
        self._password_match(password_1, password_2)

        user = await self.authenticate_user(self.db_objects, jwt_token)
        user.password = User.make_password(password_1)
        await user.async_update(self.db_objects)
        self._login(user)
        return {"redirect_url": self._get_url("index")}, http.HTTPStatus.OK
    def test_sign_up__ok(self, client, user_invite, dbs):
        request_data = self._sign_up_data(user_invite)
        response = client.post(self.url, json=request_data)
        response_data = self.assert_ok_response(response, status_code=201)

        user = await_(User.async_get(dbs, email=request_data["email"]))
        assert user is not None, f"User wasn't created with {request_data=}"
        assert_tokens(response_data, user)

        await_(dbs.refresh(user_invite))
        assert user_invite.user_id == user.id
        assert user_invite.is_applied
        assert await_(Podcast.async_get(dbs,
                                        created_by_id=user.id)) is not None
Example #8
0
 async def post(self, request):
     cleaned_data = await self._validate(request)
     user_invite: UserInvite = cleaned_data["user_invite"]
     user = await User.async_create(
         self.db_session,
         email=cleaned_data["email"],
         password=User.make_password(cleaned_data["password_1"]),
     )
     await user_invite.update(self.db_session,
                              is_applied=True,
                              user_id=user.id)
     await Podcast.create_first_podcast(self.db_session, user.id)
     token_collection = await self._create_session(user)
     return self._response(token_collection,
                           status_code=status.HTTP_201_CREATED)
Example #9
0
    async def test_check_owners(db_objects, user_data, unauth_client,
                                check_for_owner_urls):
        handlers = {
            "get": unauth_client.get,
            "post": unauth_client.post,
        }
        with db_objects.allow_sync():
            email, password = user_data
            another_user = User.create(email=email, password=password)

        make_cookie(unauth_client, {"user": another_user.id})

        for url in check_for_owner_urls:
            handler = handlers[url.method]
            response = await handler(url.url, allow_redirects=False)
            assert response.status == url.status_code, f"Couldn't get expected response for {url}"
    def test_sign_up__user_already_exists__fail(self, client, user_invite,
                                                dbs):
        request_data = self._sign_up_data(user_invite)
        user_email = request_data["email"]

        await_(
            User.async_create(dbs,
                              db_commit=True,
                              email=user_email,
                              password="******"))
        response = client.post(self.url, json=request_data)
        response_data = self.assert_fail_response(response)
        assert response_data == {
            "error": "Requested data is not valid.",
            "details": f"User with email '{user_email}' already exists",
        }
Example #11
0
def upload_teachers():
    print('Adding Teachers ...')
    with app.app_context():
        for teacher in teachers:
            name = teacher[0]
            email = teacher[1]
            password = teacher[2]
            to_add_teacher = User(name=name, email=email, role='teacher')
            to_add_teacher.set_hash(password)
            to_add_teacher.insert()
            print('[x] Added', teacher)
Example #12
0
def upload_students():
    print('Adding Students ...')
    with app.app_context():
        for student in students:
            name = student[0]
            email = student[1]
            password = student[2]
            to_add_student = User(name=name, email=email, role='student')
            to_add_student.set_hash(password)
            to_add_student.insert()
            print('[x] Added', student)
Example #13
0
    async def test_signin__ok(self, unauth_client, web_app):
        email, password = f"u_{uuid.uuid4().hex}"[:10], "password"

        await web_app.objects.create(User,
                                     email=email,
                                     password=User.make_password(password))
        request_data = {"email": email, "password": password}
        response = await unauth_client.post(self.path,
                                            data=request_data,
                                            allow_redirects=False)
        assert response.status == 302
        location = response.headers["Location"]
        assert str(web_app.router["index"].url_for()), location

        response = await unauth_client.get(location, allow_redirects=False)
        assert response.status == 200
        content = await response.text()
        assert "podcasts" in content
Example #14
0
def add_check(grade_id):
    if request.method == 'POST':
        context = base_context()
        form = AddStudentForm()
        # if form.validate_on_submit():
        if not form.validate_on_submit():
            flash_errors(form)
            return redirect(url_for('student.view', grade_id=grade_id))

        user = User.query.filter(User.email == form.email.data).first()
        if user:
            flash(notify_danger('Mail already exists!'))
            return redirect(url_for('student.index'))
        student = User(name=form.name.data,
                       email=form.email.data,
                       role='student')
        grade = Grade.query.get(grade_id)
        student.grade = grade
        student.set_hash(current_app.config['DEFAULT_PASS_ALL'])
        student.insert()
        flash(notify_success('Added {}!'.format(form.email.data)))
        return redirect(url_for('student.view', grade_id=grade_id))
Example #15
0
def add_check():
    if request.method == 'POST':
        context = base_context()
        form = AddTeacherForm()
        # if form.validate_on_submit():
        if not form.validate_on_submit():
            flash_errors(form)
            return redirect(url_for('teacher.index'))
        user = User.query.filter(User.email == form.email.data).first()
        if user:
            flash(notify_danger('Mail already exists!'))
            return redirect(url_for('teacher.index'))
        teacher = User(name=form.name.data,
                       email=form.email.data,
                       role='teacher')
        teacher.set_hash(current_app.config['DEFAULT_PASS_ALL'])
        teacher.insert()
        flash(notify_success('Added {}!'.format(teacher.name)))
        return redirect(url_for('teacher.index'))
Example #16
0
def add_admin(name, email, password):
    with app.app_context():
        admin = User(name=name, email=email, role='admin')
        admin.set_hash(password)
        admin.insert()
        print('[x] added admin:', name, email, password)
Example #17
0
def user(db_objects):
    with db_objects.allow_sync():
        email, password = get_user_data()
        yield User.create(email=email, password=password)
Example #18
0
def teardown_module(module):
    print(f"module teardown {module}")
    Episode.truncate_table()
    Podcast.truncate_table()
    User.truncate_table()
Example #19
0
#coding: utf8

from modules.auth.models import User, Application, AppUser, db

db.create_all()
apps = [
    Application(nom='Administration'),
    Application(nom='Annuaire'),
    Application(nom='Recrutement')]

user = User(login='******',
        password='******',
        email='*****@*****.**'
        )

rels = [
    AppUser(niveau=6, user=user, application=apps[0]),
    AppUser(niveau=6, user=user, application=apps[1]),
    AppUser(niveau=6, user=user, application=apps[2])]

db.session.add_all(apps)
db.session.add(user)
db.session.add_all(rels)
db.session.commit()
Example #20
0
def create_user(db_session):
    email, password = get_user_data()
    return await_(User.async_create(db_session, db_commit=True, email=email, password=password))
 def setup_class(cls):
     cls.encoded_password = User.make_password(cls.raw_password)