Example #1
0
def choose_register(request):
    """
    Choose register
    """
    login_bg_image_path = get_login_bg_image_path()

    return render(request, 'choose_register.html',
                  {'login_bg_image_path': login_bg_image_path})
Example #2
0
def choose_register(request):
    """
    Choose register
    """
    login_bg_image_path = get_login_bg_image_path()

    return render(request, 'choose_register.html', {
        'enable_weixin': ENABLE_WEIXIN,
        'login_bg_image_path': login_bg_image_path
    })
Example #3
0
def dtable_share_link_view(request, token):
    dsl = DTableShareLinks.objects.filter(token=token).first()
    if not dsl:
        return render_error(request, _('Share link does not exist'))
    if dsl.is_expired():
        return render_error(request, _('Share link has expired'))

    shared_user = email2nickname(dsl.username)
    login_bg_image_path = get_login_bg_image_path()

    if isinstance(request.user, AnonymousUser):
        return render(
            request, 'dtable_share_react.html', {
                'shared_user': shared_user,
                'table_name': dsl.dtable.name,
                'next': '/dtable/links/%s' % dsl.token,
                'login_bg_image_path': login_bg_image_path,
                'powered_by_link': POWERED_BY_LINK
            })

    # resource check
    workspace_id = dsl.dtable.workspace.id
    workspace = Workspaces.objects.get_workspace_by_id(workspace_id)
    if not workspace:
        raise Http404

    name = dsl.dtable.name
    dtable = DTables.objects.get_dtable(workspace, name)
    if not dtable:
        return render_error(request, _('DTable does not exist'))

    current_username = request.user.username
    try:
        if current_username not in list_dtable_related_users(
                workspace, dtable):
            obj = DTableShare.objects.get_by_dtable_and_to_user(
                dtable, current_username)
            if not obj:
                DTableShare.objects.add(dtable, dsl.username, current_username,
                                        dsl.permission)
                share_dtable_to_user.send(sender=None,
                                          table_id=dtable.id,
                                          share_user=dsl.username,
                                          to_user=current_username)
    except Exception as e:
        logger.error(
            'take user: %s to table: %s table-token: %s share-list error: %s',
            current_username, dsl.dtable_id, token, e)
        return render_error(request, _('Internal Server Error.'))

    return HttpResponseRedirect(
        reverse('dtable:dtable_file_view', args=(workspace_id, name)))
Example #4
0
    def get_context_data(self, form, **kwargs):
        """
        Adds user's default and backup OTP devices to the context.
        """
        context = super(TwoFactorVerifyView, self).get_context_data(form, **kwargs)
        if self.steps.current == 'token':
            context['device'] = self.get_device()
            device = StaticDevice.objects.device_for_user(self.user.username)
            context['backup_tokens'] = device.token_set.count() if device else 0

        context['cancel_url'] = settings.LOGOUT_URL
        context['form_prefix'] = '%s-' % self.steps.current
        login_bg_image_path = get_login_bg_image_path()
        context['login_bg_image_path'] = login_bg_image_path
        context['remember_days'] = settings.TWO_FACTOR_DEVICE_REMEMBER_DAYS

        return context
Example #5
0
def register(request, backend, success_url=None, form_class=None,
             disallowed_url='registration_disallowed',
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register an account.

    The actual registration of the account will be delegated to the
    backend specified by the ``backend`` keyword argument (see below);
    it will be used as follows:

    1. The backend's ``registration_allowed()`` method will be called,
       passing the ``HttpRequest``, to determine whether registration
       of an account is to be allowed; if not, a redirect is issued to
       the view corresponding to the named URL pattern
       ``registration_disallowed``. To override this, see the list of
       optional arguments for this view (below).

    2. The form to use for account registration will be obtained by
       calling the backend's ``get_form_class()`` method, passing the
       ``HttpRequest``. To override this, see the list of optional
       arguments for this view (below).

    3. If valid, the form's ``cleaned_data`` will be passed (as
       keyword arguments, and along with the ``HttpRequest``) to the
       backend's ``register()`` method, which should return the new
       ``User`` object.

    4. Upon successful registration, the backend's
       ``post_registration_redirect()`` method will be called, passing
       the ``HttpRequest`` and the new ``User``, to determine the URL
       to redirect the user to. To override this, see the list of
       optional arguments for this view (below).

    **Required arguments**

    None.

    **Optional arguments**

    ``backend``
        The dotted Python import path to the backend class to use.

    ``disallowed_url``
        URL to redirect to if registration is not permitted for the
        current ``HttpRequest``. Must be a value which can legally be
        passed to ``django.shortcuts.redirect``. If not supplied, this
        will be whatever URL corresponds to the named URL pattern
        ``registration_disallowed``.

    ``form_class``
        The form class to use for registration. If not supplied, this
        will be retrieved from the registration backend.

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``success_url``
        URL to redirect to after successful registration. Must be a
        value which can legally be passed to
        ``django.shortcuts.redirect``. If not supplied, this will be
        retrieved from the registration backend.

    ``template_name``
        A custom template to use. If not supplied, this will default
        to ``registration/registration_form.html``.

    **Context:**

    ``form``
        The registration form.

    Any extra variables supplied in the ``extra_context`` argument
    (see above).

    **Template:**

    registration/registration_form.html or ``template_name`` keyword
    argument.

    """
    if not config.ENABLE_SIGNUP:
        raise Http404

    if config.ACTIVATE_AFTER_REGISTRATION:
        success_url = settings.SITE_ROOT

    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)
    if form_class is None:
        form_class = backend.get_form_class(request)

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            new_user = backend.register(request, **form.cleaned_data)
            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
    else:
        userid = request.GET.get('userid', '')
        form = form_class(initial={'userid': userid })

    if extra_context is None:
        extra_context = {}
    from django.template import RequestContext
    context = {}
    for key, value in list(extra_context.items()):
        context[key] = callable(value) and value() or value

    src = request.GET.get('src', '')
    if src:
        form = form_class(initial={'email': src})

    context['form'] = form
    context['min_len'] = config.USER_PASSWORD_MIN_LENGTH
    context['strong_pwd_required'] = config.USER_STRONG_PASSWORD_REQUIRED
    context['level'] = config.USER_PASSWORD_STRENGTH_LEVEL

    login_bg_image_path = get_login_bg_image_path()
    context['login_bg_image_path'] = login_bg_image_path

    return render(request, template_name, context)
Example #6
0
def org_register(request, redirect_field_name=REDIRECT_FIELD_NAME):
    """Allow a new user to register an organization account. A new
    organization will be created associate with that user.

    Arguments:
    - `request`:
    """
    login_bg_image_path = get_login_bg_image_path()
    redirect_to = request.GET.get(redirect_field_name)

    if request.method == 'POST':
        form = OrgRegistrationForm(request.POST)

        if ORG_AUTO_URL_PREFIX:
            # generate url prefix automatically
            url_prefix = gen_org_url_prefix(3)
            if url_prefix is None:
                messages.error(request, "Failed to create organization account, please try again later.")
                return render(request, 'organizations/org_register.html', {
                    'form': form,
                    'login_bg_image_path': login_bg_image_path,
                    'org_auto_url_prefix': ORG_AUTO_URL_PREFIX,
                })

        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password1']
            org_name = form.cleaned_data['org_name']

            new_user = User.objects.create_user(email, password,
                                                is_staff=False, is_active=True)
            create_org(org_name, url_prefix, new_user.username)
            new_org = get_org_by_url_prefix(url_prefix)
            org_created.send(sender=None, org=new_org)

            if name:
                Profile.objects.add_or_update(new_user.username, name)

            # login the user
            new_user.backend = settings.AUTHENTICATION_BACKENDS[0]
            login(request, new_user)

            if not redirect_to:
                return HttpResponseRedirect(reverse('dtable'))
            else:
                return HttpResponseRedirect(redirect_to)
    else:
        form = OrgRegistrationForm()

    service_url = get_service_url()
    up = urlparse(service_url)
    service_url_scheme = up.scheme
    service_url_remaining = up.netloc + up.path

    return render(request, 'organizations/org_register.html', {
        'form': form,
        'login_bg_image_path': login_bg_image_path,
        'service_url_scheme': service_url_scheme,
        'service_url_remaining': service_url_remaining,
        'org_auto_url_prefix': ORG_AUTO_URL_PREFIX,
        'redirect_to': redirect_to or reverse('dtable'),
    })
Example #7
0
def login(request,
          template_name='registration/login.html',
          redirect_if_logged_in=None,
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm):
    """Displays the login form and handles the login action."""

    if request.user.is_authenticated() and redirect_if_logged_in:
        return HttpResponseRedirect(reverse(redirect_if_logged_in))

    redirect_to = request.GET.get(redirect_field_name, '')
    ip = get_remote_ip(request)

    if request.method == "POST":
        login = request.POST.get('login', '').strip()
        failed_attempt = get_login_failed_attempts(username=login, ip=ip)
        remember_me = True if request.POST.get('remember_me',
                                               '') == 'on' else False
        redirect_to = request.POST.get(redirect_field_name, '') or redirect_to

        # check the form
        used_captcha_already = False
        if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
            form = authentication_form(data=request.POST)
        else:
            if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
                form = CaptchaAuthenticationForm(data=request.POST)
                used_captcha_already = True
            else:
                form = authentication_form(data=request.POST)

        if form.is_valid():
            return _handle_login_form_valid(request, form.get_user(),
                                            redirect_to, remember_me)

        # form is invalid
        user_logged_in_failed.send(sender=None, request=request)
        failed_attempt = incr_login_failed_attempts(username=login, ip=ip)

        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                # log user in if password is valid otherwise freeze account
                logger.warn(
                    'Login attempt limit reached, try freeze the user, email/username: %s, ip: %s, attemps: %d'
                    % (login, ip, failed_attempt))
                email = Profile.objects.get_username_by_login_id(login)
                if email is None:
                    email = login
                try:
                    user = User.objects.get(email)
                    if user.is_active:
                        user.freeze_user(notify_admins=True)
                        logger.warn(
                            'Login attempt limit reached, freeze the user email/username: %s, ip: %s, attemps: %d'
                            % (login, ip, failed_attempt))
                except User.DoesNotExist:
                    logger.warn(
                        'Login attempt limit reached with invalid email/username: %s, ip: %s, attemps: %d'
                        % (login, ip, failed_attempt))
                    pass
                form.errors['freeze_account'] = _(
                    'This account has been frozen due to too many failed login attempts.'
                )
            else:
                # use a new form with Captcha
                logger.warn(
                    'Login attempt limit reached, show Captcha, email/username: %s, ip: %s, attemps: %d'
                    % (login, ip, failed_attempt))
                if not used_captcha_already:
                    form = CaptchaAuthenticationForm()

    else:
        ### GET
        failed_attempt = get_login_failed_attempts(ip=ip)
        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                form = authentication_form()
            else:
                logger.warn(
                    'Login attempt limit reached, show Captcha, ip: %s, attempts: %d'
                    % (ip, failed_attempt))
                form = CaptchaAuthenticationForm()
        else:
            form = authentication_form()

    request.session.set_test_cookie()
    current_site = get_current_site(request)

    multi_tenancy = getattr(settings, 'MULTI_TENANCY', False)

    if config.ENABLE_SIGNUP:
        if multi_tenancy:
            org_account_only = getattr(settings, 'FORCE_ORG_REGISTER', False)
            if org_account_only:
                signup_url = reverse('org_register')
            else:
                signup_url = reverse('choose_register')
        else:
            signup_url = reverse('registration_register')
    else:
        signup_url = ''

    enable_sso = getattr(settings, 'ENABLE_SHIB_LOGIN', False) or \
                 getattr(settings, 'ENABLE_KRB5_LOGIN', False) or \
                 getattr(settings, 'ENABLE_ADFS_LOGIN', False) or \
                 getattr(settings, 'ENABLE_OAUTH', False) or \
                 getattr(settings, 'ENABLE_CAS', False)

    login_bg_image_path = get_login_bg_image_path()

    return render(
        request, template_name, {
            'form': form,
            redirect_field_name: redirect_to,
            'site': current_site,
            'site_name': get_site_name(),
            'remember_days': config.LOGIN_REMEMBER_DAYS,
            'signup_url': signup_url,
            'enable_sso': enable_sso,
            'login_bg_image_path': login_bg_image_path,
        })