示例#1
0
def login_user(request):
    if request.method == 'GET':
        return redirect("anon-landing")

    if request.user.is_authenticated:
        return HttpResponseNotAllowed()

    form = LoginForm(request.POST)
    if not form.is_valid():
        data = {
            "loginerror": "invalid email/password",
        }
        return render(request, 'anon_landing.html', data)

    user = authenticate(request,
                        username=form.cleaned_data['email'],
                        password=form.cleaned_data['password'])

    if user is not None:
        login(request, user)
        return redirect('app-landing')
    else:
        data = {
            "loginerror": "invalid email/password",
            "loginemail": form.cleaned_data['email'],
        }
        return render(request, 'anon_landing.html', data)
示例#2
0
def login(request):
    from django.contrib.auth import login as auth_login, REDIRECT_FIELD_NAME
    from website.forms import LoginForm
    redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, '')
    if request.method == "POST":
        form = LoginForm(data=request.POST)
        if form.is_valid():
            user = form.get_user()
            if not redirect_to or ' ' in redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL
            elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
                redirect_to = settings.LOGIN_REDIRECT_URL

            if not form.cleaned_data['remember']:
                request.session.set_expiry(0)

            auth_login(request, user)

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

            return redirect(redirect_to)
    else:
        form = LoginForm(request)
    request.session.set_test_cookie()
    return render(request, 'login.html',
        {'form': form, REDIRECT_FIELD_NAME: redirect_to})
示例#3
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user=User.query.filter_by(email=form.email.data).first()
        login_user(user, form.remember_me.data)
        return redirect(url_for('.front_index'))
    return render_template('login.html',form=form)
示例#4
0
def login_view(request):
    '''Handle login

    If login is successful redirect to welcome page
    if not it redirects to other pages accordingly

    Keyword arguments:
    request -- request from client
    '''
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect('welcome')
                else:
                    return redirect('thanks')
            else:
                return redirect('thanks')
            return HttpResponseRedirect('thanks')
    else:
        form = LoginForm()

    return render(request, 'home.html', {
        'form': form,
    })
示例#5
0
def login(request):
    if request.method == "POST":
        login_form = LoginForm(request.POST)
        if login_form.isvalid():
            pass
    else:
        login_form = LoginForm()
示例#6
0
 def test_restaurant_is_found(self):
     database = Restaurant.objects.create(restaurant_name='restaurant',
                                          restaurant_username='******',
                                          restaurant_password='******')
     form = LoginForm()
     form.fields['restaurantsearch'] = 'exist'
     matching_restaurants = Restaurant.objects.filter(
         restaurant_name__icontains=form.fields['restaurantsearch'])
     # comparing the database's restaurant name with the inputted restaurant name
     self.assertNotEqual(matching_restaurants,
                         form.fields['restaurantsearch'])
示例#7
0
 def test_password_doesnt_match(self):
     database = Restaurant.objects.create(restaurant_name='restaurant',
                                          restaurant_username='******',
                                          restaurant_password='******')
     form = LoginForm()
     form.fields['restaurantname'] = 'restaurant'
     form.fields['username'] = '******'
     form.fields['password'] = '******'
     # comparing the database's username with the inputted username
     self.assertNotEqual(getattr(database, 'restaurant_password'),
                         form.fields['password'])
示例#8
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.email.data == '*****@*****.**' and form.password == 'passwordTEMP':
            flash(f'You have been logged in!', 'success')
            return redirect(url_for('home'))
        else:
            flash(
                f'Sorry, your password was incorrect. Please double-check your password.',
                'danger')

    return render_template('login.html', title='Login', form=form)
示例#9
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(user.password, form.password.data):
            login_user(user, remember=form.remember.data)
            next_page = request.args.get('next')
            return redirect(next_page) if next_page else redirect(url_for('home'))
        else:
            flash('Login Unsuccessful. Please check email and password', 'danger')
    return render_template('login.html', title='Login', form=form)
示例#10
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if not user or not user.check_password(form.password.data):
            flash('Invalid credentials.')
            return redirect(url_for('login'))
        login_user(user)
        if user.role == 'admin':
            return redirect(url_for('user_page'))
        else:
            return redirect(url_for('exam_page'))
    return render_template('users/login.html', form=form)
示例#11
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if not user or not user.check_password(form.password.data):
            flash('Invalid credentials.')
            return redirect(url_for('login'))
        login_user(user)
        if user.role == 'admin':
            return redirect(url_for('user_page'))
        else:
            return redirect(url_for('exam_page'))
    return render_template('users/login.html', form=form)
示例#12
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    login_form = LoginForm()
    if login_form.validate_on_submit():
        user = User.query.get(login_form.email_or_username.data) or \
                User.query.filter_by(email=login_form.email_or_username.data).first()
        if user and bcrypt.check_password_hash(user.password,
                                               login_form.password.data):
            login_user(user, force=True)
            return redirect(url_for('home'))
        flash('Login failed. Please check your username/email and password.')
    return render_template('login-page.html', form=login_form)
示例#13
0
def login_view(request):
    """View function for logging in."""
    #is user already logged in?
    if request.user.is_authenticated:
        messages.error(request,
                       _('You are already logged in.'),
                       extra_tags='alert alert-warning')
        return HttpResponseRedirect(
            request.GET.get('next', reverse('surveys-dashboard')))

    #If we receive POST data
    if request.method == 'POST':
        # Create a form instance and populate it with data from the request (binding it):
        form = LoginForm(request.POST)
        context = {
            'submit_button_text': _('Login'),
            'back_button_text': _('Cancel'),
            'show_back_button': False,
            'form': form,
        }
        # Check if the form is valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(request, username=username, password=password)
            if user is not None:
                auth.login(request, user)
                request.user.organization.update_subscription_paid_until()
                messages.success(request,
                                 _('You have logged in.'),
                                 extra_tags='alert alert-success')
                #mark an event - user logged in
                event = Event(category='completed_log_in',
                              user=request.user,
                              comment=None)
                event.save()

                return HttpResponseRedirect(request.GET.get('next', '/'))
    else:
        #make context
        form = LoginForm
        context = {
            'submit_button_text': _('Login'),
            'back_button_text': _('Cancel'),
            'show_back_button': False,
            'form': form,
        }
    return render(request, 'login_form.html', context)
示例#14
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('account'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password', 'danger')
            return redirect(url_for('login'))
        login_user(user)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('home')
        return redirect(next_page)
    return render_template('login.html', title="Log In", form=form)
示例#15
0
def login(req):
    if req.method == 'POST':
        form = LoginForm(req.POST)
        if form.is_valid():
            user = User.objects.filter(email=form.cleaned_data['email'],
                                       password=form.cleaned_data['password'])\
                               .first()
            if not user:
                error = 'invalid email or password.'
            else:
                error = 'You have logged in successfully'
                req.session['email'] = form.cleaned_data['email']
                return redirect('/profile')
    form = LoginForm()
    return render(req, 'login.html', locals())
示例#16
0
def ajax_login(request):
    """ AJAX login procedure """
    if request.method != 'POST':
        return HttpResponse("NOTFOUND")

    login_form = LoginForm(request.POST)
    if login_form.is_valid():
        username = login_form.cleaned_data['username']
        password = login_form.cleaned_data['password']
        try:
            user = authenticate(username=username, password=password)
            login(request, user)
        except Exception, e:
            return HttpResponse("CANT")
        return HttpResponse("OK")
示例#17
0
 def get(self, request: Request, *args: object,
         **kwargs: object) -> HttpResponse:
     """Retrieve the rendered login form."""
     form = LoginForm()
     context = get_additional_context({"form": form, "slim_form": True})
     if next_path := request.GET.get("next", None):
         context.update({"next": next_path})
示例#18
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.get_by_username(form.login.data)
        if user is None:
            form.login.errors.append("Такого пользователя не существует")
            return render_template("login.html", form=form)
        if not check_password_hash(user.password_hash, form.password.data):
            form.password.errors.append("Неправильный пароль")
            return render_template("login.html", form=form)
        session["user_name"] = user.name
        session["role"] = user.role
        session["blocked"] = user.blocked
        return redirect("/")

    return render_template("login.html", form=form)
示例#19
0
def login():
    context = global_context()
    if current_user:
        if current_user.is_authenticated:
            return redirect(url_for('home'))
    form = LoginForm()
    if request.method == 'POST':
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            if not user.is_validated:
                flash(
                    Markup(
                        f'Bitte bestätige erst deine Account, über den Link aus der Email. \n<a href="{url_for("resend_confirmation_link",email=user.email)}">Nochmal zusenden</a>'
                    ), 'danger')
                return redirect(url_for('home'))
            if user and bcrypt.check_password_hash(user.password,
                                                   form.password.data):
                login_user(user, remember=form.remember.data)
                next_page = request.args.get('next', 'home')
                flash(f'Willkommen {current_user.firstname}.', 'success')
                return redirect(url_for(next_page.strip('/')))
        flash(
            'Das hat nicht geklappt. Email oder Password sind nicht korrekt.',
            'danger')
    context['form'] = form
    context['title'] = 'Einloggen'
    return render_template('login.html', **context)
示例#20
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    with open('config.json') as f:
        data = json.load(f)
    if form.validate_on_submit():
        if form.password.data == data['password']:
            user = User()
            user.id = "Rick"
            login_user(user, remember=True)
            flash('Successfully logged in!', 'success')
            return redirect(url_for('home'))
        else:
            flash('Incorrect password!', 'danger')
    return render_template('login.html', form=form, data=data)
示例#21
0
    def post(self, request: Request, *args: object,
             **kwargs: object) -> HttpResponseRedirect:
        """Post the response to the login form."""
        form = LoginForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            if user := EmailBackend().authenticate(
                    username=data.get("email"), password=data.get("password")):
                login(request, user)

                if request.GET.get("next", None):
                    location = request.GET.get("next")
                else:
                    location = "/"

                return HttpResponseRedirect(location)
            return HttpResponseRedirect(request.build_absolute_uri())
示例#22
0
def auth_login(request):
    form = LoginForm()
    if request.method == 'GET':
        return render(request, 'website/login.html', {'form': form})
    elif request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.data['email']
            password = form.data['password']
            user = authenticate(email=email, password=password)
            if user is not None and user.is_active:
                login(request, user)
                return redirect("/account")
            else:
                return render(request, 'website/login.html',{'form': form})
        else:
            return render(request, 'website/login.html',{'form': form})
示例#23
0
def dashboard_login(request):
    context = RequestContext(request)
    if context.get('user').is_authenticated():
        return redirect('index')

    if request.method == "POST":
        form_login = LoginForm(request.POST)
        if form_login.validate():
            user = form_login.get_user()
            login(request, user)
            if request.POST.get('remember', None):
                request.session.set_expiry(0)
            return redirect('index')
    else:
        form_login = LoginForm()
    context.update({'form_login': form_login})
    return render_to_response('login.html',
                              context_instance=context)
示例#24
0
def login(req):
    error = None
    if req.method == 'POST':
        form = LoginForm(req.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(req, username=username, password=password)
            if user is not None:
                auth_login(req, user)
                return HttpResponseRedirect('/')
            else:
                error = 'Niepoprawne dane logowania!'
    template = loader.get_template('login.html')
    context = {
        'error': error
    }
    return HttpResponse(template.render(context, req))
示例#25
0
def login_user(request):
    # form = LoginForm(request.POST or None)
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(username=request.POST['username'],
                                password=request.POST['password'])
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect('/home/')
                else:
                    return HttpResponse('Disabled account')
        else:
            return HttpResponse('Invalid Login')
    else:
        form = LoginForm()
    context = {'formulario': form}
    return render(request, 'login.html', context)
示例#26
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, "website/login.html", {'form': form})
示例#27
0
def login(request):
    """
    Login view.
    """
    form = LoginForm(data=request.POST)

    if form.is_valid():
        data = {
            'username': form.cleaned_data['username'],
            'password': form.cleaned_data['password']
        }
        client = Communicator()
        cookies = client.login(data)

        if 'sessionid' in cookies:
            response = HttpResponseRedirect(reverse('dashboard'))
            response.set_cookie('sessionid', cookies['sessionid'])
            return response

        return HttpResponseRedirect(reverse('index'))
    return HttpResponseRedirect(reverse('index'))
示例#28
0
def login(request):
    """
    Login view.
    """
    form = LoginForm(data=request.POST)

    if form.is_valid():
        data = {
            'username': form.cleaned_data['username'],
            'password': form.cleaned_data['password']
        }
        client = Communicator()
        cookies = client.login(data)

        if 'sessionid' in cookies:
            response = HttpResponseRedirect(reverse('dashboard'))
            response.set_cookie('sessionid', cookies['sessionid'])
            return response

        return HttpResponseRedirect(reverse('index'))
    return HttpResponseRedirect(reverse('index'))
示例#29
0
文件: auth.py 项目: OReznyk/MHA
def login():
    # if user already logged in -> logout to login
    if current_user.is_authenticated:
        flash('חייבים להתנתק בכדי להכנס מחדש', 'error')
        return redirect(url_for("views.dashboard"))
    else:
        form = LoginForm()
        if form.validate_on_submit():
            # Get user from db
            user = User.query.filter_by(email=form.email.data).first()
            # Checking pwd
            if user and bcrypt.check_password_hash(user.password, form.password.data):
                login_user(user, remember=form.remember.data)
                #session.permanent = True
                #session['user'] = user
                # if user get here from page that needed authentication -> redirect to that page
                next_page = request.args.get('next')
                return redirect(next_page) if next_page else redirect(url_for('views.dashboard'))
            else:
                flash('הוכנסו נתונים לא נכונים', 'error')
    return render_template('login.html', form=form)
示例#30
0
def login_view(request):
    """View function for logging in."""
    #is user already logged in?
    if request.user.is_authenticated:
        messages.error(request, 'You are already logged in.', extra_tags='alert alert-warning')
        return HttpResponseRedirect(request.GET.get('next', reverse('dashboard')))

    #If we receive POST data
    if request.method == 'POST':
        # Create a form instance and populate it with data from the request (binding):
        form = LoginForm(request.POST)
        context = {
            'submit_button_text': 'Login',
            'form': form,
            }
        # Check if the form is valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required (here we just write it to the model due_back field)
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            #print("username was: %s and password: "******"user was not none")
                auth.login(request, user)
                #print("user is: %s" % request.user)
                #print("user is authenticated?: %s" % request.user.is_authenticated)
                messages.success(request, 'You have logged in.', extra_tags='alert alert-success')
                return HttpResponseRedirect(request.GET.get('next', '/'))
            else:
                #i don't see this happening, as my form validation should take care of this
                messages.error(request, "Username and password did not match, please try again.", extra_tags='alert alert-warning')
    else:
        #make context
        form = LoginForm
        context = {
            'submit_button_text': 'Login',
            'form': form,
            }
    return render(request, 'login_form.html', context)
示例#31
0
def login():
    print(count)
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    title = 'Log In'
    if form.validate_on_submit():
        #Query by email to see if it exists in db to login
        username = user_list.query.filter_by(
            username=form.username.data).first()
        if username and bcrypt.check_password_hash(username.password,
                                                   form.password.data):
            login_user(username, remember=form.remember.data)

            #If a page accessible only to logged in users is accessed before logging in
            next_page = request.args.get('next')
            flash('Successfully logged in!', category='success')
            return redirect(next_page) if next_page else redirect(
                url_for('home'))
        else:
            flash('Incorrect email or password', 'danger')
    return render_template('login.html', title=title, form=form)
示例#32
0
def login():
    form = LoginForm()

    if current_user.is_authenticated:
        print(
            'Authenticated user attempting to login. Redirecting to index.html...'
        )
        return redirect(url_for('index'))

    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None:
            return redirect(url_for('login'))

        if validate_password(form.password.data, user.hash_pw) == False:
            # TODO: Flash
            return redirect(url_for('login'))

        print('Succesfully logged in!')
        login_user(user)
        return redirect(url_for('index'))

    return render_template('login.html', form=form)
def login():
    if 'user' in session:
        logout()
    form = LoginForm()
    if form.validate_on_submit:
        username = form.username.data
        password = form.password.data
        if username and password is not None:
            if username != 'admin' or password != 'admin':
                flash("Your password is worng, please try again", 'danger')
            else:
                session['user'] = '******'
                return redirect(url_for('home'))
    return render_template('login.html', form=form)
示例#34
0
def login(request):
    if request.method == 'POST':
        login_form = LoginForm(request.POST)

        if login_form.is_valid():
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']

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

            if user is not None:
                login(request, user)
            else:
                pass
        else:
            pass
    else:
        context = {
            'login_form': LoginForm(),
            'success': 0,
        }

        return render(request, 'authentication/login.html', context)
示例#35
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for("home"))
    form = LoginForm()
    if form.validate_on_submit():
        users = getDBData()
        print(users)
        userFoundRow = None
        if users:
            for row in users:
                print(row.username)
                if row.username.lower() == form.username.data.lower():
                    userFoundRow = row
                    break

        if userFoundRow:
            if bcrypt.check_password_hash(userFoundRow.password,
                                          form.password.data):
                login_user(User(userFoundRow), remember=form.remember.data)
                return redirect(url_for("home"))
            flash("Incorrect password specified.")
        else:
            flash("The specified household nickname was not found")
    return render_template("login.html", form=form)
示例#36
0
def index(request):
    """ View on main page / """
    if request.user.is_authenticated() is False:
        reg_form = RegistrationForm(auto_id='reg_%s')
        login_form = LoginForm(auto_id='login_%s')

        c = {
            'reg_form': reg_form,
            'login_form': login_form,
            'session': request.user
        }
        c.update(csrf(request))

        return render_to_response('index.html',
                                  c,
                                  context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect("/profile/")
示例#37
0
def contacto(request):
	if request.method == 'POST':
		cform = ContactanosForm(request.POST or None)
		if cform.is_valid():
			solicitud = cform.save(commit=False)
			solicitud.tipo = 'Contacto'
			solicitud.save()
			return redirect('website:home')
		return redirect('solicitudes:contacto')
	else:
		contactof = ContactanosForm()
		if request.user.is_authenticated:
			if request.user.perfil.es_supervisor:
				return render(request, 'solicitudes/contacto.html',{'base_template':'website/base_admin.html','contactof':contactof})
			else:
				return render(request, 'solicitudes/contacto.html',{'base_template':'website/base_usuario.html','contactof':contactof})
		else:			
			loginf = LoginForm()	
			return render(request, 'solicitudes/contacto.html', {'base_template':'website/base.html','loginf': loginf,'contactof':contactof})
示例#38
0
def dashboard_login_external(request, language_code):
    context = RequestContext(request)
    if context.get('user').is_authenticated():
        return redirect('index_external', language_code=language_code)

    if request.method == "POST":
        form_login = LoginForm(request.POST)
        if form_login.validate():
            user = form_login.get_user()
            login(request, user)
            if request.POST.get('remember', None):
                request.session.set_expiry(0)
            return redirect('index')
    else:
        form_login = LoginForm()
    context.update({'form_login': form_login, 'language_code': language_code})
    return render_to_response('login_external.html', context_instance=context)