Beispiel #1
0
def activate(request, *args, **kwargs):
    code = request.GET.get('code')
    user_created = request.GET.get('user_created')
    invitation = Invitation.objects.get(code=code)
    user = invitation.invitee.user
    if not user_created:
        auth_logout(request)

    if not invitation.is_activated() and not user_created:
        try:
            usermapping = user.usermapping
        except UserMapping.DoesNotExist:
            redirect = '%s&%s' % (request.build_absolute_uri(), 
                                  'user_created=created')
            param = urllib.urlencode({'action': 'create', 'redirect': redirect})
            return HttpResponseRedirect(
                    '%s/c/portal/sso?%s' % (settings.PARTNER_BASE, param))

    if not request.user.is_authenticated():
        return redirect_to_login(request.build_absolute_uri())

    if request.user != user:
        # TODO: merge user
        pass
    invitation.activate()
    return HttpResponseRedirect('/client/profile.html')
Beispiel #2
0
def _should_abort_user(request, should_redirect):

    # authorize if user is staff
    if request.user.is_staff:
        return False

    # authorize if user is female and not blocked
    not_female = False
    blocked = False
    if hasattr(request.user, 'profile'):
        if request.user.profile.gender == Profile.FEMALE:
            if not request.user.profile.blocked:
                return False
            else:
                blocked = True
        else:
            not_female = True

    auth_logout(request)
    if should_redirect:
        if not_female:
            return redirect(resolve_url('female_only'))
        elif blocked:
            return redirect(resolve_url('blocked'))

    return HttpResponseForbidden()
Beispiel #3
0
def logout(request, next_page=None,
           template_name='registration/logged_out.html',
           redirect_field_name=REDIRECT_FIELD_NAME,
           current_app=None, extra_context=None):
    """
    Logs out the user and displays 'You are logged out' message.
    """
    the_user = request.user
    auth_logout(request)
    user_actions.action_logout(the_user)
    redirect_to = request.REQUEST.get(redirect_field_name, '')
    if redirect_to:
        netloc = urlparse.urlparse(redirect_to)[1]
        # Security check -- don't allow redirection to a different host.
        if not (netloc and netloc != request.get_host()):
            return HttpResponseRedirect(redirect_to)

    if next_page is None:
        current_site = get_current_site(request)
        context = {
            'site': current_site,
            'site_name': current_site.name,
            'title': 'Logged out'
        }
        if extra_context is not None:
            context.update(extra_context)
        return TemplateResponse(request, template_name, context,
                                current_app=current_app)
    else:
        # Redirect to this page until the session has been cleared.
        return HttpResponseRedirect(next_page or request.path)
Beispiel #4
0
def logout(request):
    """
    Log the user out.
    """
    auth_logout(request)
    info(request, _("Successfully logged out"))
    return redirect(next_url(request) or get_script_prefix())
def logout(request, next_page=None,
           template_name='registration/logged_out.html',
           redirect_field_name=REDIRECT_FIELD_NAME,
           current_app=None, extra_context=None):
    """
    Logs out the user and displays 'You are logged out' message.
    """
    auth_logout(request)

    if redirect_field_name in request.REQUEST:
        next_page = request.REQUEST[redirect_field_name]
        # Security check -- don't allow redirection to a different host.
        if not is_safe_url(url=next_page, host=request.get_host()):
            next_page = request.path

    if next_page:
        # Redirect to this page until the session has been cleared.
        return HttpResponseRedirect(next_page)

    current_site = get_current_site(request)
    context = {
        'site': current_site,
        'site_name': current_site.name,
        'title': _('Logged out')
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request, template_name, context,
        current_app=current_app)
Beispiel #6
0
def logout(request):
    """
    Log the user out.
    """
    auth_logout(request)
    info(request, _("Successfully logged out"))
    return redirect(request.GET.get("next", "/"))
Beispiel #7
0
def logout(request):
    """
    Log the user out.
    """
    auth_logout(request)
    info(request, _("Successfully logged out"), fail_silently=True)
    return HttpResponseRedirect(request.GET.get("next", "/"))
Beispiel #8
0
def logout(request):
    # It's safer to handle logout requests as POST
    if request.method == 'POST':
        auth_logout(request)
        return redirect('uploads.views.index')
    else:
        raise Http404
Beispiel #9
0
def verify(request):

    try:
        auth = authenticate(request, settings.SAML_1['URL'])
    except SamlException as e:
        ctx = {'e': e}
        return render_to_response('registration/saml_error.html', ctx)

    if UserProfile.objects.filter(verified_ssn=auth['ssn']).count() > 0:
        taken_user = UserProfile.objects.select_related('user').get(verified_ssn=auth['ssn']).user
        ctx = {
            'auth': auth,
            'taken_user': taken_user,
        }

        auth_logout(request)

        return render_to_response('registration/verification_duplicate.html', ctx)

    profile = request.user.userprofile # It shall exist at this point
    profile.verified_ssn = auth['ssn']
    profile.verified_name = auth['name'].encode('utf8')
    profile.verified_token = request.GET['token']
    profile.verified_timing = datetime.now()
    profile.save()

    if hasattr(settings, 'ICEPIRATE'): # Is IcePirate support enabled?
        configure_external_member_db(request.user, create_if_missing=True)

    return HttpResponseRedirect('/')
Beispiel #10
0
def delete_account(request):
    context = {}
    if request.method == 'POST':
        confirma = request.POST.get('borrar', False)
        if confirma:
            try:
                token = str(uuid4())
                user = request.user
                cache.set(token, user.username,
                          timeout=settings.USER_DELETION_TTL)
                emails = ['registration/default/delete_email_subject.txt',
                          'registration/default/delete_email_subject.txt']
                subject = render_to_string(select_template(emails).name,
                                           {'site': settings.SITE_URL})
                delete_url = 'accounts:registration-confirm-deletion'
                mail_vars = {'site': settings.SITE_URL,
                             'path': reverse(delete_url, args=[token])}
                emails = ['registration/default/delete_email.html',
                          'registration/default/delete_email.html']
                html_content = render_to_string(select_template(emails).name,
                                                mail_vars)
                msg = EmailMessage(subject.strip("\n"), html_content,
                                   settings.DEFAULT_FROM_EMAIL, [user.email])
                # Main content is now text/html
                msg.content_subtype = "html"
                msg.send()
                mensaje = _(u'Te enviamos instrucciones para completar el cierre de tu cuenta.')
                messages.success(request, mensaje)
                auth_logout(request)
            except Exception as e:
                logger.error("Obtained error {e}".format(e=e.message))
            return render(request, 'accounts/delete_account_success.html',
                          context)
    return render(request, 'accounts/delete_account.html', context)
Beispiel #11
0
def confirm_deletion(request, token):
    key = cache.get(token, None)
    if key:
        cache.delete(token)
        try:
            user = User.objects.get(username=key)
            back_user = serializers.serialize('json', [user])
            ex_profile = ExtendedProfile.objects.filter(user=user)
            back_profile = serializers.serialize('json', ex_profile)
            backup_info = {'user': back_user, 'extended_profile': back_profile}
            deleted_user = DeletedUser()
            deleted_user.identifier = user.email
            deleted_user.user_information = backup_info
            deleted_user.save()
            user.delete()
            messages.success(request, _(u'Tu cuenta ha sido borrada.'))
            auth_logout(request)
        except Exception as e:
            logger.error("Error {e} en borrado de usuario".format(e=e))
            msg = _(u'Tu cuenta no ha sido borrada. Por favor intentar nuevamente')
            messages.error(request, msg)
        return redirect('accounts:profile')
    else:
        msg = _(u'Tu cuenta no ha sido borrada. Por favor intentar nuevamente')
        messages.error(request, msg)
        return redirect('accounts:profile')
Beispiel #12
0
def password(request):
    """
    修改用户密码
    """
    current_page = 'profile-password'
    if request.method == 'POST':
        raw_password = request.POST.get('raw_password','')
        new_password1 = request.POST.get('new_password1','')
        new_password2 = request.POST.get('new_password2','')

        if not request.user.check_password(raw_password):
            messages.error(request,'原始密码错误!')
        elif len(new_password1)<6 or len(new_password1)>30:
            messages.error(request,'新密码的长度不符合要求!')
        elif new_password1 <> new_password2:
            messages.error(request,'两次新密码输入不一致!')
        else:
            try:
                request.user.set_password(str(new_password2))
                request.user.save()
            except Exception,e:
                raise e
            auth_logout(request)
            messages.success(request,'密码修改成功!请使用新密码重新登录一次。')
            return HttpResponseRedirect('/accounts/login/?next=/home/')
Beispiel #13
0
def logout(request):
    auth_logout(request)

    redirect_to = request.POST.get(REDIRECT_FIELD_NAME,
                                   request.GET.get(REDIRECT_FIELD_NAME, ''))

    return HttpResponseRedirect(redirect_to or reverse('accounts:login'))
Beispiel #14
0
def logout(request):
    redirect = request.GET.get("redirect", request.POST.get("redirect", kwargs.get("redirect", "")))

    if not is_safe_url(url=redirect, host=request.get_host()):
        redirect = reverse("home")
    auth_logout(request)
    return HttpResponseRedirect(redirect)
Beispiel #15
0
 def dispatch(self, request, *args, **kwargs):
     auth_logout(request)
     next_page = self.get_next_page()
     if next_page:
         # Redirect to this page until the session has been cleared.
         return HttpResponseRedirect(next_page)
     return super(LogoutView, self).dispatch(request, *args, **kwargs)
Beispiel #16
0
def logout_view(request):
	from django.contrib.auth import logout as auth_logout

	cashdesk = get_cashdesk(request)
	if cashdesk:

		sessions = CashdeskSession.objects.filter(cashdesk=cashdesk, cashier=request.user, valid_from__lte=datetime.datetime.now(), cashier_has_ended=False)
		try:
			session = sessions[0]

			if request.GET.get('type') == 'session_end':
				# we have an active session -- end it and open the cash drawer
				open_drawer(cashdesk.receipt_printer_name)

				session.is_logged_in = False

				# set the session end time to NOW
				session.valid_until = datetime.datetime.now()
				session.cashier_has_ended = True

				session.save()
				cashdesk.active_session = None
				cashdesk.save()
			else:
				session.is_logged_in = False
				session.save()
		except:
			pass

	auth_logout(request)
	return HttpResponseRedirect(reverse("dashboard"))
Beispiel #17
0
def change_email(request, token):
    try:
        email_change_request = EmailChangeRequest.objects.get(
            token=token, valid_until__gte=now())
            # TODO: cronjob (celery task) to delete stale tokens
    except EmailChangeRequest.DoesNotExist:
        return TemplateResponse(request, 'registration/invalid_token.html')

    # if another user is logged in, we need to log him out, to allow the email
    # owner confirm his identity
    if (request.user.is_authenticated() and
            request.user != email_change_request.user):
        auth_logout(request)
    if not request.user.is_authenticated():
        query = urlencode({
            'next': request.get_full_path(),
            'email': email_change_request.user.email})
        login_url = utils.url(path=settings.LOGIN_URL, query=query)
        return redirect(login_url)

    request.user.email = email_change_request.email
    request.user.save()
    email_change_request.delete()

    messages.success(request, _('Your email has been successfully changed'))
    return redirect(settings.LOGIN_REDIRECT_URL)
Beispiel #18
0
 def get(self, request, *args, **kwargs):
     if defs.USERWARE_SWTICHED_USER_KEY in request.session:
         del request.session[defs.USERWARE_SWTICHED_USER_KEY]
     if request.user.is_authenticated():
         auth_logout(request)
         messages.add_message(self.request, messages.SUCCESS, _('You are now logged out.'))
     return HttpResponseRedirect(defs.LOGOUT_REDIRECT_URL)
Beispiel #19
0
def logout(request):
    try:
        del request.session['wechat_id']
    except:
        pass
    auth_logout(request)
    return redirect(reverse("home", kwargs={}))
def logout(request, redirect_url=None):

    auth_logout(request)

    url = redirect_url or getattr(settings, 'LOGOUT_REDIRECT_URL', '/')

    return HttpResponseRedirect(url) 
Beispiel #21
0
def logout(request, species_wid=None):
	auth_logout(request)	
	return render_queryset_to_response(
		species_wid = species_wid,
		request = request, 
		templateFile = 'public/logout.html', 
		)
Beispiel #22
0
def choose_collection(request):
    redirect_to = request.REQUEST.get('next', '')
    redirect_resp = HttpResponseRedirect(
        redirect_to if is_safe_url(url=redirect_to, host=request.get_host())
        else settings.LOGIN_REDIRECT_URL
    )

    available_collections = users_collections(connection.cursor(), request.specify_user.id)

    if len(available_collections) < 1:
        auth_logout(request)
        return TemplateResponse(request, 'choose_collection.html', context={'next': redirect_to})

    if len(available_collections) == 1:
        set_collection_cookie(redirect_resp, available_collections[0][0])
        return redirect_resp

    class Form(forms.Form):
        collection = CollectionChoiceField(
            choices=available_collections,
            initial=request.COOKIES.get('collection', None))

    if request.method == 'POST':
        form = Form(data=request.POST)
        if form.is_valid():
            set_collection_cookie(redirect_resp, form.cleaned_data['collection'])
            return redirect_resp
    else:
        form = Form()

    context = {'form': form, 'next': redirect_to}
    return TemplateResponse(request, 'choose_collection.html', context)
Beispiel #23
0
def logout(request, redirect_to=None):
    auth_logout(request)
    if redirect_to is None:
        return redirect('login')

    else:
        return redirect(redirect_to)
Beispiel #24
0
def logout(request, next_page=None):
    """Redirects to CAS logout page"""
    # try to find the ticket matching current session for logout signal
    try:
        st = SessionTicket.objects.get(session_key=request.session.session_key)
        ticket = st.ticket
    except SessionTicket.DoesNotExist:
        ticket = None
    # send logout signal
    cas_user_logout.send(
        sender="manual",
        user=request.user,
        session=request.session,
        ticket=ticket,
    )
    auth_logout(request)
    # clean current session ProxyGrantingTicket and SessionTicket
    ProxyGrantingTicket.objects.filter(session_key=request.session.session_key).delete()
    SessionTicket.objects.filter(session_key=request.session.session_key).delete()
    next_page = next_page or get_redirect_url(request)
    if settings.CAS_LOGOUT_COMPLETELY:
        protocol = get_protocol(request)
        host = request.get_host()
        redirect_url = urllib_parse.urlunparse(
            (protocol, host, next_page, '', '', ''),
        )
        client = get_cas_client()
        return HttpResponseRedirect(client.get_logout_url(redirect_url))
    else:
        # This is in most cases pointless if not CAS_RENEW is set. The user will
        # simply be logged in again on next request requiring authorization.
        return HttpResponseRedirect(next_page)
Beispiel #25
0
def logout(request, *args, **kwargs):
    auth_logout(request)
    messages.success(request,
                     "You have successfully logged out.")
    if 'next' in kwargs:
        return redirect(kwargs['next_page'])
    return bounce(request)
Beispiel #26
0
def logout(request):
    '''
    logout current user
    '''
    if request.user.is_authenticated():
        auth_logout(request)
        return redirect("/")
def logout(request, next_page=None,
           template_name='registration/logged_out.html',
           redirect_field_name=REDIRECT_FIELD_NAME,
           current_app=None, extra_context=None):
    """
    Logs out the user and displays 'You are logged out' message.

    A copy/paste of django.contrib.auth.views.logout, except with
    a different is_safe_url() check.
    """
    # XXX TODO: Replace this function with something that's
    # more flexible - class based auth?

    auth_logout(request)

    if redirect_field_name in request.REQUEST:
        next_page = request.REQUEST[redirect_field_name]
        # Security check -- don't allow redirection to a different host.
        if not is_safe_url(next_page):
            next_page = '/'

    if next_page:
        # Redirect to this page until the session has been cleared.
        return HttpResponseRedirect(next_page)

    current_site = get_current_site(request)
    context = {
        'site': current_site,
        'site_name': current_site.name,
        'title': _('Logged out')
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request, template_name, context,
        current_app=current_app)
Beispiel #28
0
def api_login(request):
    if request.method == 'PUT':
        data = simplejson.load(request)
        if any(data[key] is None for key in 'username password collection'.split()):
            auth_logout(request)
            return HttpResponse('', status=204)

        user = authenticate(username=data['username'],
                            password=data['password'])
        if user is None:
            return HttpResponseForbidden()
        auth_login(request, user)

        try:
            collection = Collection.objects.get(id=data['collection'])
        except Collection.DoesNotExist:
            return HttpResponseBadRequest('collection %s does not exist' % data['collection'])
        response = HttpResponse('', status=204)
        set_collection_cookie(response, collection.id)
        return response

    return HttpResponse(simplejson.dumps(dict(
        collections={c.collectionname: c.id for c in Collection.objects.all()},
        username=None,
        password=None,
        collection=None)), content_type='application/json')
Beispiel #29
0
def logout(request):
    if request.user.is_authenticated:
        print(request.user)
        auth_logout(request)
        print("after")
        print(request.user)
        return HttpResponseRedirect("/polls/login")
Beispiel #30
0
def third_user_login(request):

    """
    The method is third user login
    @param request: third_key, third_type
    @return:
    """
    if request.method == 'GET':
        return response_fail_to_mobile(500, REQUEST_METHOD_ERROR)
    try:
        username = request.POST['third_key']
        password = request.POST['third_type']
        user = authenticate(username=username, password=password, type=3)
        auth_login(request, user)
        logic = UserProfileLogic.get_user_profile_by_user_id(user_id=request.user.id)

        last_login = datetime_convert_current_timezone(logic.last_login_time)
        if last_login is not None:
            last_login = datetime_to_string(last_login)
        if logic.user_nick is None:
            user_nick = ''
        else:
            user_nick = logic.user_nick

        rec = dict()
        rec['session_id'] = request.session._session_key
        rec['user_id'] = request.user.id
        rec['user_name'] = user_nick
        rec['last_login'] = last_login
        UserProfileLogic.update_last_login_time(request.user.id)
        return response_success_to_mobile(rec)
    except Exception as e:
        error(e)
        auth_logout(request)
        return response_fail_to_mobile(500, 'Third part account login fail!')
Beispiel #31
0
def logout(request):
    """
    Log the user out of the current session, then redirect to login page.
    """
    auth_logout(request)
    return redirect('control:auth.login')
Beispiel #32
0
 def post(self, request, *args, **kwargs):
     auth_logout(request)
     return HttpResponseRedirect(request.get_full_path())
Beispiel #33
0
def logout(request):
    auth_logout(request)
    return redirect('articles:index')
Beispiel #34
0
def logout(request):
    auth_logout(request)
    messages.success(request, "Logged out!")
    return redirect('login')
Beispiel #35
0
def logout(request):
    auth_logout(request)
    return redirect('todos:index')
Beispiel #36
0
def logout_view(request):
  auth_logout(request)
  url2 = reverse_url("index")
  return HttpResponseRedirect(url2)
Beispiel #37
0
def logout(request):
    auth_logout(request)
    return redirect('/')
Beispiel #38
0
def logout(request):
    logger.info("%s logging out", request.user)
    auth_logout(request)
    return HttpResponseRedirect(reverse('landing_page'))
Beispiel #39
0
def logout(request):
    '''注销视图'''
    auth_logout(request)
    return HttpResponseRedirect(reverse('index'))
Beispiel #40
0
def logout(request):
    auth_logout(request)
    return redirect("movie:index")
Beispiel #41
0
def logout(request):
    """
    Logout view for the API consumer
    """
    auth_logout(request)
    return JsonResponse({'success': 'logout'})
Beispiel #42
0
def logout(request):
    auth_logout(request)
    return redirect("login")
Beispiel #43
0
def logout(request):
    auth_logout(request)
    return HttpResponseRedirect(reverse('question:index'))
Beispiel #44
0
def logout(request):
    auth_logout(request)
    return redirect('movies:list')
Beispiel #45
0
def logout(request):  # Session을 Delete하는 방식으로 로그아웃 기능 구현
    if request.method == 'POST':
        auth_logout(request)
        return redirect('boards:index')
    else:
        return redirect('boards:index')
Beispiel #46
0
def logout(request):
    auth_logout(request)
    return redirect('boards:index')
def logout(request):
    if request.user.is_authenticated:
        auth_logout(request)
    return HttpResponseRedirect(request.GET.get('next'))
Beispiel #48
0
def logout(request):
    auth_logout(request)
    return HttpResponse(
        '<script>window.alert("Ok!");location.href="/account/login"</script>')
Beispiel #49
0
    def get(self, request):
        if is_user_logged_in(request):
            auth_logout(request)
            messages.info(request, "You have logged out.")

        return redirect("home")
Beispiel #50
0
def logout(request):
    createLogEvent(request.user.username, "view: logout", 4, "User logged out")
    auth_logout(request)
    message = "Successfully logged out!"
    messages.add_message(request, messages.INFO, message)
    return HttpResponseRedirect("/")
Beispiel #51
0
def logout(request):
    auth_logout(request)
    return redirect('community:index')
Beispiel #52
0
def logout(request):
    auth_logout(request)
    return redirect('accounts:login')
Beispiel #53
0
def logout(request):
    auth_logout(request)
    request.session.set_expiry(0)
    next_url = request.META.get('HTTP_REFERER', reverse('web_selection'))
    return HttpResponseRedirect(next_url)
Beispiel #54
0
def handle_logout(request):
    """
    Log out.
    """
    auth_logout(request)
 def get(self, request, *args, **kwargs):
     auth_logout(request)
     return super(LogoutView, self).get(request, *args, **kwargs)
Beispiel #56
0
 def get_object(self):
     logged_user = get_object_or_404(UserProfile, user=self.request.user)
     if logged_user:
         auth_logout(self.request)
         return logged_user
Beispiel #57
0
def logout(request):
    auth_logout(request)
    return render(request, 'users/login.html', {'message': 'Logged out.'})
Beispiel #58
0
def logout(request):
    auth_logout(request)
    return HttpResponseRedirect('/')
Beispiel #59
0
def logout(request):
    form_login = LoginForm()
    auth_logout(request)
    
    return HttpResponseRedirect("/")
Beispiel #60
0
def logout(req):
    if not req.user.is_authenticated:
        return redirect('index')
    auth_logout(req)
    return redirect('index')