Beispiel #1
0
 def testLoginForm(self):
     """Check login form
     """
     # Forget user
     f1 = LoginForm({'pw':'test'})
     self.assertEqual(f1.is_valid(), False)
     self.assertEqual(f1.errors['__all__'][0], _("Email or password incorrect").translate('en'))
     # Forget password
     f1 = LoginForm({'email':'test'})
     self.assertEqual(f1.is_valid(), False)
     self.assertEqual(f1.errors['__all__'][0], _("Email or password incorrect").translate('en'))
     # Unexistant email
     f1 = LoginForm({'email':'*****@*****.**', 'pw':'test'})
     self.assertEqual(f1.is_valid(), False)
     self.assertEqual(f1.errors['__all__'][0], _("Email or password incorrect").translate('en'))
     # Incorrect
     f1 = LoginForm({'email':'*****@*****.**', 'pw':'test'})
     self.assertEqual(f1.is_valid(), False)
     self.assertEqual(f1.errors['__all__'][0], _("Email or password incorrect").translate('en'))
     # correct
     f1 = LoginForm({'email':'*****@*****.**','pw':'toto'})
     self.assertEqual(f1.is_valid(), True)
     # not active
     auser = User.objects.get(email='*****@*****.**')
     auser.is_active = False
     auser.save()
     f1 = LoginForm({'email':'*****@*****.**','pw':'toto'})
     self.assertEqual(f1.errors['__all__'][0], _("This user is not active").translate('en'))
Beispiel #2
0
def login_view(request):
    context = {}

    user = request.user

    if user.is_authenticated:
        return redirect("dashboard")

    if request.POST:
        form = LoginForm(request.POST)
        print(form)
        print("validity")
        if form.is_valid():
            email = request.POST['email']
            password = request.POST['password']

            user = authenticate(email=email, password=password)

            if user:
                login(request, user)
                return redirect("dashboard")
    else:
        form = LoginForm()
    context['login_form'] = form
    return render(request, 'login.html', context)
Beispiel #3
0
def user_login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        #这里执行is_valid()函数会调用forms文件中的clean_password2(self)验证器函数来验证表单信息是否存在
        if form.is_valid():
            cd = form.cleaned_data
            # authenticate,该方法接收request对象,username,password三个参数,到数据库中进行匹配。如果匹配成功,返回一个User数据对象,否则返回None.
            user = authenticate(request,
                                username=cd["username"],
                                password=cd["password"])
            if user is not None:
                if user.is_active:
                    #login()方法会在会话中设置用户信息
                    login(request, user)
                    return HttpResponse("登录成功!")
                else:
                    return HttpResponse("您的账户被禁用,请联系管理员解封!")
            else:
                return HttpResponse("登录失败!")
    else:
        form = LoginForm()
    data = {
        "form": form,
    }
    return render(request, "account/login.html", data)
def signin_view(request):
    if request.method == "POST":
        # Login action
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            print(username, password)
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                # messages.success(request, "Login successfully!")
                next_url = request.POST.get('next')
                logger.debug(str(next_url))
                if next_url:
                    return redirect(next_url)
                else:
                    return redirect('/')
            else:
                messages.error(request, "Invalid Login")
        else:
            messages.error(request, Inv)
        return render(request, "signin.html")
    elif request.method == "GET":
        return render(request, 'signin.html')
Beispiel #5
0
def login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            if '@' not in form.cleaned_data['email']:
                username = form.cleaned_data['email']
            else:
                try:
                    user = User.objects.get(email=form.cleaned_data['email'])
                    username = user.username
                except User.DoesNotExist:
                    username = None
            if username is not None:
                user = auth.authenticate(
                    username=username, password=form.cleaned_data['password'])
                if user is not None:
                    if user.is_active:
                        auth.login(request, user)
                        return HttpResponseRedirect(
                            request.GET.get('next') or reverse('me'))
            messages.error(
                request,
                "Your email and password didn't match. Please try again.")
    else:
        form = LoginForm()

    return render(request, 'account/login.html', {
        'form': form,
        'next': request.GET.get('next', '')
    })
Beispiel #6
0
def ajax_user_login(request):
    dic = {'status': True, 'msg': None}
    if request.method == 'POST':
        print(request.POST['user_name'])
        user_to_check = LoginForm(request.POST)
        if user_to_check.is_valid():
            data = user_to_check.cleaned_data
            user = authenticate(username=data['user_name'],
                                password=data['user_password'])
            if user:
                login(request, user)
                return HttpResponseRedirect('/blog/')
            else:
                # 有问题
                mes = '用户名或密码错误,请检查'
                dic['msg'] = mes
                dic['status'] = False
                # v =json.dumps(dic)
                return HttpResponse(dic['msg'])
        else:
            print(user_to_check.errors['user_password'][0])
            # return render(request, 'account/user_login.html', {'user_to_check': user_to_check})
            mes = user_to_check.errors['user_password'][0]
            dic['msg'] = mes
            dic['status'] = False
            return HttpResponse(dic['msg'])
    else:
        unlogin_user = LoginForm()
        return render(request, 'account/user_login.html',
                      {"unlogin_user": unlogin_user})
Beispiel #7
0
def user_login(request):
    # if request.user.is_authenticated():
    #     return render(request, 'account/login.html', {'message': "您已登录!请先退出"})
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(request,
                                username=cd['username'],
                                password=cd['password'])
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect('/book/')
                else:
                    return HttpResponse('用户目前禁用')
            else:
                return render(request, 'account/login.html',
                              {'message': "用户名或者密码错误"})
        else:
            form = LoginForm()
            return render(request, 'account/login.html',
                          {'message': "用户名或者密码错误"})
    else:

        form = LoginForm()
        return render(request, 'account/login.html', {'form': form})
Beispiel #8
0
 def test_valid_login_form(self):
     data = {
         'username': "******",
         'password': "******",
     }
     form = LoginForm(data=data)
     self.assertTrue(form.is_valid())
Beispiel #9
0
def user_login(request):
    # 判断http请求方式
    if request.method == "POST":
        # 实例化表单对象
        form = LoginForm(request.POST)
        # 判断表单内容是否是有效的
        if form.is_valid():
            # 维护表单数据格式
            cd = form.cleaned_data
            # 验证提交的证书是否是有效的
            user = authenticate(request,
                                username=cd['username'],
                                password=cd['password'])
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponse("Authenticated successfully")
                else:
                    return HttpResponse("Disable templates")
            else:
                return HttpResponse("Invalid login")

    else:
        form = LoginForm()

    return render(request, "account/login.html", {'form': form})
Beispiel #10
0
def login(request):
    """Вход в учетную запись"""
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user:
                if user.is_active:
                    auth_login(request, user)
                    messages.success(request,
                                     f'Добро пожаловать, {user.username}!')
                    if user.is_superuser:
                        # если суперюзер, то перенаправить сразу в админку
                        return redirect('/admin')
                    return redirect('/')
                else:
                    messages.error(
                        request,
                        'Ваша учетная запись неактивна. Возможно, Вы не подтвердили её.'
                    )
                    return redirect('login')
            else:
                messages.error(request, 'Неверный логин или пароль')
                return redirect('login')
    else:
        form = LoginForm
    template = os.path.join(BASE_DIR, "templates/registration/login.html")
    context = {'form': form}
    return render(request, template, context)
Beispiel #11
0
def user_login(request):
    '''
    登录
    :param request:
    :return:
    '''
    if request.method == "GET":
        if request.session.get('is_login'):  # 如果is_login存在,说明已经登陆,直接跳转到主页
            return redirect(reverse('account:home'))
        login_form = LoginForm()
        return render(request, 'account/login_bootstrap3.html', locals())

    if request.method == "POST":
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            # .cleaned_data 清洗出合法数据
            name = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            user = AccountUser.objects.filter(
                name=name).first()  # 返回filter后的第一个
            if user and user.password == password:
                request.session['is_login'] = True
                request.session['id'] = user.id  # id 展示的是ID,主键
                request.session['display_name'] = user.display_name
                request.session['dep'] = user.dep.name  # 获取所属的小组
                Log.objects.create(user_id=user.id, action='登录')
                return redirect(reverse('account:home'))
            else:
                message = '用户名或密码错误!'
            # 检验账号、密码是否正确匹配数据库中的某个用户
            # 如果均匹配则返回这个 user 对象
        else:
            return HttpResponse("不合法")
        return render(request, 'account/login_bootstrap3.html', locals())
Beispiel #12
0
def login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            if '@' not in form.cleaned_data['email']:
                username = form.cleaned_data['email']
            else:
                try:
                    user = User.objects.get(email=form.cleaned_data['email'])
                    username = user.username
                except User.DoesNotExist:
                    username = None
            if username is not None:
                user = auth.authenticate(username=username, 
                                         password=form.cleaned_data['password'])
                if user is not None:
                    if user.is_active:
                        auth.login(request, user)
                        return HttpResponseRedirect(request.GET.get('next') or reverse('me'))
            messages.error(request, "Your email and password didn't match. Please try again.")
    else:
        form = LoginForm()

    return render(request, 'account/login.html', {
        'form': form,
        'next': request.GET.get('next', '')
    })
Beispiel #13
0
def user_login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(username=cd['username'],
                                password=cd['password'])
            if user is not None:
                if user.is_active and user.is_verified:
                    login(request, user)
                    if request.user.is_investor:
                        return redirect('portal:home')
                    elif request.user.is_innovator:
                        return redirect('portal:home')
                    elif request.user.is_entrepreneur:
                        return redirect('portal:home')
                    elif request.user.is_partner:
                        return redirect('portal:home')
                    elif request.user.is_service_provider:
                        return redirect('portal:home')
                    elif request.user.is_superuser or request.user.is_staff:
                        return redirect('/admin/')
                else:
                    login(request, user)
                    return redirect('account:verify')
            else:
                messages.error(
                    request,
                    'Your username and password didn\'t match. please try again'
                )

    else:
        form = LoginForm()
    return render(request, 'loginApp/login.html', {'form': form})
def do_login(request):
    form = LoginForm(initial={"next": request.GET.get("next", "/")})
    if request.POST:
        form = LoginForm(request.POST)
        if form.is_valid():
            pantheon_id = form.user_data["id"]
            try:
                user = User.objects.get(new_pantheon_id=pantheon_id)
            except User.DoesNotExist:
                user = User.objects.create_user(
                    username=form.user_data["email"],
                    email=form.user_data["email"],
                    password=None,
                )
                user.new_pantheon_id = pantheon_id
                user.save()

            login(request, user)

            try:
                league_player = LeaguePlayer.objects.get(
                    name=form.user_data["title"])
                league_player.user = user
                league_player.save()
            except LeaguePlayer.DoesNotExist:
                pass

            return redirect(form.cleaned_data["next"])

    return render(request, "account/login.html", {"form": form})
Beispiel #15
0
def user_login(request):
    if request.method == 'POST':  #  не будет виден в строке браузера
        form = LoginForm(
            request.POST
        )  # request.POST создст штмл форму из Django создаст как мы прописали в forms
        if form.is_valid():  #  проверка правильно заполнен пароль
            cd = form.cleaned_data  # метод cleaned_data создаем формы и проверяем
            user = authenticate(username=cd['username'],
                                password=cd['password']
                                )  # это словарь ключем является поле из forms

            if user is not None:  # говоря проще если пользователь существует
                if user.is_active:
                    login(request, user)
                    return redirect('dashboard')  # перенаправить в кабинет
                    #return redirect('/') # вернуть на главную

                else:  # если пароль и имя не подошли
                    return HttpResponse('Disabled account')

            else:  # если вообще все пошло не так
                return HttpResponse('Invalid login and password')

    else:
        form = LoginForm()
    return render(request, "account/login.html", {
        'form': form,
        'username': auth.get_user(request).username
    })  #  будет отображать вошел пользователь или не вошел
Beispiel #16
0
 def login(request):
     form = None
     if request.method == 'POST':
         form = LoginForm(request.POST)
         if form.is_valid():
             data = form.data
             if '@' in data['identity']:
                 kwargs = {'email': data['identity'].lower()}
             else:
                 kwargs = {'username': data['identity'].lower()}
             try:
                 user = User.objects.get(**kwargs)
                 if user is not None and user.check_password(
                         data['password']):
                     login(request, user)
                     if 'keep_connected' in data:
                         request.session.set_expiry(0)
                     next_page = request.GET.get('next', None)
                     redirect_path = reverse('home')
                     if next_page is not None and next_page != '':
                         redirect_path = next_page
                     user_account = Account.get_by_user(user=user)
                     request.session[
                         'user_avatar'] = user_account.user_avatar
                     request.session.save()
                     return redirect(redirect_path)
             except User.DoesNotExist:
                 pass
     return render(request, 'index.html', {'form': form})
Beispiel #17
0
def login_view(request):
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            user = authenticate(username=email, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect(reverse('home'))
                else:
                    form = LoginForm(request.POST)
                    messages.warning(request, _("this user is not active"))
                    ctx = {"login_form": form}
                    return render(request, "login.html", ctx)
            else:
                form = LoginForm(request.POST)
                form.errors["email"] = _("no such user")
                messages.error(request, "no such user")
                ctx = {"login_form": form}
                return render(request, "login.html", ctx)
        else:
            form = LoginForm(request.POST)
            ctx = {"login_form": form}
            return render(request, "login.html", ctx)
    else:
        form = LoginForm()
        ctx = {"login_form": form}
        return render(request, "login.html", ctx)
Beispiel #18
0
def login_view(request):

    context = {}

    user = request.user
    if user.is_authenticated:
        return redirect(reverse('index'))

    if request.POST:
        form = LoginForm(request.POST)
        if form.is_valid():
            email = request.POST['email']
            password = request.POST['password']
            user = authenticate(email=email, password=password)

            if user:
                login(request, user)
                return redirect(reverse('index'))

    else:
        form = LoginForm()

    context['login_form'] = form

    # print(form)
    return render(request, "account/login.html", context)
Beispiel #19
0
def user_login(request):

    if request.user.is_authenticated and request.user.is_active:

        return HttpResponseRedirect(reverse('account:dashboard'))
    if request.method == 'POST':

        form = LoginForm(request.POST)

        if form.is_valid():

            cd = form.cleaned_data
            username = cd['username']
            password = cd['password']

            user = authenticate(request, username=username, password=password)

            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect(reverse('account:dashboard'))
                else:
                    return HttpResponse('Disable Account')
            else:
                return HttpResponse('Invalid login')
    else:
        form = LoginForm()

    context = {'form': form}
    return render(request, 'account/login.html', context)
Beispiel #20
0
def login(request):

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

        if form.is_valid():
            user = authenticate(email=request.POST['email'],
                                password=request.POST['password'])
            existed_user = get_user(request.POST['email'])

            if user is not None:
                if user.is_active:
                    django_login(request, user)
                    messages.success(request, '로그인되었습니다.')
                    return redirect('/')

            elif user is None and existed_user is not None:
                messages.error(request, '이메일 인증절차가 필요합니다.')

            elif user is None and existed_user is None:
                messages.error(request, '가입되지 않은 사용자입니다.')

        else:
            messages.error(request, '올바른 정보를 입력해주세요.')

    else:
        form = LoginForm()

    return render(request, 'account/login.html', {'form': form})
Beispiel #21
0
def user_login(request):
    if request.user.is_authenticated():
        return redirect('account:dashboard')
    elif request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(username=cd['username'],
                                password=cd['password'])
            # If the user exists and it is active, login, else error.
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect('account:dashboard')
                else:
                    return render(request, 'account/login.html', {
                        'form': form,
                        'error': 'Disabled account'
                    })
            else:
                return render(request, 'account/login.html', {
                    'form': form,
                    'error': 'Disabled account'
                })
    else:
        form = LoginForm()
    return render(request, 'account/login.html', {'form': form})
Beispiel #22
0
def login_view(request):
    context = {}

    user = request.user
    if user.is_authenticated:
        return redirect('index')

    if request.POST:
        form = LoginForm(data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(request, username=username, password=password)
            if user:
                login(request, user)
                return redirect('index')
            else:
                # Unsuccessfull login, redirect error to context
                context['login_form'] = form
        else:
            # If form not valid, redirect user's errors to context
            context['login_form'] = form
    else:
        # If not post request, then let user see an empty form
        form = LoginForm()
        context['login_form'] = form
    return render(request, "account/login.html", context)
Beispiel #23
0
def login(request):
    if request.user.is_authenticated():
        return handle_user_type(request, redirect_request=True)
    f = LoginForm(request.POST)
    if f.is_valid():
        user = f.get_user()
        if not user.is_active:
            from datetime import datetime
            user_hashid = ''
            timestamp = user.last_login or user.date_joined
            if ((datetime.utcnow() -
                 timestamp.replace(tzinfo=None)).total_seconds() >
                    300):  # 5 min
                user_hashid = settings.HASHID_CUSTOM_USER.encode(user.pk)
            return JsonResponse(
                data={
                    'success':
                    True,
                    'render':
                    loader.render_to_string('account/inactive.html', {
                        'user': user,
                        'user_hashid': user_hashid
                    })
                })
        auth_login(request, user)
        return JsonResponse(data={
            'success': True,
            'location': get_relevant_reversed_url(request)
        })
    else:
        return JsonResponse(status=400,
                            data={'errors': dict(f.errors.items())})
Beispiel #24
0
def login_view(request):
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            user = authenticate(username=email, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect(reverse('home'))
                else:
                    form = LoginForm(request.POST)
                    messages.warning(request, _("this user is not active"))
                    ctx = { "login_form": form}
                    return render(request, "login.html", ctx)
            else:
                form = LoginForm(request.POST)
                form.errors["email"] = _("no such user")
                messages.error(request, "no such user")
                ctx = { "login_form": form}
                return render(request, "login.html", ctx)
        else:
            form = LoginForm(request.POST)
            ctx = {"login_form": form }
            return render(request, "login.html", ctx)
    else:
        form = LoginForm()
        ctx = { "login_form": form}
        return render(request, "login.html", ctx)
Beispiel #25
0
def user_login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(request,
                                username=cd['username'],
                                password=cd['password'])
            if user is not None:
                if user.is_active:
                    login(request, user)
                    if user.is_manager():
                        if Room.objects.filter(author=user):
                            return redirect(reverse('account:profile'))
                        else:
                            return redirect(reverse('account:create_room'))
                    else:
                        print(user.username)
                        return redirect(reverse_lazy('account:profile'))
                else:
                    return HttpResponse('аккаунт неактивен')
            else:
                return HttpResponse('Неправильный логин')
    else:
        form = LoginForm()
    return render(request, 'account/login.html', {'form': form})
Beispiel #26
0
def login_view(request):
    account = LoginForm(data=request.POST or None, request=request, prefix='warga')
    context = {
        "form" : account
    }
    if account.is_valid():
        return redirect('warga:index')
    return render(request, 'warga/auth/login.html', context)
Beispiel #27
0
def login_admin_kelola(request):
    account = LoginForm(data=request.POST or None, request=request, prefix='admin')
    context = {
        "form" : account
    }
    if account.is_valid():
        return redirect('admin_kelola:index')
    return render(request, 'admin_kelola/auth/login.html', context)
Beispiel #28
0
 def post(self, request):
     form = LoginForm(request.POST)
     if form.is_valid():
         form.login(request)
         profile = request.user.get_profile()
         return Response({'id': profile.id, 'name': profile.name})
     else:
         return Response(form.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #29
0
def login(request):
    context = {}
    if request.method == "POST":
        next_page = request.POST.get('next', None)
        if not request.POST.get("remember_me", None):
            request.session.set_expiry(0)
        form = LoginForm(request.POST)
        if form.is_valid():
            context["form"] = form
            username = form.data["login"]
            password = form.data["password"]
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                try:
                    user = User.objects.get(email=username)
                except User.DoesNotExist:
                    messages.error(request, "Имя пользователя/Email неверный")
                    return redirect(reverse('account:login'))
            if user.check_password(password):
                if user.is_active:
                    user_auth = authenticate(request, username=user.username)
                    auth_login(request, user_auth)
                    messages.success(request, f'Здравствуйте, {user.username}')
                    if next_page is not None:
                        return redirect(next_page)
                    return redirect(reverse('link_add'))
                else:
                    try:
                        code_object = Code.objects.get(user=user, status=True)
                        messages.warning(
                            request,
                            'Был получен запрос на восстановление пароля. Учётная запись деактивирована. Следуйте инструкциями отправленным на электронную почту, указанную при регистрации.'
                        )
                    except Code.DoesNotExist:
                        messages.error(
                            request,
                            "На электронную почту, указанную при регистрации было выслано письмо с инструкцией для подтверждения аккаунта."
                        )
            else:
                try:
                    User.objects.get(username=username)
                    messages.error(request, "Неверный пароль")
                except User.DoesNotExist:
                    messages.error(request, "Имя пользователя/Email неверный")
        else:
            messages.error(request, "Неправильный формат данных.")
            context["form"] = LoginForm()
    else:
        if request.user.is_authenticated:
            messages.warning(request, "Вы уже вошли в аккаунт.")
            return redirect(reverse('account:view_my'))
        next_page = request.GET.get('next', None)
        context['next'] = next_page
        context["form"] = LoginForm()
    return render(request, "account/login.html", context)
Beispiel #30
0
def login(request):
    """
    DataHub account login form.

    GET returns and HttpResponse containing the account login form.
    POST logs in name/email/password accounts.
    Other links from the page lead to Python Social Auth options (Google,
    Facebook, Twitter, etc).
    """
    # Redirect succesful logins to `next` if set.
    # Failing that `redirect_url`.
    # Failing that, LOGIN_REDIRECT_URL from settings.py.
    redirect_uri = get_or_post(request,
                               'next',
                               fallback=get_or_post(
                                   request,
                                   'redirect_url',
                                   fallback=settings.LOGIN_REDIRECT_URL))
    redirect_absolute_uri = add_query_params_to_url(
        request.build_absolute_uri(redirect_uri),
        {'auth_user': request.user.get_username()})

    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username'].lower()
            password = form.cleaned_data['password']
            user = datahub_authenticate(username, password)
            if user is not None and user.is_active:
                django_login(request, user)
                # Append auth_user to redirect_uri so apps like Kibitz can
                # pull the username out of the redirect. This should be
                # removed when Thrift is removed from DataHub.
                redirect_uri = add_query_params_to_url(
                    redirect_uri, {'auth_user': request.user.get_username()})
                return HttpResponseRedirect(redirect_uri)
            else:
                form.add_error(None, "Username and password do not match.")
        else:
            # Form isn't valid. Fall through to return it to the user with
            # errors.
            pass
    else:
        form = LoginForm()

    providers = provider_details()
    context = RequestContext(
        request, {
            'request': request,
            'user': request.user,
            'form': form,
            'providers': providers,
            'next': redirect_uri,
            'absolute_next': redirect_absolute_uri,
        })
    return render_to_response('login.html', context_instance=context)
Beispiel #31
0
def userlogin(request):
  template_name = "account/login.html"
  form = LoginForm()
  if request.method == 'POST':
    form = LoginForm(request.POST)
    if form.is_valid():
      user = form.cleaned_data['user']
      login(request, user)
      return redirect("/")
  return render(request, template_name, {'form': form})
Beispiel #32
0
def loginuser(request):
    print(request.session.items())

    if (request.user.is_authenticated()):
        title = "pinmyblogs|dashboard"
        return redirect('dashboard')

    else:
        title = "Pinmyblogs|Login"
        data = {}
        if (request.method == "POST"):

            form = LoginForm(request.POST)
            if form.is_valid():
                email = form.cleaned_data.get('email')
                password = form.cleaned_data.get('password')
                username = User.objects.filter(email=email)
                # print(username)
                if (username):

                    print(username[0])
                    try:
                        user = authenticate(username=username[0],
                                            password=password)
                        login(request, user)
                        request.session['email'] = email

                        return redirect('dashboard')
                    except Exception:
                        print("error is here")
                        data['error'] = 'Invalid E-mail/Password'
                        return render(request, 'login.html', {
                            'title': title,
                            'error': data['error']
                        })

                else:
                    print(form.errors)
                    print('Here we got the main error ')

                    data['error'] = 'Invalid E-mail/Password'
                    return render(request, 'login.html', {
                        'title': title,
                        'error': data['error']
                    })
            else:
                data['error'] = 'Invalid E-mail/Password'

                return render(request, 'login.html', {
                    'title': title,
                    'error': data['error']
                })

        data = {"title": title}
        return render(request, 'login.html', data)
Beispiel #33
0
def login(request):
    '''登陆视图'''
    context={}
    form = LoginForm()    
    if request.method == 'POST':
        form=LoginForm(request.POST.copy())
        if form.is_valid():
            return _login(request,form.cleaned_data["username"],form.cleaned_data["password"])
    context["form"]=form        
    return render_to_response("accounts/login.html",context,\
                                   context_instance=RequestContext(request))
Beispiel #34
0
def login_view(request):
    form = LoginForm(request.POST or None)
    if request.method == 'POST':

        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            login(request, user)
            return redirect('home')
    return render(request, 'accounts/login.html', {'form': form})
Beispiel #35
0
def login(request):
    login_form = LoginForm(request.POST)
    data = {}
    if login_form.is_valid():
        user = login_form.cleaned_data['user']
        auth.login(request, user)
        data['status'] = 'SUCCESS'

    else:
        data['status'] = 'ERROR'
    return JsonResponse(data)
Beispiel #36
0
 def post(self, request, *args, **kwargs):
     user_form = LoginForm(request.POST)
     if user_form.is_valid():
         user = authenticate(username=user_form.cleaned_data['username'],
                             password=user_form.cleaned_data['password'])
         if user is not None:
             if user.is_active:
                 login(request, user)
                 return HttpResponseRedirect(self.get_success_url())
         else:
             messages.error(request, 'User not found. Please enter correct parameters.')
     return render(request, self.template_name, {'form': user_form})
Beispiel #37
0
def login(request):
    if request.method == 'POST':
        form = LoginForm(request, data=request.POST)
        if form.is_valid():
            auth_login(request, form.get_user())
            next_page = request.GET.get('next', '/')
            return HttpResponseRedirect(next_page)
    else:
        form = LoginForm()
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    return TemplateResponse(request, 'account/login.html', {'form': form})
Beispiel #38
0
def login_user(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            print "I get here"
            user = authenticate(username=User.objects.get(email=form.cleaned_data['email']).username, password=form.cleaned_data['password'])
            login(request, user)
            return HttpResponseRedirect('/')
    else:
        form = LoginForm()
    print "no here"
    return render_to_response("account/login.html", {'form':form}, context_instance=RequestContext(request))
Beispiel #39
0
def login(request):
    r_url = request.REQUEST.get('next','/')
    template_var={}
    form = LoginForm()    
    if request.method == 'POST':
        form=LoginForm(request.POST.copy())
        if form.is_valid():
            _login(request,form.cleaned_data["username"],form.cleaned_data["password"])
            
            return HttpResponseRedirect(r_url)
    template_var["form"]=form        
    return render_to_response("login.html",template_var,context_instance=RequestContext(request))
Beispiel #40
0
    def post(self, request):
        form = LoginForm(request.POST.copy())

        if form.is_valid():
            data = form.cleaned_data

            user = authenticate(username=data['username'], password=data['password'])
            if user:
                auth_login(request, user)
                return {"redirect": "/account/profile/"}

        return {'form': form}
Beispiel #41
0
def login(request):
    """
    DataHub account login form.

    GET returns and HttpResponse containing the account login form.
    POST logs in name/email/password accounts.
    Other links from the page lead to Python Social Auth options (Google,
    Facebook, Twitter, etc).
    """
    # Redirect succesful logins to `next` if set.
    # Failing that `redirect_url`.
    # Failing that, LOGIN_REDIRECT_URL from settings.py.
    redirect_uri = post_or_get(
        request, 'next', fallback=post_or_get(
            request, 'redirect_url', fallback=settings.LOGIN_REDIRECT_URL))
    redirect_absolute_uri = add_query_params_to_url(
        request.build_absolute_uri(redirect_uri),
        {'auth_user': request.user.get_username()})

    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username'].lower()
            password = form.cleaned_data['password']
            user = datahub_authenticate(username, password)
            if user is not None and user.is_active:
                django_login(request, user)
                # Append auth_user to redirect_uri so apps like Kibitz can
                # pull the username out of the redirect. This should be
                # removed when Thrift is removed from DataHub.
                redirect_uri = add_query_params_to_url(
                    redirect_uri, {'auth_user': request.user.get_username()})
                return HttpResponseRedirect(redirect_uri)
            else:
                form.add_error(None, "Username and password do not match.")
        else:
            # Form isn't valid. Fall through to return it to the user with
            # errors.
            pass
    else:
        form = LoginForm()

    providers = provider_details()
    context = RequestContext(request, {
        'request': request,
        'user': request.user,
        'form': form,
        'providers': providers,
        'next': redirect_uri,
        'absolute_next': redirect_absolute_uri,
        })
    return render_to_response('login.html', context_instance=context)
Beispiel #42
0
def login_user(request):
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            user = authenticate(
                username=User.objects.get(username=form.cleaned_data["username"]).username,
                password=form.cleaned_data["password"],
            )
            login(request, user)
            return HttpResponseRedirect("/")
    else:
        form = LoginForm()
    return render_to_response("account/login.html", {"form": form}, context_instance=RequestContext(request))
Beispiel #43
0
def do_login(request):
    try:
        nexturl = request.REQUEST['next']
    except KeyError:
        nexturl = LOGIN_REDIRECT_URL
    form = LoginForm(request.POST)
    if not form.is_valid():
        return render_to_response('acc_login.html',
                                  {'form': form },
                                  context_instance=RequestContext(request))
    username = form.cleaned_data['username']
    password = form.cleaned_data['password']
    user = authenticate(username=username, password=password)
    login(request, user)
    return HttpResponseRedirect(nexturl)
Beispiel #44
0
def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            user = auth.authenticate(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['passwd']
            )
            if user is not None:
                auth.login(request, user)
                return redirect(request, 'src-home')
    else:
        form = LoginForm()
    params = {'form': form}
    params.update(csrf(request))
    return response(request, params)
Beispiel #45
0
def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            user = data['user']
            auth.login(request, user)
            redirect_to = request.REQUEST.get('next', reverse('home'))
            return HttpResponseRedirect(redirect_to)
    else:
        form = LoginForm()
    referrer = get_referrer(request)
    context = RequestContext(request)
    context['form'] = form
    context['referrer'] = referrer
    return render_to_response('account/login.html', context)
Beispiel #46
0
def login_view(request, template_name='account/retailer/login.html'):
    form = LoginForm()
    if request.method == 'POST':
        form = LoginForm(data=request.POST)

        if form.is_valid():
            user = authenticate(username=request.POST['email'], password=request.POST['password'])
            if user is not None:
                login(request, user)
                return HttpResponseRedirect('/')

    variables = RequestContext(request, {
        'form':form,
    })

    return render_to_response(template_name, variables)
Beispiel #47
0
def login(request):
    """
    Displays the login form and handles the login action.
    """
    redirect_to = request.REQUEST.get('next', '')
    if not redirect_to:
        redirect_to = get_referer_url(request)

    if request.method == "POST":
        form = LoginForm(data=request.POST)
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            if not form.cleaned_data.get('remember_me'):
                request.session.set_expiry(0)

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()

            return  JsonResponse({'status': True, 'redirect': redirect_to})
        else:
            status = False
    else:
        form = LoginForm(request)
        status = True

    request.session.set_test_cookie()

    request_url = urlparse.urlparse(request.build_absolute_uri())

    context = {
        'form': form,
        'next': redirect_to or '',
        'domain': request_url.netloc,
        'rand': ''.join(random.choice(string.ascii_lowercase) for x in range(5))
    }

    if request.is_ajax():
        return JsonResponse({'status': status, 'template': render_to_string(
            'account/login/login_form.html', context, context_instance=RequestContext(request))})
    return TemplateResponse(request, 'account/login/login_container.html', context)
Beispiel #48
0
def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            user = authenticate(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password']
            )
            if user and user.is_active:
                django_login(request, user)
                return redirect(request.GET.get('next', '/sign/'))
            else:
                form.add_error(None, _('Invalid username or password'))
    else:
        form = LoginForm()

    return render(request, 'account/login.html', {'form': form})
Beispiel #49
0
def login_user(request,
               login_success_url="home",
               template="account/login.html"):
    form = LoginForm()

    if request.POST:
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            user = authenticate(email=email, password=password) 

            if user is not None:
                login(request, user)
                return redirect(login_success_url)

    ctx={'form': form, 'user':request.user}
    return render(request, template, ctx)
Beispiel #50
0
def login_page(request):
	is_guest = False
	if request.user.is_authenticated():
		is_guest = hasattr(request.user, 'additional') and request.user.additional.is_guest
		if not is_guest:
			return redirect('/')

	if request.POST:
		form = LoginForm(data=request.POST)
		user = authenticate(username=request.POST['username'], password=request.POST['password'])
		if form.is_valid() and user:
			if is_guest:
				logout(request)
			login(request, user)
			messages.success(request, 'Welcome %s !' % (user.username, ))
			return redirect('/')
		return render(request, 'login.html', {'form': form})
	return render(request, 'login.html', {'form': LoginForm()})
Beispiel #51
0
def log_in(request):
    form = LoginForm(request.POST)

    if not form.is_valid():
        return HttpResponse(status=400, content="Must fill in all fields")

    username = form.cleaned_data["username"]
    password = form.cleaned_data["password"]

    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            return HttpResponse(status=200)
        else:
            return HttpResponse(status=400, content="Account has been de-activated")
    else:
        return HttpResponse(status=400, content="Username or password is incorrect")
Beispiel #52
0
def do_login(request):
    post = dict(request.POST)
    post['next'] = request.REQUEST['next'] or LOGIN_REDIRECT_URL
    form = LoginForm(post)
    if not form.is_valid():
        return render_to_response('acc_login.html',
                                  {'form': form },
                                  context_instance=RequestContext(request))
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user = authenticate(username=username, password=password)
        if not user or not user.is_active():
            form.errors['username'] = '******'
            return render_to_response('acc_login.html',
                                      {'form': form },
                                      context_instance=RequestContext(request))
        login(request, user)
        return HttpResponseRedirect(form.cleaned_data['next'])
Beispiel #53
0
def user_login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(username=cd['username'],
                password=cd['password'])
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponse('Authenticated successfully')
                else:
                    return HttpResponse('Disabled account')
            else:
                return HttpResponse('Invalid login')
    else:
        form = LoginForm()
    return render(request, 'account/login.html', {'form': form})
Beispiel #54
0
def login(request,template_name='user.login.tpl'):
    next_url = request.GET.get("next")
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            pwd = form.cleaned_data['password']
            user = authenticate(email=email,password=pwd)
            if user is not None:
                auth_login(request,user)
                if next_url:
                    return redirect(next_url)
                return redirect("/")
            else:
                form.errors['msg'] = u"登录失败,请检查用户名和密码是否正确"
        else:
            form.errors['msg'] = u"输入信息格式不合法,请重试"
    else:
        form = LoginForm()
    return render_response(template_name,form=form,request=request,next_url=next_url)
Beispiel #55
0
    def post(self, request):
        form = LoginForm(request.POST)

        if form.is_valid():
            user = authenticate(username=form.cleaned_data['username'],
                                password=form.cleaned_data['password'])
            if user is not None:
                if user.is_active:
                    login(request, user)
                    messages.success(request, "Inloggen gelukt!")
                    if len(request.GET) > 0:
                        return redirect(request.GET['next'])
                    return redirect("dining:index")
                else:
                    messages.error(request, "Deze account is niet geactiveerd")
            else:
                messages.warning(request, "Gebruikersnaam of wachtwoord klopt niet")

        self.context['form'] = form
        return render(request, self.template, self.context)
Beispiel #56
0
def auth(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            passwd = form.cleaned_data['password']
            user = authenticate(username=username,password=passwd)
            if user is not None:
                if user.is_active:
                    login(request,user)
                    return redirect("index")
                else:
                    return HttpResponse("User not active")
            else:
                return HttpResponse("User not found or user not register")
        else:
            return HttpResponse("Your input wrong")
            
    else:
        form = LoginForm()
        return render(request,'auth.html',{'form':form })
Beispiel #57
0
def auth_login( request ):
    members = Member.objects.active()
    projects = Project.objects.all()
    redirect_to = request.REQUEST.get( 'next', '' ) or REDIRECT_TO
    if request.method == 'POST':
        form = LoginForm( request.POST )
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate( username=username, password=password )
            if user is not None:
                if user.is_active:
                    login( request, user )
                    member, created = Member.objects.get_or_create(
                            nickname=username)
                    if created:
                        member.save()
                    return HttpResponseRedirect( redirect_to )
    else:
        form = LoginForm()
    return render_to_response( 'login.django', RequestContext( request, locals() ) )
Beispiel #58
0
def user_login(request):
	template = 'account/login.html'
	if request.method == 'POST':
		form = LoginForm(request.POST)
		if form.is_valid():
			# if the submitted data is valid we authenticate it against the database using authenticate()
			cd = form.cleaned_data
			user = authenticate(username=cd['username'], password=cd['password'])

			if user is not None:
				# if the user exists in the database
				if user.is_active:
					# login() sets the user in the session
					login(request, user)
					return HttpResponse('Authenticated Successfully')
				else:
					return HttpResponse('Disabled Account')
			else:
				return HttpResponse('Invalid Login')
	else:
		# if the request method is GET, return a new form
		form = LoginForm()
	return render(request, template, {'form': form})
Beispiel #59
0
    def post(self, request):
        form = LoginForm(request.POST.copy())

        if form.is_valid():
            data = form.cleaned_data

            user = authenticate(username=data['username'], password=data['password'])
            if user:
                auth_login(request, user)
                # create row in db->table User_LastOut
                # db->table User_LastOut
                # db->table UserSetting
                # db->table User_data
                # if no row
                if not(User_LastOut.objects.filter(username=data['username'])):
                    LastOut_obj = User_LastOut(username = data['username'],last_out_string = '', text = 'added automatically')
                    LastOut_obj.save()
                if not(UserSetting.objects.filter(username=data['username'])):
                    UserSettingObj = UserSetting(username = data['username'], receive_digest = False, time ='8:18:-1')
                    UserSettingObj.save()
                return {"redirect": "/account/profile/"}

        return {'form': form}
Beispiel #60
0
def auth_login(request):
    redirect_to = request.GET.get('next', '') or '/'
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = form.login(request)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    member, created = \
                        User.objects.get_or_create(username=username)
                    if created:
                        member.save()

                    # save password in the session for later use with LDAP
                    key = store_ldap_password(request, password)
                    response = HttpResponseRedirect(redirect_to)
                    response.set_cookie('sessionkey', key)
                    return response
    else:
        form = LoginForm()
    return render(request, 'login.html', {'form': form})