Ejemplo n.º 1
0
    def post(self):
        """
        Handles the HTTP POST requests (overriding :meth:`MethodView.post`) .

        If the form was correctly filled and the user password validates
        (through :meth:`~base.models.User.check_password`),
        calls :func:`flask.ext.login.login_user`,
        emits a flash message of success and redirects the request to
        the `next` parameter or the home page if not specified.

        Otherwise, emits errors as flash messages and renders the login page again.

        :return: On error, renders the login page, but redirects to value of `next` or home page on success.
        """
        form = LoginForm()
        if not form.validate_on_submit():
            flash(self._messages['invalid_data'])
            return render_template('login.html', form=form)

        user = User.get_by_email(form.email.data)
        if user and user.check_password(form.password.data):
            login_user(user)
            flash(self._messages['success'])
        else:
            flash(self._messages['invalid_auth'])
            return redirect(url_for('base.login'))

        return redirect(request.args.get('next') or url_for('base.front_page'))
Ejemplo n.º 2
0
def standard_login_view(request):
    logout(request)

    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            next = request.GET.get('next', '/')
            login(request, form.cleaned_data['user'])

            user = User.objects.get(id=form.cleaned_data['user'].id)
            # analytics
            analytics_id(
                request,
                user_id=user.id,
                traits={
                    'email':
                    user.email,
                    'name':
                    user.trainer.name if user_type(user) == 'T' else
                    user.client.name if user_type(user) == 'D' else 'spotter',
                    'blitz':
                    '(trainer)' if user_type(user) == 'T' else
                    user.client.get_blitz().title
                    if user_type(user) == 'D' else '(spotter)'
                })
            return redirect(next)

    else:
        form = LoginForm()

    #displays the error but preserves the e-mail address entered
    return render(request, "login.html", {
        'form': form,
    })
Ejemplo n.º 3
0
def login_view(request):
    """ The view of the login page. """
    ANONYMOUS_SESSION = request.session.get("ANONYMOUS_SESSION", False)
    page_name = "Login Page"
    redirect_to = request.GET.get("next", reverse("homepage"))
    if (request.user.is_authenticated() and not ANONYMOUS_SESSION) or (
        ANONYMOUS_SESSION and request.user.username != ANONYMOUS_USERNAME
    ):
        return HttpResponseRedirect(redirect_to)
    form = LoginForm(request.POST or None)
    if form.is_valid():
        user = form.save()
        login(request, user)
        if ANONYMOUS_SESSION:
            request.session["ANONYMOUS_SESSION"] = True
        return HttpResponseRedirect(redirect_to)
    elif request.method == "POST":
        reset_url = request.build_absolute_uri(reverse("reset_pw"))
        messages.add_message(request, messages.INFO, MESSAGES["RESET_MESSAGE"].format(reset_url=reset_url))

    return render_to_response(
        "login.html",
        {"page_name": page_name, "form": form, "oauth_providers": _get_oauth_providers(), "redirect_to": redirect_to},
        context_instance=RequestContext(request),
    )
Ejemplo n.º 4
0
    def post(self, request):
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST['login']
            password = request.POST['password']

            if 'enter' in request.POST:
                user = authenticate(request, username=username, password=password)
                if user is not None:
                    login(request, user)
                    return HttpResponseRedirect(reverse('base'))
                else:
                    error = 'Пользователь с именем {} не зарегистрирован.'.format(username)
                    context = {'form': form, 'error': error}
                    return render(request, 'login.html', context=context)

            elif 'registration' in request.POST:
                new_user = User.objects.create_user(username, '', password)
                new_user.save()
                user = authenticate(request, username=username, password=password)
                if user is not None:
                    login(request, user)
                    return HttpResponseRedirect(reverse('base'))

        else:
            context = {'form': form}
            return render(request, 'login.html', context=context)
Ejemplo n.º 5
0
def login_view(request):
    ''' The view of the login page. '''
    ANONYMOUS_SESSION = request.session.get('ANONYMOUS_SESSION', False)
    page_name = "Login Page"
    redirect_to = request.GET.get('next', reverse('homepage'))
    if (request.user.is_authenticated() and not ANONYMOUS_SESSION) or (ANONYMOUS_SESSION and request.user.username != ANONYMOUS_USERNAME):
        return HttpResponseRedirect(redirect_to)
    form = LoginForm(request.POST or None)
    if form.is_valid():
        user = form.save()
        login(request, user)
        if ANONYMOUS_SESSION:
            request.session['ANONYMOUS_SESSION'] = True
        return HttpResponseRedirect(redirect_to)
    elif request.method == "POST":
        reset_url = request.build_absolute_uri(reverse('reset_pw'))
        messages.add_message(request, messages.INFO,
                             MESSAGES['RESET_MESSAGE'].format(reset_url=reset_url))

    return render_to_response('login.html', {
        'page_name': page_name,
        'form': form,
        'oauth_providers': _get_oauth_providers(),
        'redirect_to': redirect_to,
        }, context_instance=RequestContext(request))
Ejemplo n.º 6
0
def login():
    if not current_user.is_anonymous:
        return redirect(
            request.args.get("next") or url_for(".index", _external=True))
    form = LoginForm()
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        user = None
        try:

            user = mongo.db.user.find_one({"username": username})
        except MultipleResultsFound as e:
            # TODO: deal with MultipleResultsFound
            pass
        # password_match = bcrypt.checkpw(password.encode(), user.password.encode())
        if user is None:
            flash(u"帐号或密码出错", category="danger")
            return render_template("base/login.html", form=form)
        user = User(user["username"])
        login_user(user, form.remember_me.data)
        identity_changed.send(current_app._get_current_object(),
                              identity=Identity(user.username))
        return redirect(
            request.args.get("next") or url_for(".index", _external=True))
    return render_template("base/login.html", form=form)
Ejemplo n.º 7
0
    def post(self):
        """
        Handles the HTTP POST requests (overriding :meth:`MethodView.post`) .

        If the form was correctly filled and the user password validates
        (through :meth:`~base.models.User.check_password`),
        calls :func:`flask.ext.login.login_user`,
        emits a flash message of success and redirects the request to
        the `next` parameter or the home page if not specified.

        Otherwise, emits errors as flash messages and renders the login page again.

        :return: On error, renders the login page, but redirects to value of `next` or home page on success.
        """
        form = LoginForm()
        if not form.validate_on_submit():
            flash(self._messages['invalid_data'])
            return render_template('login.html', form=form)

        user = User.get_by_email(form.email.data)
        if user and user.check_password(form.password.data):
            login_user(user)
            flash(self._messages['success'])
        else:
            flash(self._messages['invalid_auth'])
            return redirect(url_for('base.login'))

        return redirect(request.args.get('next') or url_for('base.front_page'))
Ejemplo n.º 8
0
    def login(self,request):
        loginForm=LoginForm(request.POST)
        if loginForm.is_valid():
             username = loginForm.cleaned_data['username']
             password = loginForm.cleaned_data['password']
             remember = loginForm.cleaned_data['remember']
             username=username.strip()
             password=password.strip()
             user = authenticate(username=username, password=password)

             if user is not None:
                if user.is_active:  # 登录成功
                    loginLog=UserLoginLog()
                    loginLog.uid=user.id
                    loginLog.src_uuid=username
                    loginLog.login_time=datetime.now()
                    if request.META.has_key('REMOTE_ADDR'):
                        loginLog.ip=request.META['REMOTE_ADDR']
                    elif request.META.has_key('REMOTE_HOST'):
                        loginLog.ip=request.META['REMOTE_HOST']
                    loginLog.src=0
                    loginLog.port=0 #todo
                    loginLog.save()

                    login(request,user)
                    return {'result':'success'}
                else:
                    return {'result':'failed','login_failed':'true'}
             else:
                return {'result':'failed','login_failed':'true'}
        else:
             result={'result':'failed'}

             #result.update(loginForm.errors)
             return result
Ejemplo n.º 9
0
def login_view(request):
    ''' The view of the login page. '''
    ANONYMOUS_SESSION = request.session.get('ANONYMOUS_SESSION', False)
    page_name = "Login Page"
    redirect_to = request.GET.get('next', reverse('homepage'))
    if (request.user.is_authenticated() and not ANONYMOUS_SESSION) or (
            ANONYMOUS_SESSION and request.user.username != ANONYMOUS_USERNAME):
        return HttpResponseRedirect(redirect_to)
    form = LoginForm(request.POST or None)
    if form.is_valid():
        user = form.save()
        login(request, user)
        if ANONYMOUS_SESSION:
            request.session['ANONYMOUS_SESSION'] = True
        return HttpResponseRedirect(redirect_to)
    elif request.method == "POST":
        reset_url = request.build_absolute_uri(reverse('reset_pw'))
        messages.add_message(
            request, messages.INFO,
            MESSAGES['RESET_MESSAGE'].format(reset_url=reset_url))

    return render_to_response('login.html', {
        'page_name': page_name,
        'form': form,
        'oauth_providers': _get_oauth_providers(),
        'redirect_to': redirect_to,
    },
                              context_instance=RequestContext(request))
Ejemplo n.º 10
0
def login(request):
    def errorHandle(error):
        context_new = {
            'error': error,
            'form': LoginForm(),
        }
        return render_to_response('base/login.html', context_new, RequestContext(request))

    if request.method == 'POST': # If the form has been submitted...
        form = LoginForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            username_or_email = request.POST['username_or_email']
            password = request.POST['password']
            user = auth.authenticate(username=username_or_email, password=password)
            if user is not None:
                if user.is_active:
                    # Redirect to a success page.
                    auth.login(request, user)
                    return redirect('/collection/')
                else:
                    # Return a 'disabled account' error message
                    error = u'account disabled'
                    return errorHandle(error)
            else:
                # Return an 'invalid login' error message.
                error = u'invalid login'
                return errorHandle(error)
        else:
            error = u'form is invalid'
            return errorHandle(error)
    else:
        context = {
            'form': LoginForm()
        }
        return render_to_response('base/login.html', context, RequestContext(request))
Ejemplo n.º 11
0
 def test_login_form_valid(self):
     form = LoginForm()
     form_widget_attrs = {
         'class': 'form-control',
         'name': 'username',
         '1': '1'
     }
     form.fields['password'].widget.attrs = form_widget_attrs
     self.assertFalse(form.is_valid())
Ejemplo n.º 12
0
Archivo: views.py Proyecto: daret07/tp
def login(request):
    from base.forms import LoginForm

    form = LoginForm(request.POST or None)

    if form.is_valid():
        username = form.cleaned_data['usuario']
        password = form.cleaned_data['contrasena']

        try:
            user = authenticate(username=username, password=password)
        except:
            form.add_error(
                'usuario',
                'Usuario y/o contraseña incorrectos, verifiquelo e intente nuevamente.'
            )
            user = None

        if user is not None:
            if user.is_active:
                login_django(request, user)
                return redirect('index')
            else:
                form.add_error(
                    'usuario',
                    'El usuario se encuentra inactivo, contacte con su administrador.'
                )
        else:
            if not form._errors.has_key('usuario'):
                form.add_error(
                    'usuario',
                    'Usuario y/o contraseña incorrectos, verifiquelo e intente nuevamente.'
                )

    return TemplateResponse(request, 'core/login.html', {'form': form})
Ejemplo n.º 13
0
def login():
    login_form = LoginForm(request.form)
    if login_form.validate_on_submit():
        user = User.objects(email=login_form.email.data).first()
        if user and user.check_password(login_form.password.data):
            login_user(user)
            return redirect(request.args.get("next") or url_for('dashboard._dashboard'))
        else:
            flash("Login failed.", "login_error")
            # login is not valid
            return redirect('#create')
    return render_template('index.html', login_form=login_form, create_form=CreateAccountForm())
Ejemplo n.º 14
0
def login():
    login_form = LoginForm(request.form)
    if login_form.validate_on_submit():
        user = User.objects(email=login_form.email.data).first()
        if user and user.check_password(login_form.password.data):
            login_user(user)
            return redirect(request.args.get("next") or url_for('dashboard._dashboard'))
        else:
            flash("Login failed.", "login_error")
            # login is not valid
            return redirect('#create')
    return render_template('index.html',
                           login_form=login_form,
                           create_form=CreateAccountForm())
Ejemplo n.º 15
0
def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            login_info = form.cleaned_data
            user = auth.authenticate(username=login_info.get('username'),
                                     password=login_info.get('password'))
            if user is not None:
                logging.info("id:%, username:& login system" %
                             (user.id, user.username))
                return Json().http_response()
            else:
                return Json().http_response(success=False, msg='用户名或密码不正确')
    return Json().http_response(success=False, msg="请求错误,get方法不允许")
Ejemplo n.º 16
0
def sign_in(request):
    if request.method == "POST":
        form = LoginForm(request.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("/")
        else:
            return render(request, "login.html", {"form": form})
    else:
        form = LoginForm()
        return render(request, "login.html", {"form": form})
Ejemplo n.º 17
0
    def post(self):
        form = LoginForm()
        if not form.validate_on_submit():
            flash(self._messages['invalid_form'])
            return render_template('login.html', form=form)

        user = User.get_by_email(form.email.data)
        if user and user.check_password(form.password.data):
            login_user(user)
            flash(self._messages['success'])
        else:
            flash(self._messages['invalid_auth'])
            return redirect(url_for('base.login'))

        return redirect(request.args.get('next') or url_for('base.front_page'))
Ejemplo n.º 18
0
    def post(self):
        form = LoginForm()
        if not form.validate_on_submit():
            flash(self._messages['invalid_form'])
            return render_template('login.html', form=form)

        user = User.get_by_email(form.email.data)
        if user and user.check_password(form.password.data):
            login_user(user)
            flash(self._messages['success'])
        else:
            flash(self._messages['invalid_auth'])
            return redirect(url_for('base.login'))

        return redirect(request.args.get('next') or url_for('base.front_page'))
Ejemplo n.º 19
0
 def get(self, request, *args, **kwargs):
     signup_form = RegistrationForm(self.request.GET, prefix='signup_form')
     login_form = LoginForm(self.request.GET, prefix='login_form')
     context = self.get_context_data(**kwargs)
     context['signup_form'] = signup_form
     context['login_form'] = login_form
     return render(request, self.template_name, context)
Ejemplo n.º 20
0
def home():
    print "config.AUTHENTICATE {}".format(config.AUTHENTICATE)
    if config.AUTHENTICATE:
        return render_template('index.html',
                               login_form=LoginForm(),
                               create_form=CreateAccountForm())
    else:
        email = 'default'
        password = '******'
        access_key_id = config.AWS_ID
        secret_access_key = config.AWS_KEY
        aws_bucket_name = config.AWS_BUCKET_NAME
        next_backend_global_host = config.NEXT_BACKEND_GLOBAL_HOST
        if not User.objects(email=email):
            user = User(email=email,
                        access_key_id=access_key_id,
                        secret_access_key=secret_access_key,
                        aws_bucket_name=aws_bucket_name,
                        next_backend_global_host=next_backend_global_host)
            user.set_password(password)
            user.save()
        else:
            user = User.objects(email=email).first()
        login_user(user, remember=True)
        return redirect(url_for('dashboard._dashboard'))
Ejemplo n.º 21
0
 def get(self, request):
     if not request.user.is_authenticated:
         form = LoginForm()
         context = {'form': form}
         return render(request, 'login.html', context=context)
     else:
         return HttpResponseRedirect(reverse('base'))
Ejemplo n.º 22
0
Archivo: views.py Proyecto: h3l/hexyou
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=auth.authenticate(username=username,password=password)
            if user!=None:
                auth.login(request,user)
                if request.GET and request.GET.has_key('next'):
                    return redirect(request.GET['next'])
                return redirect('/members/%s/' % user.username)
            else:
                return render_to_response('accounts/login.html',context_instance=RequestContext(request))
    else: form=LoginForm()
    return render_to_response('accounts/login.html',{'form':form},context_instance=RequestContext(request))
Ejemplo n.º 23
0
    def post(self, request):
        if ('login' in request.POST):
            form = LoginForm(request.POST)
            if form.is_valid():
                user = form.login(request)
                if user:
                    login(request, user)
                    if is_caregiver(user):
                        caregiver = CareGiver.objects.get(user=user)
                        elders = Elder.get_cared_elder(caregiver)
                        if elders:
                            request.session['active_elder'] = elders[0].id
                        else:
                            request.session['active_elder'] = 0
                        return self.caregiver(request)
                    else:
                        return self.partner(request)
            else:
                return render(request, 'login.html',
                              {'error_login': form.errors})

        elif ('signup' in request.POST):
            userform = UserForm(request.POST)
            caregiverform = CareGiverForm(request.POST)
            # return reverse(request.POST['gender'])
            if userform.is_valid() and caregiverform.is_valid():
                user = userform.save(commit=False)
                user.set_password(userform.cleaned_data.get('password'))
                user.save()
                caregiver = caregiverform.save(commit=False)
                caregiver.user = user
                caregiver.save()
                g = Group.objects.get(name='CareGiver')
                g.user_set.add(user)
                return render(
                    request, 'login.html',
                    {'success': "Pendaftaran Berhasil, silahkan login"})
            else:
                userform.errors.update(caregiverform.errors)
                return render(request, 'login.html', {
                    'error_signup': userform.errors,
                    'values': request.POST
                })
        else:
            return render(request, 'login.html')
Ejemplo n.º 24
0
 def post(self, request):
     action = self.request.POST['action']
     if action == 'signup':
         signup_form = RegistrationForm(data=request.POST, prefix='signup_form')
         if signup_form.is_valid():
             user = signup_form.save(commit=False)
             user.is_active = False
             user.save()
             current_site = get_current_site(request)
             email = signup_form.cleaned_data['email']
             template = get_template('email.html')
             email_message = f'Welcome to code convert'
             send_mail(
                 subject='Activate your account',
                 message=email_message,
                 html_message=template.render(context={
                     'user': user,
                     'domain': current_site.domain,
                     'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                     'token': account_activation_token.make_token(user),
                 }),
                 from_email='Code convert',
                 recipient_list=[email]
             )
             return JsonResponse({"status": 200})
         else:
             return JsonResponse({"errors": json.dumps(signup_form.errors)}, status=400)
     elif action == 'login':
         login_form = LoginForm(data=request.POST, prefix='login_form')
         if login_form.is_valid():
             user = authenticate(
                 self.request,
                 username=login_form.cleaned_data['username'],
                 password=login_form.cleaned_data['password']
             )
             if user is not None:
                 if user.is_active:
                     login(self.request, user)
                     return JsonResponse({"status": 200})
                 else:
                     return JsonResponse({"error": "Disabled account"}, status=403)
             else:
                 return JsonResponse({"error": "invalid login or password"}, status=400)
         else:
             return JsonResponse({"error": json.dumps(login_form.errors)}, status=400)
Ejemplo n.º 25
0
 def post(self, request,*args, **kwargs):
     loginForm=LoginForm(request.POST)
     if loginForm.is_valid():
          username = loginForm.cleaned_data['username']
          password = loginForm.cleaned_data['password']
          remember = loginForm.cleaned_data['remember']
          user = authenticate(username=username, password=password)
          if user is not None:
             if user.is_active:  # 登录成功
                 login(request,user)
                 c = {'result':'success'}
             else:
                 c={'login_failed':'true'}
          else:
             c={'login_failed':'true'}
     else:
          c=loginForm.errors
     return self._get_json_respones(c)
Ejemplo n.º 26
0
def login(request):
    message = ""
    form = LoginForm(request.POST or None)  # 获取登录表单样式
    if request.method == "POST":
        if form.is_valid():
            cd = form.cleaned_data
            input_name = cd['username']
            input_pwd = cd['password']
            url = request.POST['url']
            # print(url)
            user = authenticate(username=input_name, password=input_pwd)
            if user is not None and user.is_active:
                auth.login(request, user)
                return redirect('/')
            else:
                message = '用户名或密码不正确'
                print(message)

    return render(request, 'login.html', {'form': form, 'message': message})
Ejemplo n.º 27
0
def login_view(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            print(username)
            password_raw = form.cleaned_data.get('password')
            print(password_raw)
            user = authenticate(username=username, password=password_raw)
            if user is not None:
                login(request, user)
                print(user)
                return redirect(reverse('home'))
            else:
                print(form.errors)
                return redirect(reverse('signup-class-view'))
    else:
        form = LoginForm()
    return render(request, 'login.html', {'form': form})
Ejemplo n.º 28
0
def loginView(request):
    # if user is already logged in, send directly to homepage
    if request.user.is_authenticated():
        return redirect('/')

    # form validation handles authenticating user
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            authed_user = authenticate(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password']
            )
            login(request, authed_user)
            return HttpResponseRedirect('/')
    else:
        form = LoginForm()

    return render(request, 'base/login.html', {
        'form': form
    })
Ejemplo n.º 29
0
def signupsubmit(request, data):
    registration_status, registration_message = save_registration_form(data)
    if registration_status:
        user_data = {
            'username': str(data.username),
            'password': str(data.password)
        }
        form = LoginForm(user_data)
        return render(request, 'login.html', {'form': form})
    messages.error(
        request,
        'Sorry! Unable to register. Reason: %s' % registration_message)
    return redirect('/account/user/signup')
Ejemplo n.º 30
0
def do_login(request):
    if request.method=='POST':
        loginForm=LoginForm(request.POST)
        if loginForm.is_valid():
            username=loginForm.cleaned_data['username']
            password=loginForm.cleaned_data['password']
            user=authenticate(username=username,password=password)
            if user is not None:
                if user.is_active: #登录成功
                    login(request,user)
                    return HttpResponseRedirect('/setup')
                else:
                    return __render_login(request, loginForm,msg="用户帐号被禁用!")
            else:
                return __render_login(request, loginForm,msg="用户名或密码错误!")
        else:
            return __render_login(request,loginForm)
    else:
        pass
    
    loginForm=LoginForm()
    return __render_login(request, loginForm)
Ejemplo n.º 31
0
def landing(request):
    if request.method == 'GET':
        if 'invite' in request.GET and request.GET['invite']:
            invite = Invite.objects.get(pk=request.GET['invite'])
            form = ServiceForm(initial={'invite': str(invite.pk)})
            login = LoginForm(initial={'forgot': False})

            data = dict(invite=invite,
                        pop=True,
                        form=form,
                        login=login,
                        chapter=invite.chapter)
        else:
            login = LoginForm(initial={'forgot': False})
            data = {'login': login}

    elif request.method == 'POST':
        login = LoginForm(initial={'forgot': False})
        if 'invite' in request.POST:
            try:
                invite = Invite.objects.get(pk=request.POST['invite'])
            except Invite.DoesNotExist:
                invite = None
                chapter = None
            else:
                if 'service' in request.POST:
                    invite.category = request.POST['service']
                    invite.save()
                chapter = invite.chapter

            data = dict(invite=invite, pop=False, login=login, chapter=chapter)

        else:
            data = dict(pop=False, login=login)

    return render_to_response('organizer/or_landing.html',
                              data,
                              context_instance=RequestContext(request))
Ejemplo n.º 32
0
def login_view(request):
    ''' The view of the login page. '''
    ANONYMOUS_SESSION = request.session.get('ANONYMOUS_SESSION', False)
    page_name = "Login Page"
    redirect_to = request.REQUEST.get('next', reverse('homepage'))
    if (request.user.is_authenticated() and not ANONYMOUS_SESSION) or (ANONYMOUS_SESSION and request.user.username != ANONYMOUS_USERNAME):
        return HttpResponseRedirect(redirect_to)
    form = LoginForm(request.POST or None)
    if form.is_valid():
        username_or_email = form.cleaned_data['username_or_email']
        password = form.cleaned_data['password']
        username = None
        if username == ANONYMOUS_USERNAME:
            return red_ext(request, MESSAGES['ANONYMOUS_DENIED'])
        temp_user = None
        try:
            temp_user = User.objects.get(username=username_or_email)
            username = username_or_email
        except User.DoesNotExist:
            try:
                temp_user = User.objects.get(email=username_or_email)
                username = User.objects.get(email=username_or_email).username
            except User.DoesNotExist:
                form.errors['__all__'] = form.error_class(["Invalid username/password combination. Please try again."])
        if temp_user is not None:
            if temp_user.is_active:
                user = authenticate(username=username, password=password)
                if user is not None:
                    login(request, user)
                    if ANONYMOUS_SESSION:
                        request.session['ANONYMOUS_SESSION'] = True
                    return HttpResponseRedirect(redirect_to)
                else:
                    reset_url = request.build_absolute_uri(reverse('reset_pw'))
                    messages.add_message(request, messages.INFO, MESSAGES['RESET_MESSAGE'].format(reset_url=reset_url))
                    form.errors['__all__'] = form.error_class([MESSAGES['INVALID_LOGIN']])
                    time.sleep(1) # Invalid login - delay 1 second as rudimentary security against brute force attacks
            else:
                form.errors['__all__'] = form.error_class(["Your account is not active. Please contact the site administrator to activate your account."])

    return render_to_response('login.html', {
        'page_name': page_name,
        'form': form,
        'oauth_providers': _get_oauth_providers(),
        'redirect_to': redirect_to,
        }, context_instance=RequestContext(request))
Ejemplo n.º 33
0
def sponsor(request, slug):
    if len(slug) <= 2:
        return HttpResponseRedirect(reverse('homepage'))

    try:
        chapter = Chapter.objects.get(slug=slug)
    except Chapter.DoesNotExist:
        return HttpResponseRedirect(reverse('homepage'))
    """ If you want to keep track uncomment, but every crawler will create an invite
    invite = Invite( chapter = chapter )
    invite.save()
    form = ServiceForm( initial = {'invite': str(invite.pk)} )
    data = dict(chapter = chapter, pop = True, invite = invite, form = form )
    """
    form = LoginForm(initial={'forgot': False})
    data = dict(chapter=chapter, pop=False, login=form)
    return render_to_response('organizer/or_landing.html',
                              data,
                              context_instance=RequestContext(request))
Ejemplo n.º 34
0
def Login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST['username']
            password = request.POST['password']
            user = User()
            name = [username]
            if user.is_exist():
                return render(request, 'base/exists.html', {'name': name})
            else:
                return render(request, 'base/form.html')
        else:
            form = LoginForm()
        return render(request, 'base/login.html')
    else:
        form = ContactForm()
        return render(request, 'base/form.html', {'form': form})
Ejemplo n.º 35
0
def create():
    create_form = CreateAccountForm(request.form)
    if create_form.validate_on_submit():
        print "form data",create_form.new_email.data
        new_email = create_form.new_email.data
        new_password = create_form.new_password.data
        confirm_password = create_form.confirm_password.data
        print User.objects()
        if User.objects(email=new_email).count() == 0:
            if new_password == confirm_password:
                # Set the hashed password on the user.
                user = User(email=new_email)
                user.set_password(new_password)
                user.save()
                login_user(user, remember=True)
                return redirect(url_for('dashboard._dashboard'))
            else:
                flash("Passwords don't match!", "create_error")
                return redirect('#create')    
        else:
            flash("Username exists!", "create_error")
            return redirect('#create')
    # login form is not valid
    return render_template('index.html', login_form=LoginForm(), create_form=create_form)
Ejemplo n.º 36
0
 def test_login_form_max_length_field(self):
     form = LoginForm()
     self.assertTrue(form.fields['password'].widget.attrs['maxlength'], 30)
Ejemplo n.º 37
0
def login(request, methods="GET"):
    form = LoginForm()
    return render(request, 'login.html', {'form': form})
Ejemplo n.º 38
0
 def get(self):
     """
     Handles the HTTP GET requests (overriding :meth:`MethodView.get`) .
     :return: The rendered login form page.
     """
     return render_template('login.html', form=LoginForm())
Ejemplo n.º 39
0
 def test_login_form_username_field(self):
     form = LoginForm()
     self.assertTrue(form.fields['username'].label == None
                     or form.fields['username'].label == 'Username')
Ejemplo n.º 40
0
 def test_login_form_password_field(self):
     form = LoginForm()
     self.assertTrue(form.fields['password'].label == None
                     or form.fields['password'].label == 'Password')
Ejemplo n.º 41
0
 def get(self):
     return render_template('login.html', form=LoginForm())