Ejemplo n.º 1
0
def login(request):
    """
    This view handles user authentication
    """

    username = request.POST.get("username", "")
    password = request.POST.get("password", "")

    form = AuthenticationForm()

    if username != "":
        user = authenticate(username=username, password=password)
        if user is not None:
            user1 = User.objects.get(username = user.username)
            if MyUser.objects.all().filter(user = user1):
                myuser = MyUser.objects.get(user=user1)
            else: myuser = Developer.objects.get(user=user1)
            if user.is_active:
                login_user(request, user)
                if myuser.verif == False:
                    return HttpResponseRedirect("/verification/")
                return HttpResponseRedirect("/")
            else:
                return HttpResponse("Ur banned son")
        else:
            form = AuthenticationForm(initial={"username":username})

    form.fields['password'].widget.attrs['autofocus'] = 'on'

    return render(request, "login.html", {"form":form})
Ejemplo n.º 2
0
def register(request):
    from sentry.conf import settings

    if not (settings.ALLOW_REGISTRATION
            or request.session.get('can_register')):
        return HttpResponseRedirect(reverse('sentry'))

    form = RegistrationForm(request.POST or None)
    if form.is_valid():
        user = form.save()

        # can_register should only allow a single registration
        request.session.pop('can_register', None)

        # HACK: grab whatever the first backend is and assume it works
        user.backend = dj_settings.AUTHENTICATION_BACKENDS[0]

        login_user(request, user)

        return login_redirect(request)

    return render_to_response(
        'sentry/register.html', {
            'form': form,
            'AUTH_PROVIDERS': get_auth_providers(),
            'SOCIAL_AUTH_CREATE_USERS': dj_settings.SOCIAL_AUTH_CREATE_USERS,
        }, request)
Ejemplo n.º 3
0
def signup(request):
  if request.method=='POST':
    form = SignupForm(request.POST)
    if form.is_valid():
      username = form.cleaned_data['username']
      role = form.cleaned_data['role']
      password = form.cleaned_data['password']
      user = MyUser.objects.create_user(username=username,role=role,password=password)
      user.save()
      user = authenticate(username=username,password=password)
      login_user(request,user)
      messages.success(request,'You have signed up successfully! Please complete some further information.')
      if role=='tutor':
        tutor = Tutor()
        tutor.base_info = user
        tutor.name = username
        tutor.save()
        return HttpResponseRedirect(reverse('myAuth:signup_tutor'))
      else:
        student = Student()
        student.base_info = user
        student.name = username
        student.save()
        return HttpResponseRedirect(reverse('myAuth:signup_student'))
    messages.error(request,'The username you used already exists!')
    return HttpResponseRedirect(reverse('myAuth:signup'))
  else:
    form = SignupForm()
    return render(request,'signup.html',{'form':form})
Ejemplo n.º 4
0
def register(request):
    """Try to register new user"""

    if request.user.is_authenticated():
        return redirect('grunts')

    if request.method == 'POST':
        form = CustomRegisterForm(data=request.POST)
        if not form.is_valid():
            return render(
                request,
                'auth/register.html',
                {'form': form}
            )
        else:
            # If valid form -> create user
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password1']
            )

            # And associate all required profiles
            associate_profiles(user)

            # Login registered user
            user.backend = 'django.contrib.auth.backends.ModelBackend'
            login_user(request, user)

            # Go to device list
            return redirect('grunts')
    else:
        form = CustomRegisterForm()

    return render(request, 'auth/register.html', {'form': form})
Ejemplo n.º 5
0
def oauth_callback( request ):
	'''Twitter redirects to this handler after authenticating on their server'''
	if request.session[ 'oauth_domain' ] == 'twitter':
		backend = TwitterBackend()
	else:
		return HttpResponse( 'fail; invalid oauth provider' )
	
	# It's possible that the user didn't authenticate correctly or denied access
	if backend.access_granted( request ):
		# Store Twitter tokens and fetch user info
		request = backend.finalize_handshake( request )
		request.user = backend.get_user( backend.get_user_id( request ) )
	
		if request.user:
			request.user.backend = 'placethings.auth.backends.TwitterBackend' # Required by Django
			login_user( request, request.user )
			
			# Return status message if they authenticated through the API and have already finished registration on our system
			return HttpResponse( 'success; id=%d' % (request.user.id) )
		elif request.META[ 'HTTP_USER_AGENT' ].find( 'iPhone' ):
			# . . . unless they're on an iPhone, then send them the session key so it can do things for us
			return redirect( 'placethings://' + request.session_key )
		else:
			# If they haven't finished registering on Placethings, tell them to do this
			return HttpResponse( 'success; no account on placethings; complete login at /api/register' )
	else:
		request = backend.clear_session_data( request )
		Session.objects.all().delete()
		return HttpResponse( 'fail; access was denied' )
Ejemplo n.º 6
0
 def post(self, request):
     username = request.POST['username']
     password = request.POST['password']
     user = authenticate(username=username, password=password)
     if user is not None:
         login_user(request, user)
         return render(request, 'index.html')
Ejemplo n.º 7
0
def login(request, 
          invalid_template='biims/login_page.html',
          succesful_template='biims/options.html'):
    if request.user.is_authenticated():
        messages.info(
                request,
                'You\'re already logged in',
                extra_tags="login_message")
        return render(request, succesful_template)

    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')

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

        if user is not None:
            if user.is_active:
                login_user(request, user)
                messages.info(
                    request,
                    'Welcome {}'.format(request.user.username),
                    extra_tags="login_message")
                return render(request, succesful_template)
        else:
            messages.error(request,
                    'Invalid Credentials',
                    extra_tags="wrong_login")
            return render(request, invalid_template)
    else:
        return render(request, invalid_template)
Ejemplo n.º 8
0
def register(request):
    """Register new user and associate profile"""
    if request.user.is_authenticated():
        return redirect('profile')

    if request.method == 'POST':
        form = UserCreationForm(data=request.POST)
        if not form.is_valid():
            return render(
                request,
                'index.html',
                {'error_message': 'Could not create user', 'register': True}
                # {'error_message': form.errors.values()}
            )
        else:
            # If valid form -> create user
            user, profile = new_user_with_profile(form)

            # Login registered user
            user.backend = 'django.contrib.auth.backends.ModelBackend'
            login_user(request, user)

            # Go to profile
            return redirect('profile')

    # Otherwise, display register page
    return render(request, 'index.html', {'register': True})
Ejemplo n.º 9
0
    def wrapper_login_cookie(request, *args, **kwargs):
        cookie_key = 'cookieid'
        # Cookie Session Exists
        if not request.user.is_authenticated and request.COOKIES.get(
                cookie_key):
            cookie_id = request.COOKIES.get(cookie_key)
            try:
                user_login_cookie = Cookie.objects.get(cookie_id=cookie_id)
            except Cookie.DoesNotExist:
                # Cookie doesn't exists in database, so delete the cookie from browser
                user_login_cookie = None
                return delete_cookie(request,
                                     view_func(request, *args, **kwargs),
                                     cookie_key,
                                     user=None)
            else:
                # Cookie exists
                if user_login_cookie.expiry_date >= datetime.datetime.now():
                    # Recreate login session for the user as cookie hasn't expired
                    login_user(request, user_login_cookie.user)
                    """ SET SESSION FOR LOGIN """
                    SESSION_EXPIRY_AGE = 24 * 60 * 60  # 1 day in secs
                    request.session.set_expiry(
                        SESSION_EXPIRY_AGE
                    )  # expire this session after EXPIRY_AGE
                else:
                    # Delete the cookie as it has been expired
                    return delete_cookie(request,
                                         view_func(request, *args, **kwargs),
                                         cookie_key,
                                         user=user_login_cookie.user)

        return view_func(request, *args, **kwargs)
Ejemplo n.º 10
0
def login(request):
    """Login existing user and redirect to device list page"""

    if request.user.is_authenticated():
        return redirect('grunts')

    if request.method == 'POST':
        form = CustomAuthForm(data=request.POST)
        if not form.is_valid():
            return render(
                request,
                'auth/login.html',
                {'form': form}
            )

        # If form is valid, try to authenticate user
        user = authenticate(
            username=form.cleaned_data['username'],
            password=form.cleaned_data['password']
        )

        if user is not None:
            # Log in and redirect to device list
            login_user(request, user)
            return redirect('grunts')
        else:
            return render(
                request,
                'auth/login.html',
                {'form': form}
            )
    else:
        form = CustomAuthForm()

    return render(request, 'auth/login.html', {'form': form})
Ejemplo n.º 11
0
def validatePayment(request):
    user=None
    if request.user.is_authenticated:
        user=request.user
    user_id=request.GET.get('user')
    payment_request_id=request.GET.get('payment_request_id')
    payment_id=request.GET.get('payment_id')
    print(payment_id,payment_request_id)
    response = API.payment_request_payment_status(payment_request_id, payment_id)

               # Purpose of Payment Request
    status=response.get('payment_request').get('payment').get('status')           
    user=User.objects.get(id=user_id)
    login_user(request,user)
    if status !="Failed":
        try:
            payment=Payment.objects.get(payment_request_id=payment_request_id)
            payment.payment_id=payment_id
            payment.payment_status=status
            payment.save()
            order=payment.order
            order.order_status='PLACED'
            order.save()
            cart=[]
            request.session['cart']=cart
            Cart.objects.filter(user=user).delete()
            print(user)
            return render(request,'payment_success.html')
        except:
            
            return render(request,'payment_failed.html')
            
    else:
        return render(request,'payment_failed.html')
Ejemplo n.º 12
0
def login(request):
	if request.method == "POST":
		username = request.POST['username']
		password = request.POST['password']
		user = authenticate(request, username=username, password=password)
		if user is not None:
			if user.is_active:
				login_user(request, user)
				user = User.objects.filter(username=request.user)
				
				my_followers = []
				for followMem in User.objects.get(username=username).following_set.all():
					my_followers.append(followMem.follow)

				# request.session['my_followers'] = my_followers

				return redirect(index)
				
			else:
				messages.error(request, 'Your account has been disabled')
				return render(request, 'index/login.html', {
					'title': 'Check out the latest updates'
				})
		else:
			messages.error(request, 'Invalid login')
			return render(request, 'index/login.html', {
				'title': 'Check out the latest updates'
			})
	else:
		return render(request, 'index/login.html', {'title': 'Check out the latest updates'})
Ejemplo n.º 13
0
def update_participant_info(request):
    participant = Participant.objects.get(user=request.user)
    initial = {
        'new_participant': 0,
        'username': participant.user.username,
        'name': participant.name,
        'id': participant.id,
        'course': participant.course.id,
        'email': participant.user.email,
        'year': participant.year.id,
        'campus': participant.campus.id
    }
    form = ParticipantForm(request.POST or None, initial=initial)

    form.fields['username'].widget.attrs['readonly'] = True
    form.fields['email'].widget.attrs['readonly'] = True
    form.fields['id'].widget.attrs['readonly'] = True

    context = {
        'form': form,
        'action': '/meu-cadastro',
        'title': 'Alterar dados cadastrais',
        'breadcrumb': [
            {
                'name': 'Início',
                'link': '/'
            },
            {
                'name': 'Meu cadastro'
            },
        ]
    }

    if request.method == 'POST':
        if form.is_valid():
            try:
                participant.name = form.cleaned_data['name']
                # participant.id = form.cleaned_data['id']
                # participant.user.email = form.cleaned_data['email']
                participant.campus = Campus.objects.get(
                    id=int(form.cleaned_data['campus']))
                participant.year = Year.objects.get(
                    id=int(form.cleaned_data['year']))
                participant.course = Course.objects.get(
                    id=int(form.cleaned_data['course']))
                participant.user.set_password(form.cleaned_data['password'])
                participant.user.save()
                participant.save()
                login_user(
                    request,
                    authenticate(username=form.cleaned_data['username'],
                                 password=form.cleaned_data['password']))
                messages.success(request, 'Dados alterados com sucesso.')
                return render(request, 'signup.html', context)
            except:
                messages.error(request, 'Não foi possível alterar seus dados.')
                return render(request, 'signup.html', context, status=400)
        return render(request, 'signup.html', context, status=400)

    return render(request, 'signup.html', context)
Ejemplo n.º 14
0
def recover_confirm(request, user_id, hash):
    try:
        password_hash = LostPasswordHash.objects.get(user=user_id, hash=hash)
        if not password_hash.is_valid():
            password_hash.delete()
            raise LostPasswordHash.DoesNotExist
        user = password_hash.user

    except LostPasswordHash.DoesNotExist:
        context = {}
        tpl = "sentry/account/recover/failure.html"

    else:
        tpl = "sentry/account/recover/confirm.html"

        if request.method == "POST":
            form = ChangePasswordRecoverForm(request.POST)
            if form.is_valid():
                user.set_password(form.cleaned_data["password"])
                user.save()

                # Ugly way of doing this, but Django requires the backend be set
                user = authenticate(username=user.username, password=form.cleaned_data["password"])

                login_user(request, user)

                password_hash.delete()

                return login_redirect(request)
        else:
            form = ChangePasswordRecoverForm()

        context = {"form": form}

    return render_to_response(tpl, context, request)
Ejemplo n.º 15
0
def accept(request: HttpRequest, key: str):
    invitation = Invite.objects.filter(key=key).first()
    if invitation is None:
        return redirect('login')
    if request.method == "GET":
        return render(request, 'book/accept.html', {
            'key': key,
            'member': invitation.member,
        })
    values = tuple(request.POST.get(value) for value in ('username', 'password', 'name'))
    if not all(values):
        request.session['errors'] = ["Please enter all values"]
        redirect("accept", key=key)
    username, password, name = values
    user = User.objects.create_user(username, invitation.email, password)
    family = invitation.family
    family.users.add(user)
    family.save()
    user.save()
    user = authenticate(username=username, password=password)
    login_user(request, user)
    member = Member.objects.create(family=family, name=name, user=user)
    member.save()
    invitation.delete()
    return redirect('family:home', family=family.url_name)
Ejemplo n.º 16
0
def login(request):
    if request.user.is_authenticated:
        messages.add_message(
            request, messages.INFO, message=_("You are already logged in.")
        )
        return redirect("home")

    context = {"login_form": AuthenticationForm(), "signup_form": UserCreationForm()}
    if request.method == "POST":
        if request.POST.get("action") == "login":
            login_form = AuthenticationForm(data=request.POST)
            if login_form.is_valid():
                username = login_form.cleaned_data.get("username")
                raw_password = login_form.cleaned_data.get("password")
                user = authenticate(username=username, password=raw_password)
                login_user(request, user, backend=user.backend)
                return redirect("home")
            else:
                context["login_form"] = login_form
                context["action"] = "login"
        elif request.POST.get("action") == "signup":
            signup_form = UserCreationForm(data=request.POST)
            if signup_form.is_valid():
                signup_form.save()
                username = signup_form.cleaned_data.get("username")
                raw_password = signup_form.cleaned_data.get("password1")
                user = authenticate(username=username, password=raw_password)
                login_user(request, user, backend=user.backend)
                return redirect("home")
            else:
                context["signup_form"] = signup_form
                context["action"] = "signup"

    return render(request, "get_together/users/login.html", context)
Ejemplo n.º 17
0
def login(request):
    if request.method == 'POST':
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            identifier = login_form.cleaned_data['identifier']
            password = login_form.cleaned_data['password']
            user = authenticate(request,
                                username=identifier,
                                password=password)
            if user != None:
                login_user(request, user)
                return redirect('main-page')
            else:
                context_dict = {
                    'form': login_form,
                    'invalid_credentials': True
                }
                return render(request, 'user/login.html', context_dict)
        else:
            context_dict = {'form': login_form, 'invalid_credentials': True}
            return render(request, 'user/login.html', context_dict)

    else:
        login_form = LoginForm()
        context_dict = {'form': login_form, 'invalid_credentials': False}
        return render(request, 'user/login.html', context_dict)
Ejemplo n.º 18
0
def import_signup(request):
    if request.method == "POST":
        signup_form = SignupForm(prefix='signup', data=request.POST)
        if signup_form.is_valid():
            new_user = signup_form.save()
            
            user_token = None
            if not user_token:
                user_uuid = request.COOKIES.get('newsblur_reader_uuid')
                if user_uuid:
                    user_token = OAuthToken.objects.filter(uuid=user_uuid).order_by('-created_date')
            if not user_token:
                if request.session.session_key:
                    user_token = OAuthToken.objects.filter(session_id=request.session.session_key).order_by('-created_date')
            if not user_token:
                user_token = OAuthToken.objects.filter(remote_ip=request.META['REMOTE_ADDR']).order_by('-created_date')

            if user_token:
                user_token = user_token[0]
                user_token.session_id = request.session.session_key
                user_token.user = new_user
                user_token.save()
                login_user(request, new_user)
                return HttpResponseRedirect(reverse('index'))
            else:
                logging.user(request, "~BR~FW ***> Can't find user token during import/signup. Re-authenticating...")
                return HttpResponseRedirect(reverse('google-reader-authorize'))
    else:
        signup_form = SignupForm(prefix='signup')

    return render_to_response('import/signup.xhtml', {
        'signup_form': signup_form,
    }, context_instance=RequestContext(request))
Ejemplo n.º 19
0
def login(request):
    context = {
        'data': {},
        'errors': [],
    }

    Group .objects.get_or_create(name='rider')
    Group.objects.get_or_create(name='establishment')

    if request.method == 'POST':
        data = request.POST
        username = data.get('username', '')
        password = data.get('password', '')

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

        if user is not None:
            if user.is_active:
                request.session.set_expiry(86400)
                login_user(request, user)

                if user.groups.filter(name='rider').exists():
                    return HttpResponseRedirect('/riderHome')
                if user.groups.filter(name='establishment').exists():
                    return HttpResponseRedirect('/establishmentHome')
        else:
            context['errors'].append("The username or password is incorrect.")

    return render(request, "login.html", context)
Ejemplo n.º 20
0
def register(request):

    content = {'username': "", 'form': "", 'error': ""}

    if 'logged_in' in request.session:
        return redirect('/')

    if request.method == "GET":
        request.session.flush()
        form = RegisterForm()

    if request.method == "POST":
        form = RegisterForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['user_name']
            password = form.cleaned_data['password']
            password_confirm = form.cleaned_data['password_confirm']
            if password == password_confirm:
                try:
                    new_user = User.objects.create(username=username,
                                                   password=password)
                    new_user.save()
                    request.session['username'] = username
                    content['username'] = username
                    request.session['logged_in'] = True
                    login_user(request, new_user)
                    return redirect('/')
                except IntegrityError:
                    form = RegisterForm(request.POST)
                    content['error'] = "Username already exist!"
            else:
                content['error'] = "Passwords not match!"

    content['form'] = form
    return render(request, 'register.html', content)
Ejemplo n.º 21
0
def login(request):
    """Login existing user and redirect to device list page"""

    if request.user.is_authenticated():
        return redirect('grunts')

    if request.method == 'POST':
        form = CustomAuthForm(data=request.POST)
        if not form.is_valid():
            return render(request, 'auth/login.html', {'form': form})

        # If form is valid, try to authenticate user
        user = authenticate(username=form.cleaned_data['username'],
                            password=form.cleaned_data['password'])

        if user is not None:
            # Log in and redirect to device list
            login_user(request, user)
            return redirect('grunts')
        else:
            return render(request, 'auth/login.html', {'form': form})
    else:
        form = CustomAuthForm()

    return render(request, 'auth/login.html', {'form': form})
Ejemplo n.º 22
0
def login(request):
	if request.method == 'GET':
		return render(request,"login.html",{})

	if request.method == 'POST':
		username = request.POST['username']
		password = request.POST['password']
		print username
		print password
		try:
			user = authenticate(username=username,password=password)
			print "asd"

			if user:
				print "zxc"
				try:
					login_user(request,user)
					print "cvb"
					return render(request,"index.html",{'status':'Welcome to Kalp.'})
				except:
					return render(request,"login.html",{'status':'Some error occured.'})
			else:
				return render(request,"login.html",{'status':'Invalid credentials'})
		except:
			return render(request,"login.html",{'status':'Invalid credentials'})
Ejemplo n.º 23
0
def login(request):

    content = {'username': "", 'form': "", 'error': ""}

    if 'logged_in' in request.session:
        return redirect('/')

    if request.method == "GET":
        request.session.flush()
        form = LoginForm()

    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['user_name']
            password = form.cleaned_data['password']
            try:
                object = User.objects.get(username=username)
                if object.password == password:
                    request.session['username'] = username
                    content['username'] = username
                    request.session['logged_in'] = True
                    login_user(request, object)
                    return redirect('/')
                else:
                    content['error'] = "Wrong password!"
            except Exception:
                form = LoginForm(request.POST)
                content['error'] = "No such user! Please, register at first."

    content['form'] = form
    return render(request, 'login.html', content)
Ejemplo n.º 24
0
def signup(request):
    security_error = False
    if request.method == 'POST':
        if request.POST['security'] != request.session['expected']:
            security_error = True
        form = SignUpForm(data=request.POST or None)
        if not security_error and form.is_valid():
            data = form.cleaned_data
            user = User.objects.create_user(username=data['username'],
                                            password=data['password'],
                                            email=data['email'])
            user.is_active = True
            user.save()
            user = authenticate(username=data['username'],
                                password=data['password'])
            login_user(request, user)
            return redirect('/')

    else:
        form = SignUpForm()
    question = get_security_question()
    request.session['expected'] = question['answer']
    return augmented_render(request, 'account/signup.html',
                            {'form': form, 
                             'security_error': security_error,
                             'question': question})
Ejemplo n.º 25
0
def auth(request):
    names_dict = {}
    errors = []
    form = AuthForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        data = form.cleaned_data
        names_list = ["username", "password"]
        names_dict = {x: request.POST.get(x, "") for x in names_list}
        login = data["username"]
        if not login:
            errors.append('enter login')
        password = data['password']
        if not password:
            errors.append("enter password")

        if not errors:
            try:
                userdata = User.objects.get(username=data["username"])
                if not check_password(data.get('password'), userdata.password):
                    errors.append("invalid password or user does not exist")

            except User.DoesNotExist:
                errors.append("invalid password or user does not exist")

            if not errors:
                user = authenticate(username=login, password=data.get('password'))
                if user is not None:
                    if request.user.is_authenticated:
                        pass
                    login_user(request, user)
                    return HttpResponseRedirect("/about/")
    print(list(errors))
    return render(request, 'loginPage.html', {"errors": errors, 'names_dict': names_dict, "form": form})
Ejemplo n.º 26
0
def login(request):
    title = "MyCity | Login"
    msg = ""
    active = None
    if request.method == "POST":
        loginform = LoginForm(data=request.POST)
        if loginform.is_valid():
            user = authenticate(email=request.POST['email'],
                                password=request.POST['password'])
            if user is not None:
                if user.is_active:
                    if not request.POST.get('remember_me', None):
                        request.session.set_expiry(0)
                    login_user(request, user)
                    return redirect('/')
                else:
                    active = False
                    msg = "Este e-mail ainda não está ativado! Favor verificar sua caixa de e-mail."
            else:
                active = False
                msg = "E-mail ou senha incorreto."
    else:
        loginform = LoginForm
    return render(request, 'mycity/login.html', {
        'title': title,
        'loginform': loginform,
        'active': active,
        'msg': msg
    })
Ejemplo n.º 27
0
def login(request):
    if request.user.is_authenticated():
        messages.info(request, 'You are already logged in.')

        if request.GET.get('next'):
            return redirect(request.GET.get('next'))
        else:
            return redirect(reverse('manager_index'))

    if request.POST:
        user = request.POST.get('username')
        pawd = request.POST.get('password')

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

        if user is not None:
            if user.is_active:
                login_user(request, user)
                messages.info(request, 'Login successful.')

                if request.GET.get('next'):
                    return redirect(request.GET.get('next'))
                else:
                    return redirect(reverse('manager_index'))
            else:
                messages.add_message(request, messages.ERROR,
                                     'User account is not active.')
        else:
            messages.add_message(request, messages.ERROR,
                                 'Account not found with those details.')

    context = {}
    template = 'login.html'

    return render(request, template, context)
Ejemplo n.º 28
0
def register(request):
    """Try to register new user"""

    if request.user.is_authenticated():
        return redirect('grunts')

    if request.method == 'POST':
        form = CustomRegisterForm(data=request.POST)
        if not form.is_valid():
            return render(request, 'auth/register.html', {'form': form})
        else:
            # If valid form -> create user
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password1'])

            # And associate profile
            profile = Profile()
            profile.user = user
            profile.save()

            # Login registered user
            user.backend = 'django.contrib.auth.backends.ModelBackend'
            login_user(request, user)

            # Go to device list
            return redirect('grunts')
    else:
        form = CustomRegisterForm()

    return render(request, 'auth/register.html', {'form': form})
Ejemplo n.º 29
0
def signup(request):
    if request.method == 'POST':
        if not request.POST['password'] == request.POST['password2']:
            messages.error(request,
                           'Password chosen mismatch. Please try again')
            return redirect(login)

        if User.objects.filter(username=request.POST['username']):
            messages.error(request, 'Username you chose has been taken')
            return redirect(login)

        form = UserForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user.set_password(password)

            user.save()
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login_user(request, user)

                messages.success(
                    request, 'Welcome, enjoy the best shopping experience')
                return redirect(shop, 'all')

        messages.error(request, 'Please ensure the all the field are filled')
        return redirect(signup)
    else:
        return redirect(login)
Ejemplo n.º 30
0
def login(request):
    code = -1
    errors = None
    user_agent = request.environ.get('HTTP_USER_AGENT', '')
    ip = request.META.get('HTTP_X_FORWARDED_FOR',
                          None) or request.META['REMOTE_ADDR']

    if not user_agent or user_agent.lower() in ['nativehost']:
        errors = dict(user_agent="You must set a user agent to login.")
        logging.user(
            request, "~FG~BB~SK~FRBlocked ~FGAPI Login~SN~FW: %s / %s" %
            (user_agent, ip))
    elif request.method == "POST":
        form = LoginForm(data=request.POST)
        if form.errors:
            errors = form.errors
        if form.is_valid():
            login_user(request,
                       form.get_user(),
                       backend='django.contrib.auth.backends.ModelBackend')
            logging.user(
                request,
                "~FG~BB~SKAPI Login~SN~FW: %s / %s" % (user_agent, ip))
            code = 1
    else:
        errors = dict(method="Invalid method. Use POST. You used %s" %
                      request.method)

    return dict(code=code, errors=errors)
Ejemplo n.º 31
0
def login(request):
    from django.contrib.auth.forms import AuthenticationForm
    from sentry.conf import settings

    if request.user.is_authenticated():
        return login_redirect(request)

    form = AuthenticationForm(request, request.POST or None)
    if form.is_valid():
        login_user(request, form.get_user())
        return login_redirect(request)

    request.session.set_test_cookie()

    context = csrf(request)
    context.update({
        'form':
        form,
        'next':
        request.session.get('_next'),
        'CAN_REGISTER':
        settings.ALLOW_REGISTRATION or request.session.get('can_register'),
        'AUTH_PROVIDERS':
        get_auth_providers(),
        'SOCIAL_AUTH_CREATE_USERS':
        dj_settings.SOCIAL_AUTH_CREATE_USERS,
    })
    return render_to_response('sentry/login.html', context, request)
Ejemplo n.º 32
0
def login(request):
    user = authenticate(username=request.POST.get( 'username', None ), password=request.POST.get( 'password') )
    if user is not None:
        login_user(request, user)
        return API_Success( 'id=%d' % (user.id) )
    else:
        return API_Error( 'username and password were incorrect' )
Ejemplo n.º 33
0
def import_signup(request):
    if request.method == "POST":
        signup_form = SignupForm(prefix='signup', data=request.POST)
        if signup_form.is_valid():
            new_user = signup_form.save()
            try:
                user_token = OAuthToken.objects.get(
                    session_id=request.session.session_key)
            except OAuthToken.DoesNotExist:
                user_tokens = OAuthToken.objects.filter(
                    remote_ip=request.META['REMOTE_ADDR']).order_by(
                        '-created_date')
                if user_tokens:
                    user_token = user_tokens[0]
                    user_token.session_id = request.session.session_key
                    user_token.save()
            user_token.user = new_user
            user_token.save()
            login_user(request, new_user)
            return HttpResponseRedirect(reverse('index'))
    else:
        signup_form = SignupForm(prefix='signup')

    return render_to_response('import/signup.xhtml', {
        'signup_form': signup_form,
    },
                              context_instance=RequestContext(request))
Ejemplo n.º 34
0
def login(request):
    """Try to login existing user"""
    if request.user.is_authenticated():
        return redirect('profile')

    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if not form.is_valid():
            return render(
                request,
                'index.html',
                {'error_message': 'Sorry, could not login', 'login': True}
                # {'error_message':
                # ' '.join([e.as_text() for e in form.errors.values()])}
            )

        # If form is valid, try to authenticate user
        user = authenticate(
            username=form.cleaned_data['username'],
            password=form.cleaned_data['password']
        )
        if user is not None:
            # Log in and  redirect to profile
            login_user(request, user)
            return redirect('profile')
        else:
            return render(
                request,
                'index.html',
                {'error_message': 'Sorry, could not login', 'login': True}
            )

    # Otherwise, display login page
    return render(request, 'index.html', {'login': True})
Ejemplo n.º 35
0
Archivo: api.py Proyecto: jq2st/inj-prj
def sign_in(request, data: Creds):
    user = authenticate(username=data.login, password=data.password)
    if user is not None:
        login_user(request, user)
        return f"Authenticated user {user}"
    else:
        return f"Not authenticated"
Ejemplo n.º 36
0
def signup(request):
    code = -1
    errors = None
    ip = request.META.get('HTTP_X_FORWARDED_FOR',
                          None) or request.META['REMOTE_ADDR']

    if request.method == "POST":
        form = SignupForm(data=request.POST)
        if form.errors:
            errors = form.errors
        if form.is_valid():
            try:
                new_user = form.save()
                login_user(request,
                           new_user,
                           backend='django.contrib.auth.backends.ModelBackend')
                logging.user(
                    request, "~FG~SB~BBAPI NEW SIGNUP: ~FW%s / %s" %
                    (new_user.email, ip))
                code = 1
            except forms.ValidationError as e:
                errors = [e.args[0]]
    else:
        errors = dict(method="Invalid method. Use POST. You used %s" %
                      request.method)

    return dict(code=code, errors=errors)
Ejemplo n.º 37
0
def login(request):
    if request.user.is_authenticated:
        return redirect('home')

    context = {
        "signup_form":  NewUserForm(),
        "login_form": AuthenticationForm(),
    }
    if request.method == "POST":
        if request.POST.get("action") == "login":
            login_form = AuthenticationForm(data=request.POST)
            if login_form.is_valid():
                username = login_form.cleaned_data.get("username")
                raw_password = login_form.cleaned_data.get("password")
                user = authenticate(username=username, password=raw_password)
                login_user(request, user, backend=user.backend)
                return redirect('home')
            else:
                context["login_form"] = login_form
                context["action"] = "login"
        elif request.POST.get("action") == "signup":
            signup_form = NewUserForm(data=request.POST)
            if signup_form.is_valid():
                signup_form.save()
                username = signup_form.cleaned_data.get("username")
                raw_password = signup_form.cleaned_data.get("password1")
                user = authenticate(username=username, password=raw_password)
                login_user(request, user, backend=user.backend)
                return redirect('home')
            else:
                context["signup_form"] = signup_form
                context["action"] = "signup"

    return render(request, 'savannahv2/login.html', context)
Ejemplo n.º 38
0
def signup(request):
    if request.method == 'POST':
        if not request.POST['password'] == request.POST['password2']:
            messages.error(request,
                           'Password chosen mismatch. Please try again')
            return redirect(signup)

        if User.objects.filter(username=request.POST['username']):
            messages.error(request, 'Username you chose has been taken')
            return redirect(signup)

        form = UserForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user.set_password(password)

            user.save()
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login_user(request, user)

                messages.success(
                    request, 'Please complete your profile to make it visible')
                return redirect(editprofile)

        messages.error(request, 'Please ensure the all the field are filled')
        return redirect(signup)
    else:
        return render(
            request, 'register.html', {
                'title': 'Create and Share your portfolio round the world',
                'page': 'Register'
            })
Ejemplo n.º 39
0
def signup(request):
    form = SignupForm(prefix="signup")
    recaptcha = request.POST.get('g-recaptcha-response', None)
    recaptcha_error = None
    
    if not recaptcha:
        recaptcha_error = "Please hit the \"I'm not a robot\" button."
    else:
        response = requests.post('https://www.google.com/recaptcha/api/siteverify', {
            'secret': settings.RECAPTCHA_SECRET_KEY,
            'response': recaptcha,
        })
        result = response.json()
        if not result['success']:
            recaptcha_error = "Really, please hit the \"I'm not a robot\" button."
    recaptcha_error = None

    if request.method == "POST":
        form = SignupForm(data=request.POST, prefix="signup")
        if form.is_valid() and not recaptcha_error:
            new_user = form.save()
            login_user(request, new_user)
            logging.user(new_user, "~FG~SB~BBNEW SIGNUP: ~FW%s" % new_user.email)
            new_user.profile.activate_free()
            return HttpResponseRedirect(request.POST['next'] or reverse('index'))

    return render_to_response('accounts/signup.html', {
        'form': form,
        'recaptcha_error': recaptcha_error,
        'next': request.REQUEST.get('next', "")
    }, context_instance=RequestContext(request))
Ejemplo n.º 40
0
Archivo: views.py Proyecto: NateWr/rua
def login(request):
	if request.user.is_authenticated():
		messages.info(request, 'You are already logged in.')
		roles=  request.user.profile.roles.all()
		if request.GET.get('next'):
			return redirect(request.GET.get('next'))
		else:
			return redirect(reverse('user_dashboard'))
			

	if request.POST:
		user = request.POST.get('user_name')
		pawd = request.POST.get('user_pass')

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

		if user is not None:
			if user.is_active:
				login_user(request, user)
				messages.info(request, 'Login successful.')
				roles=  user.profile.roles.all()
				if request.GET.get('next'):
					return redirect(request.GET.get('next'))
				else:
					return redirect(reverse('user_dashboard'))
			else:
				messages.add_message(request, messages.ERROR, 'User account is not active.')
		else:
			messages.add_message(request, messages.ERROR, 'Account not found with those details.')

	context = {}
	template = 'core/login.html'

	return render(request, template, context)
Ejemplo n.º 41
0
def login(request):
    from django.contrib.auth.forms import AuthenticationForm
    from sentry.conf import settings

    if request.user.is_authenticated():
        return login_redirect(request)

    form = AuthenticationForm(request, request.POST or None)
    if form.is_valid():
        login_user(request, form.get_user())
        return login_redirect(request)

    request.session.set_test_cookie()

    context = csrf(request)
    context.update(
        {
            "form": form,
            "next": request.session.get("_next"),
            "CAN_REGISTER": settings.ALLOW_REGISTRATION or request.session.get("can_register"),
            "AUTH_PROVIDERS": get_auth_providers(),
            "SOCIAL_AUTH_CREATE_USERS": dj_settings.SOCIAL_AUTH_CREATE_USERS,
        }
    )
    return render_to_response("sentry/login.html", context, request)
Ejemplo n.º 42
0
	def post(self, request):
		form = LoginForm(None, request.POST or None)
		if form.is_valid():
			login_user(request, form.get_user())
			return redirect('index', permanent=True)
		else:
			return render(request, self.template_name, {'login_form': form})
Ejemplo n.º 43
0
def signup(request):
    usermodel = get_user_model()
    if request.method == "GET":
        return r2r("signup.jinja", request, locals())
    else:
        email = request.POST['email']
        password = request.POST['password']
        if not is_valid_email(email):
            error_msg = "Please enter a valid email address."
            return r2r("signup.jinja", request, locals())
        if len(password) < 6:
            error_msg = "Please enter a password of at least 6 characters."
            return r2r("signup.jinja", request, locals())
        if usermodel.objects.filter(username=email).count():
            error_msg = "An account with this email address already exists."
            return r2r("signup.jinja", request, locals())

        user = usermodel.objects.create_user(email, email, password=password)
        user.save()
        user = authenticate(username=email, password=password)
        login_user(request, user)

        # Send email confirmation.
        email_confirm_url = reverse('email_confirm', args=[str(uuid.uuid4())])
        msg = "Thanks for signing up for {{project_name}}!\n\nPlease confirm your email address by clicking the following link: {0}{1}. You won't be able to receive further emails from us until confirming your address.\n\nIf you didn't sign up, take no action, and this is the last email you'll receive from us.\n\nThanks,\n{0}".format(settings.WEBSITE_URL, email_confirm_url)
        user.email_user("Welcome to {{project_name}}", msg, ignore_confirmed=True)

        return redirect("home")
Ejemplo n.º 44
0
def login(request):
    title = "MyCity | Login"
    msg = ""
    active = None
    if request.method == "POST":
        loginform = LoginForm(data=request.POST)
        if loginform.is_valid():
            user = authenticate(email=request.POST['email'],
             password=request.POST['password'])
            if user is not None:
                if user.is_active:
                    if not request.POST.get('remember_me', None):
                        request.session.set_expiry(0)
                    login_user(request, user)
                    return redirect('/')
                else:
                    active = False
                    msg = "Este e-mail ainda não está ativado! Favor verificar sua caixa de e-mail."
            else:
                active = False
                msg = "E-mail ou senha incorreto."
    else:
        loginform = LoginForm
    return render(request, 'mycity/login.html', {
        'title':title, 'loginform':loginform, 'active':active, 'msg':msg})
Ejemplo n.º 45
0
def AuthorizeDjango(request):
    names_dict = {}
    errors = []
    form = AuthorizeForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        data = form.cleaned_data
        names_list = ["login", "password"]
        names_dict = {x: request.POST.get(x, "") for x in names_list}

        login = data["login"]
        if not login:
            errors.append('Введите логин')
        password = data['password']

        if not password:
            errors.append("Введите пароль")

        if not errors:
            try:
                userdata = CustomerModel.objects.get(login=data["login"])
                if userdata.password != md5(password.encode('utf-8')).hexdigest():
                    errors.append("Неправильное имя пользователя или пароль")

            except CustomerModel.DoesNotExist:
                errors.append("Неправильное имя пользователя или пароль")
            if not errors:
                user = authenticate(username=login, password=password)
                if user is not None:
                    if request.user.is_authenticated():
                        pass
                    login_user(request, user)
                    return HttpResponseRedirect("/computers/")
    print(list(errors))
    return render(request, 'my_app/authorize.html', {"errors": errors, 'names_dict': names_dict, "form": form})
Ejemplo n.º 46
0
Archivo: api.py Proyecto: jq2st/inj-prj
def sign_up(request, data: Creds):
    try:
        user = User.objects.create_user(data.login, data.login, data.password)
        login_user(request, user)
        return 201, f"{user}"
    except Exception as err:
        return 401, f"{err}"
Ejemplo n.º 47
0
def login(request):
    error = None
    if request.method == "POST":
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        print('username', username)
        print('password', password)
        try:
            print([x.username for x in Admin.objects.all()])
            user = Admin.objects.get(username=username)
            if user.check_password(password):
                login_user(request, user)
                return redirect('dash')
            else:
                error = "Invalid login credentials"
        except Exception as e:
            error = "Invalid login credentials"
            print(e)

    context = {
        'port': Settings.objects.get().port,
        'ip': Settings.objects.get().ip,
        "error": error,
    }
    return render(request, 'login.html', context)
Ejemplo n.º 48
0
def login(request):
    from django.conf import settings

    if request.user.is_authenticated():
        return login_redirect(request)

    form = AuthenticationForm(request, request.POST or None,
                              captcha=bool(request.session.get('needs_captcha')))
    if form.is_valid():
        login_user(request, form.get_user())

        request.session.pop('needs_captcha', None)

        return login_redirect(request)

    elif request.POST and not request.session.get('needs_captcha'):
        request.session['needs_captcha'] = 1
        form = AuthenticationForm(request, request.POST or None, captcha=True)
        form.errors.pop('captcha', None)

    request.session.set_test_cookie()

    context = csrf(request)
    context.update({
        'form': form,
        'next': request.session.get('_next'),
        'CAN_REGISTER': settings.SENTRY_ALLOW_REGISTRATION or request.session.get('can_register'),
        'AUTH_PROVIDERS': get_auth_providers(),
        'SOCIAL_AUTH_CREATE_USERS': settings.SOCIAL_AUTH_CREATE_USERS,
    })
    return render_to_response('sentry/login.html', context, request)
Ejemplo n.º 49
0
def register(request):
    from sentry.conf import settings

    if not (settings.ALLOW_REGISTRATION or request.session.get("can_register")):
        return HttpResponseRedirect(reverse("sentry"))

    form = RegistrationForm(request.POST or None)
    if form.is_valid():
        user = form.save()

        # can_register should only allow a single registration
        request.session.pop("can_register", None)

        # HACK: grab whatever the first backend is and assume it works
        user.backend = dj_settings.AUTHENTICATION_BACKENDS[0]

        login_user(request, user)

        return login_redirect(request)

    return render_to_response(
        "sentry/register.html",
        {
            "form": form,
            "AUTH_PROVIDERS": get_auth_providers(),
            "SOCIAL_AUTH_CREATE_USERS": dj_settings.SOCIAL_AUTH_CREATE_USERS,
        },
        request,
    )
Ejemplo n.º 50
0
def login(request):
    from django.conf import settings

    if request.user.is_authenticated():
        return login_redirect(request)

    form = AuthenticationForm(request, request.POST or None,
                              captcha=bool(request.session.get('needs_captcha')))
    if form.is_valid():
        login_user(request, form.get_user())

        request.session.pop('needs_captcha', None)

        return login_redirect(request)

    elif request.POST and not request.session.get('needs_captcha'):
        request.session['needs_captcha'] = 1
        form = AuthenticationForm(request, request.POST or None, captcha=True)
        form.errors.pop('captcha', None)

    request.session.set_test_cookie()

    context = csrf(request)
    context.update({
        'form': form,
        'next': request.session.get('_next'),
        'CAN_REGISTER': settings.SENTRY_ALLOW_REGISTRATION or request.session.get('can_register'),
        'AUTH_PROVIDERS': get_auth_providers(),
        'SOCIAL_AUTH_CREATE_USERS': settings.SOCIAL_AUTH_CREATE_USERS,
    })
    return render_to_response('sentry/login.html', context, request)
Ejemplo n.º 51
0
def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            role = form.cleaned_data['role']
            password = form.cleaned_data['password']
            user = MyUser.objects.create_user(username=username,
                                              role=role,
                                              password=password)
            user.save()
            user = authenticate(username=username, password=password)
            login_user(request, user)
            messages.success(
                request,
                'You have signed up successfully! Please complete some further information.'
            )
            if role == 'tutor':
                tutor = Tutor()
                tutor.base_info = user
                tutor.name = username
                tutor.save()
                return HttpResponseRedirect(reverse('myAuth:signup_tutor'))
            else:
                student = Student()
                student.base_info = user
                student.name = username
                student.save()
                return HttpResponseRedirect(reverse('myAuth:signup_student'))
        messages.error(request, 'The username you used already exists!')
        return HttpResponseRedirect(reverse('myAuth:signup'))
    else:
        form = SignupForm()
        return render(request, 'signup.html', {'form': form})
Ejemplo n.º 52
0
def register(request):
    from django.conf import settings

    if not (settings.SENTRY_ALLOW_REGISTRATION or request.session.get('can_register')):
        return HttpResponseRedirect(reverse('sentry'))

    form = RegistrationForm(request.POST or None,
                            captcha=bool(request.session.get('needs_captcha')))
    if form.is_valid():
        user = form.save()

        # can_register should only allow a single registration
        request.session.pop('can_register', None)

        # HACK: grab whatever the first backend is and assume it works
        user.backend = settings.AUTHENTICATION_BACKENDS[0]

        login_user(request, user)

        request.session.pop('needs_captcha', None)

        return login_redirect(request)

    elif request.POST and not request.session.get('needs_captcha'):
        request.session['needs_captcha'] = 1
        form = RegistrationForm(request.POST or None, captcha=True)
        form.errors.pop('captcha', None)

    return render_to_response('sentry/register.html', {
        'form': form,
        'AUTH_PROVIDERS': get_auth_providers(),
        'SOCIAL_AUTH_CREATE_USERS': settings.SOCIAL_AUTH_CREATE_USERS,
    }, request)
Ejemplo n.º 53
0
def register(request, template_name='register.html'):
    if request.user.is_authenticated():
        return redirect('/')
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            #process the form
            email = request.POST.get('email', None)
            first_name = request.POST.get('first_name', None)
            last_name = request.POST.get('last_name', None)
            password = request.POST.get('password', None)
            user = get_user_model().objects.create_user(
                username=email,
                email=email,
                first_name=first_name,
                last_name=last_name,
                password=password,
            )
            user.save()
            user = authenticate(username=email, password=password)
            login_user(request, user)
            messages.success(request, "You have successfully registered and are now logged in.")
            return redirect(request.POST.get('next', '/'))
    else:
        initial = {'email': request.GET.get('email', None)}
        form = RegistrationForm(initial=initial)
    context = {'form': form, 'next': request.GET.get('next', None), }
    return render_to_response(template_name, context, RequestContext(request))
Ejemplo n.º 54
0
def signup_login_by_email(request, user_token, key_token):

    user = authenticate(user_token = user_token, key_token=key_token)
    if user:
        login_user(request, user)

        return redirect(settings.LOGIN_REDIRECT_URL)
    return HttpResponse('Your login link has expired or is invalid. Please select a new one.')
Ejemplo n.º 55
0
def login(request):
    if request.method == "POST":
        form = LoginForm(request.POST, prefix='login')
        if form.is_valid():
            login_user(request, form.get_user())
            logging.info(" ---> [%s] Login" % form.get_user())
            return HttpResponseRedirect(reverse('index'))

    return index(request)
Ejemplo n.º 56
0
def register(request):
    from django.conf import settings

    if not (features.has('auth:register') or request.session.get('can_register')):
        return HttpResponseRedirect(reverse('sentry'))

    form = RegistrationForm(request.POST or None,
                            captcha=bool(request.session.get('needs_captcha')))
    if form.is_valid():
        user = form.save()

        # TODO(dcramer): ideally this would be handled by a special view
        # specifically for organization registration
        if settings.SENTRY_SINGLE_ORGANIZATION:
            org = Organization.get_default()

            defaults = {
                'has_global_access': True,
                'type': OrganizationMemberType.MEMBER,
            }
            try:
                auth_provider = AuthProvider.objects.get(
                    organization=org.id,
                )
            except AuthProvider.DoesNotExist:
                pass
            else:
                defaults.update({
                    'has_global_access': auth_provider.default_global_access,
                    'type': auth_provider.default_role,
                })

            org.member_set.create(
                user=user,
                **defaults
            )

        # can_register should only allow a single registration
        request.session.pop('can_register', None)

        # HACK: grab whatever the first backend is and assume it works
        user.backend = settings.AUTHENTICATION_BACKENDS[0]

        login_user(request, user)

        request.session.pop('needs_captcha', None)

        return login_redirect(request)

    elif request.POST and not request.session.get('needs_captcha'):
        request.session['needs_captcha'] = 1
        form = RegistrationForm(request.POST or None, captcha=True)
        form.errors.pop('captcha', None)

    return render_to_response('sentry/register.html', {
        'form': form,
    }, request)
Ejemplo n.º 57
0
Archivo: views.py Proyecto: iiilx/bjj
def login(request):
    if request.method == 'POST': # If the form has been submitted...
        form = AuthenticationForm(data=request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
             login_user(request, form.get_user())
             return HttpResponseRedirect(reverse('home'))# Redirect after POST
    else:
        form = AuthenticationForm()
    return direct_to_template(request, 'login.html', {'form': form})
Ejemplo n.º 58
0
def login_as(request):
    if not request.user.is_staff:
        assert False
        return HttpResponseForbidden()
    username = request.GET['user']
    user = get_object_or_404(User, username=username)
    user.backend = settings.AUTHENTICATION_BACKENDS[0]
    login_user(request, user)
    return HttpResponseRedirect(reverse('index'))
Ejemplo n.º 59
0
def login(request):
    kwargs = convert_request(request)
    user = authenticate(**kwargs)

    if user:
        login_user(request, user)
        return API_Success("id=%d" % (user.id))
    else:
        return API_Error("username or password invalid")
Ejemplo n.º 60
0
def login_as(request):
    if not request.user.is_staff:
        logging.user(request, "~SKNON-STAFF LOGGING IN AS ANOTHER USER!")
        assert False
        return HttpResponseForbidden()
    username = request.GET['user']
    user = get_object_or_404(User, username__iexact=username)
    user.backend = settings.AUTHENTICATION_BACKENDS[0]
    login_user(request, user)
    return HttpResponseRedirect(reverse('index'))