Example #1
0
    def login(self):
        self.csrf_valid()

        try:
            schema = s.UserSchema.create_schema(self.request)
            deserialized = schema.deserialize(self.cstruct)

            headers = remember(self.request, deserialized['email'])
            token = self.request.session.new_csrf_token()

            response = HTTPSeeOther(location=self.request.route_url(
                'main', traverse='user'),
                                    headers=headers)
            response.set_cookie('CSRF-Token',
                                token,
                                max_age=864000,
                                overwrite=True)

            return response
        except colander.Invalid as e:
            self.request.response.status = 422

            form_error = None
            field_errors = e.asdict()

            if 'email' in field_errors and 'password' in field_errors:
                if field_errors['email'] == field_errors['password']:
                    form_error = "Username or password is incorrect."

            return {
                'errors': field_errors,
                'form_error': form_error,
            }
Example #2
0
    def login(self):
        self.csrf_valid()

        try:
            schema = s.UserSchema.create_schema(self.request)
            deserialized = schema.deserialize(self.cstruct)

            headers = remember(self.request, deserialized['email'])
            token = self.request.session.new_csrf_token()

            response = HTTPSeeOther(location=self.request.route_url('main', traverse='user'), headers=headers)
            response.set_cookie('CSRF-Token', token, max_age=864000, overwrite=True)

            return response
        except colander.Invalid as e:
            self.request.response.status = 422

            form_error = None
            field_errors = e.asdict()

            if 'email' in field_errors and 'password' in field_errors:
                if field_errors['email'] == field_errors['password']:
                    form_error = "Username or password is incorrect."

            return {
                    'errors': field_errors,
                    'form_error': form_error,
                    }
Example #3
0
def login(request, redirect_field_name=REDIRECT_FIELD_NAME, _form_class=LoginForm):
    # TODO: Logging in should reset request.user
    # TODO: Configure the login view as the default view for not having
    #       permission to view something.
    if request.authenticated_userid is not None:
        return HTTPSeeOther(request.route_path("manage.projects"))

    user_service = request.find_service(IUserService, context=None)
    breach_service = request.find_service(IPasswordBreachedService, context=None)

    redirect_to = request.POST.get(
        redirect_field_name, request.GET.get(redirect_field_name)
    )

    form = _form_class(
        request.POST,
        request=request,
        user_service=user_service,
        breach_service=breach_service,
        check_password_metrics_tags=["method:auth", "auth_method:login_form"],
    )

    if request.method == "POST":
        if form.validate():
            # Get the user id for the given username.
            username = form.username.data
            userid = user_service.find_userid(username)

            # If the user-originating redirection url is not safe, then
            # redirect to the index instead.
            if not redirect_to or not is_safe_url(url=redirect_to, host=request.host):
                redirect_to = request.route_path("manage.projects")

            # Actually perform the login routine for our user.
            headers = _login_user(request, userid)

            # Now that we're logged in we'll want to redirect the user to
            # either where they were trying to go originally, or to the default
            # view.
            resp = HTTPSeeOther(redirect_to, headers=dict(headers))

            # We'll use this cookie so that client side javascript can
            # Determine the actual user ID (not username, user ID). This is
            # *not* a security sensitive context and it *MUST* not be used
            # where security matters.
            #
            # We'll also hash this value just to avoid leaking the actual User
            # IDs here, even though it really shouldn't matter.
            resp.set_cookie(
                USER_ID_INSECURE_COOKIE,
                hashlib.blake2b(str(userid).encode("ascii"), person=b"warehouse.userid")
                .hexdigest()
                .lower(),
            )
            return resp

    return {
        "form": form,
        "redirect": {"field": REDIRECT_FIELD_NAME, "data": redirect_to},
    }
Example #4
0
def login(request, redirect_field_name=REDIRECT_FIELD_NAME, _form_class=LoginForm):
    # TODO: Logging in should reset request.user
    # TODO: Configure the login view as the default view for not having
    #       permission to view something.
    if request.authenticated_userid is not None:
        return HTTPSeeOther(request.route_path("manage.projects"))

    user_service = request.find_service(IUserService, context=None)
    breach_service = request.find_service(IPasswordBreachedService, context=None)

    redirect_to = request.POST.get(
        redirect_field_name, request.GET.get(redirect_field_name)
    )

    form = _form_class(
        request.POST,
        request=request,
        user_service=user_service,
        breach_service=breach_service,
        check_password_metrics_tags=["method:auth", "auth_method:login_form"],
    )

    if request.method == "POST":
        if form.validate():
            # Get the user id for the given username.
            username = form.username.data
            userid = user_service.find_userid(username)

            # If the user-originating redirection url is not safe, then
            # redirect to the index instead.
            if not redirect_to or not is_safe_url(url=redirect_to, host=request.host):
                redirect_to = request.route_path("manage.projects")

            # Actually perform the login routine for our user.
            headers = _login_user(request, userid)

            # Now that we're logged in we'll want to redirect the user to
            # either where they were trying to go originally, or to the default
            # view.
            resp = HTTPSeeOther(redirect_to, headers=dict(headers))

            # We'll use this cookie so that client side javascript can
            # Determine the actual user ID (not username, user ID). This is
            # *not* a security sensitive context and it *MUST* not be used
            # where security matters.
            #
            # We'll also hash this value just to avoid leaking the actual User
            # IDs here, even though it really shouldn't matter.
            resp.set_cookie(
                USER_ID_INSECURE_COOKIE,
                hashlib.blake2b(str(userid).encode("ascii"), person=b"warehouse.userid")
                .hexdigest()
                .lower(),
            )
            return resp

    return {
        "form": form,
        "redirect": {"field": REDIRECT_FIELD_NAME, "data": redirect_to},
    }
Example #5
0
def two_factor_and_totp_validate(request, _form_class=TOTPAuthenticationForm):
    if request.authenticated_userid is not None:
        return HTTPSeeOther(request.route_path("manage.projects"))

    try:
        two_factor_data = _get_two_factor_data(request)
    except TokenException:
        request.session.flash(
            request._("Invalid or expired two factor login."), queue="error")
        return HTTPSeeOther(request.route_path("accounts.login"))

    userid = two_factor_data.get("userid")
    redirect_to = two_factor_data.get("redirect_to")

    user_service = request.find_service(IUserService, context=None)

    two_factor_state = {}
    if user_service.has_totp(userid):
        two_factor_state["totp_form"] = _form_class(
            request.POST,
            request=request,
            user_id=userid,
            user_service=user_service,
            check_password_metrics_tags=[
                "method:auth", "auth_method:login_form"
            ],
        )
    if user_service.has_webauthn(userid):
        two_factor_state["has_webauthn"] = True
    if user_service.has_recovery_codes(userid):
        two_factor_state["has_recovery_codes"] = True

    if request.method == "POST":
        form = two_factor_state["totp_form"]
        if form.validate():
            _login_user(request,
                        userid,
                        two_factor_method="totp",
                        two_factor_label="totp")
            user_service.update_user(userid,
                                     last_totp_value=form.totp_value.data)

            resp = HTTPSeeOther(redirect_to)
            resp.set_cookie(
                USER_ID_INSECURE_COOKIE,
                hashlib.blake2b(
                    str(userid).encode("ascii"),
                    person=b"warehouse.userid").hexdigest().lower(),
            )

            if not two_factor_state.get("has_recovery_codes", False):
                send_recovery_code_reminder_email(request, request.user)

            return resp
        else:
            form.totp_value.data = ""

    return two_factor_state
Example #6
0
def change_language(request):
    lang = request.matchdict.get('lang')
    resp = HTTPSeeOther(request.application_url)

    if lang is None:
        resp.unset_cookie('_LOCALE_')
    else:
        resp.set_cookie('_LOCALE_', lang, max_age=timedelta(days=365))  # max_age = year

    return resp
Example #7
0
def login(request,
          redirect_field_name=REDIRECT_FIELD_NAME,
          _form_class=forms.LoginForm):
    # TODO: Logging in should reset request.user
    # TODO: Configure the login view as the default view for not having
    #       permission to view something.

    user_service = request.find_service(IUserService, context=None)

    redirect_to = request.POST.get(redirect_field_name,
                                   request.GET.get(redirect_field_name))

    form = _form_class(request.POST, user_service=user_service)

    if request.method == "POST" and form.validate():
        # Get the user id for the given username.
        username = form.username.data
        userid = user_service.find_userid(username)

        # If the user-originating redirection url is not safe, then redirect to
        # the index instead.
        if (not redirect_to
                or not is_safe_url(url=redirect_to, host=request.host)):
            redirect_to = "/"

        # Actually perform the login routine for our user.
        headers = _login_user(request, userid)

        # Now that we're logged in we'll want to redirect the user to either
        # where they were trying to go originally, or to the default view.
        resp = HTTPSeeOther(redirect_to, headers=dict(headers))

        # We'll use this cookie so that client side javascript can Determine
        # the actual user ID (not username, user ID). This is *not* a security
        # sensitive context and it *MUST* not be used where security matters.
        #
        # We'll also hash this value just to avoid leaking the actual User IDs
        # here, even though it really shouldn't matter.
        resp.set_cookie(
            USER_ID_INSECURE_COOKIE,
            blake2b(
                str(userid).encode("ascii"),
                person=b"warehouse.userid",
            ).hexdigest().lower(),
        )

        return resp

    return {
        "form": form,
        "redirect": {
            "field": REDIRECT_FIELD_NAME,
            "data": redirect_to,
        },
    }
Example #8
0
def login(request, redirect_field_name=REDIRECT_FIELD_NAME,
          _form_class=forms.LoginForm):
    # TODO: Logging in should reset request.user
    # TODO: Configure the login view as the default view for not having
    #       permission to view something.

    user_service = request.find_service(IUserService, context=None)

    redirect_to = request.POST.get(redirect_field_name,
                                   request.GET.get(redirect_field_name))

    form = _form_class(request.POST, user_service=user_service)

    if request.method == "POST" and form.validate():
        # Get the user id for the given username.
        username = form.username.data
        userid = user_service.find_userid(username)

        # If the user-originating redirection url is not safe, then redirect to
        # the index instead.
        if (not redirect_to or
                not is_safe_url(url=redirect_to, host=request.host)):
            redirect_to = "/"

        # Actually perform the login routine for our user.
        headers = _login_user(request, userid)

        # Now that we're logged in we'll want to redirect the user to either
        # where they were trying to go originally, or to the default view.
        resp = HTTPSeeOther(redirect_to, headers=dict(headers))

        # We'll use this cookie so that client side javascript can Determine
        # the actual user ID (not username, user ID). This is *not* a security
        # sensitive context and it *MUST* not be used where security matters.
        #
        # We'll also hash this value just to avoid leaking the actual User IDs
        # here, even though it really shouldn't matter.
        resp.set_cookie(
            USER_ID_INSECURE_COOKIE,
            blake2b(
                str(userid).encode("ascii"),
                person=b"warehouse.userid",
            ).hexdigest().lower(),
        )

        return resp

    return {
        "form": form,
        "redirect": {
            "field": REDIRECT_FIELD_NAME,
            "data": redirect_to,
        },
    }
Example #9
0
def set_color_theme(request):
    cookie_name = 'color_theme'
    current = request.cookies.get(cookie_name, 'default')
    new_theme = request.POST.get('color_theme')
    response = HTTPSeeOther(request.route_url('preferences'))
    if new_theme and new_theme != current:
        cookie_path = '/'  # FIXME: not necessarily
        if new_theme == 'default':
            response.delete_cookie(cookie_name, path=cookie_path)
        else:
            response.set_cookie(cookie_name, new_theme, path=cookie_path)
    return response
Example #10
0
def locale(request):
    form = SetLocaleForm(**request.GET)

    redirect_to = request.referer
    if not is_safe_url(redirect_to, host=request.host):
        redirect_to = request.route_path("index")
    resp = HTTPSeeOther(redirect_to)

    if form.validate():
        request.session.flash("Locale updated", queue="success")
        resp.set_cookie(LOCALE_ATTR, form.locale_id.data)

    return resp
Example #11
0
def two_factor(request, _form_class=TwoFactorForm):
    if request.authenticated_userid is not None:
        return HTTPSeeOther(request.route_path("manage.projects"))

    token_service = request.find_service(ITokenService, name="two_factor")

    try:
        two_factor_data = token_service.loads(request.query_string)
    except TokenException:
        request.session.flash("Invalid or expired two factor login.",
                              queue="error")
        return HTTPSeeOther(request.route_path("accounts.login"))

    userid = two_factor_data.get("userid")
    if not userid:
        return HTTPSeeOther(request.route_path("accounts.login"))

    redirect_to = two_factor_data.get("redirect_to")

    user_service = request.find_service(IUserService, context=None)

    form = _form_class(
        request.POST,
        user_id=userid,
        user_service=user_service,
        check_password_metrics_tags=["method:auth", "auth_method:login_form"],
    )

    if request.method == "POST":
        if form.validate():
            # If the user-originating redirection url is not safe, then
            # redirect to the index instead.
            if not redirect_to or not is_safe_url(url=redirect_to,
                                                  host=request.host):
                redirect_to = request.route_path("manage.projects")

            _login_user(request, userid)

            resp = HTTPSeeOther(redirect_to)
            resp.set_cookie(
                USER_ID_INSECURE_COOKIE,
                hashlib.blake2b(
                    str(userid).encode("ascii"),
                    person=b"warehouse.userid").hexdigest().lower(),
            )

            return resp
        else:
            form.totp_value.data = ""

    return {"form": form}
Example #12
0
def recovery_code(request, _form_class=RecoveryCodeAuthenticationForm):
    if request.authenticated_userid is not None:
        return HTTPSeeOther(request.route_path("manage.projects"))

    try:
        two_factor_data = _get_two_factor_data(request)
    except TokenException:
        request.session.flash(
            request._("Invalid or expired two factor login."), queue="error"
        )
        return HTTPSeeOther(request.route_path("accounts.login"))

    userid = two_factor_data.get("userid")

    user_service = request.find_service(IUserService, context=None)

    form = _form_class(
        request.POST, request=request, user_id=userid, user_service=user_service
    )

    if request.method == "POST":
        if form.validate():
            _login_user(request, userid, two_factor_method="recovery-code")

            resp = HTTPSeeOther(request.route_path("manage.account"))
            resp.set_cookie(
                USER_ID_INSECURE_COOKIE,
                hashlib.blake2b(str(userid).encode("ascii"), person=b"warehouse.userid")
                .hexdigest()
                .lower(),
            )

            user_service.record_event(
                userid,
                tag="account:recovery_codes:used",
                ip_address=request.remote_addr,
            )

            request.session.flash(
                request._(
                    "Recovery code accepted. The supplied code cannot be used again."
                ),
                queue="success",
            )

            return resp
        else:
            form.recovery_code_value.data = ""

    return {"form": form}
Example #13
0
def two_factor(request, _form_class=TwoFactorForm):
    if request.authenticated_userid is not None:
        return HTTPSeeOther(request.route_path("manage.projects"))

    token_service = request.find_service(ITokenService, name="two_factor")

    try:
        two_factor_data = token_service.loads(request.query_string)
    except TokenException:
        request.session.flash("Invalid or expired two factor login.", queue="error")
        return HTTPSeeOther(request.route_path("accounts.login"))

    userid = two_factor_data.get("userid")
    if not userid:
        return HTTPSeeOther(request.route_path("accounts.login"))

    redirect_to = two_factor_data.get("redirect_to")

    user_service = request.find_service(IUserService, context=None)

    form = _form_class(
        request.POST,
        user_id=userid,
        user_service=user_service,
        check_password_metrics_tags=["method:auth", "auth_method:login_form"],
    )

    if request.method == "POST":
        if form.validate():
            # If the user-originating redirection url is not safe, then
            # redirect to the index instead.
            if not redirect_to or not is_safe_url(url=redirect_to, host=request.host):
                redirect_to = request.route_path("manage.projects")

            _login_user(request, userid)

            resp = HTTPSeeOther(redirect_to)
            resp.set_cookie(
                USER_ID_INSECURE_COOKIE,
                hashlib.blake2b(str(userid).encode("ascii"), person=b"warehouse.userid")
                .hexdigest()
                .lower(),
            )

            return resp

    return {"form": form}
Example #14
0
def locale(request):
    form = SetLocaleForm(**request.GET)

    redirect_to = request.referer
    if not is_safe_url(redirect_to, host=request.host):
        redirect_to = request.route_path("index")
    resp = HTTPSeeOther(redirect_to)

    if form.validate():
        # Build a localizer for the locale we're about to switch to. This will
        # happen automatically once the cookie is set, but if we want the flash
        # message indicating success to be in the new language as well, we need
        # to do it here.
        tdirs = request.registry.queryUtility(ITranslationDirectories)
        _ = make_localizer(form.locale_id.data, tdirs).translate
        request.session.flash(_("Locale updated"), queue="success")
        resp.set_cookie(LOCALE_ATTR, form.locale_id.data)

    return resp
Example #15
0
def callback(request):

    log.debug('********* callback **********')
    print_requests(request)

    code = request.params.get('code')

    # userid, name = OAuth(code).get_user_info()
    userid ='lak'
    name = 'test'
    headers = remember(request, userid)
    login_url = request.route_url('login')
    print('login_url - ', login_url)

    response = HTTPSeeOther(location=login_url, headers=headers)
    response.set_cookie('name', name)
    response.set_cookie('userid', userid)

    return response
Example #16
0
def set_lang(request):
    new_lang = request.POST['lang']
    response = HTTPSeeOther(request.route_url('preferences'))
    cookie_path = '/'  # FIXME: not necessarily
    response.set_cookie(LOCALE_COOKIE_NAME, new_lang, path=cookie_path)
    return response