示例#1
0
def first_step_register(request):
    salida = settings.FECHA_DE_SALIDA
    now = datetime.datetime.now()
    salida = relativedelta(salida, now)
    tipo_referencia = TipoReferencia.objects.filter(activo=True)
    form = FirstStepRegistrationForm()
    referencias = []
    referencias_list = []
    for tipo in tipo_referencia:
        referencias.append({'tipo_referencia': tipo,
                            'referencias': Referencia.objects.filter(activo=True, tipo=tipo).order_by('-id')})
    if request.method == 'POST':
        form = FirstStepRegistrationForm(request.POST)
        referencias_list = map(lambda x: int(x), request.POST.getlist('referencia'))
        if form.is_valid():
            nuevo_perfil = form.save()
            username = form.cleaned_data.get('email1').replace(" ", "").lower()
            password = form.cleaned_data.get('password')
            newuser = authenticate(username=nuevo_perfil.user.username, password=password)
            userlogin(request, newuser)
            return HttpResponseRedirect(reverse('second_step'))
    template = "templates_game/userprofile/account/registration_first_step.html"
    data = {'form': form, 'tipo_referencia': tipo_referencia, 'referencias': referencias,
            'referencias_list': referencias_list, 'salida': salida}
    return render_to_response(template, data, context_instance=RequestContext(request))
示例#2
0
def login(request):
    redirect_url = '/user/profile/'
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            cell = request.POST['cellphone']
            code = request.POST['code']
            user = authenticate(cellphone=cell, code_input=code)
            if user is not None:
                userlogin(request, user)
                if 'redirect' in request.POST:
                    redirect_url = request.POST['redirect']
                return HttpResponseRedirect(redirect_url)
    else:
        if 'redirect_to' in request.GET:
            redirect_url = request.GET['redirect_to']
        form = LoginForm()
    login_bool = request.user.is_authenticated()
    if login_bool:
        login_user = request.user.cellphone
    else:
        login_user = None
    return render(request, 'suiyuan/login.html', {
        'form': form,
        'redirect': redirect_url,
        'login_bool': login_bool,
        'user': login_user
    })
示例#3
0
def login(request):
    if request.method == "GET":
        return render(request, 'couriers/login.html')
    if request.method == "POST":
        result = {}
        phone = request.POST.get("phone")
        code = request.POST.get("code")
        vc = verify_phoneCode(phone=phone, code=code, type=USER_TYPE)
        if vc == 1:
            try:
                username = USER_LABEL + phone
                user = User.objects.get(username=username);
                userlogin(request,user)
                result["result"] = "success"
            except User.DoesNotExist:
                # result["errMsg"] = "手机号未注册用户,用户不存在,请先注册!"
                # result["result"] = "fail"
                user = User(username=username);
                user.set_password(username)
                user.is_active = 1
                user.save()
                userlogin(request, user)
                result["result"] = "success"
        elif vc == 2:
            result["errMsg"] = "验证码过期,请重新发送验证码!"
            result["result"] = "fail"
        elif vc == 3:
            result["errMsg"] = "验证码错误,请输入正确的验证码!"
            result["result"] = "fail"
        elif vc == 4:
            result["errMsg"] = "请先发送验证!"
            result["result"] = "fail"
        res = json.dumps(result)
        return HttpResponse(res.decode("unicode-escape"), content_type="application/json")
示例#4
0
def login(request):
    next = request.GET.get('next')
    logger.debug("Next in GET: %s" % next)
    if next is None and request.POST.get('next') is not None:
        next = request.POST.get('next')
        logger.debug("Next in POST: %s" % next)
    if next is None:
        next = "/"
    #next = next.replace('#', '%23')

    if request.method == "POST":
        # try:
        username = request.POST.get('username')
        password = request.POST.get('password')
        #logger.debug("Authenticating user [%s]" % username)
        user = authenticate(username=username, password=password)

        if user is not None and not user.removed:
            userlogin(request, user)
            # log_event(user=user, tenant=user.tenant, event_code="WMSUSER_LOGIN")
            return redirect(next)
        else:
            return render(request, 'login.html', {
                'error': 'fail',
                'next': next
            })
        # except KeyError:
        #     return render(request, 'login.html', {'next': next})
    else:
        return render(request, 'login.html', {'next': next})
示例#5
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:
            userlogin(request, user)
            if 'save_data' in request.session.keys():
                return redirect("savelist")
            elif 'health_info' in request.session.keys():
                return redirect('updatehealthinfo')
            elif 'from_calories' in request.session.keys():
                return redirect('caloriesindex')
            else:
                if not UserProfile.objects.filter(id=user.id).exists():
                    messages.success(
                        request,
                        f'First time log in, please edit your profile')
                    return redirect("edit_profile")
                else:
                    return redirect("index")

        else:
            messages.error(request, f'Invalid username or password')
            return render(request, "users/login.html")
    else:
        return render(request, "users/login.html")
示例#6
0
def login(request):
    if request.method == "GET":
        return render(request, 'couriers/login.html')
    if request.method == "POST":
        result = {}
        phone = request.POST.get("phone")
        code = request.POST.get("code")
        vc = verify_phoneCode(phone=phone, code=code, type=USER_TYPE)
        if vc == 1:
            try:
                username = USER_LABEL + phone
                user = User.objects.get(username=username)
                userlogin(request, user)
                result["result"] = "success"
            except User.DoesNotExist:
                # result["errMsg"] = "手机号未注册用户,用户不存在,请先注册!"
                # result["result"] = "fail"
                user = User(username=username)
                user.set_password(username)
                user.is_active = 1
                user.save()
                userlogin(request, user)
                result["result"] = "success"
        elif vc == 2:
            result["errMsg"] = "验证码过期,请重新发送验证码!"
            result["result"] = "fail"
        elif vc == 3:
            result["errMsg"] = "验证码错误,请输入正确的验证码!"
            result["result"] = "fail"
        elif vc == 4:
            result["errMsg"] = "请先发送验证!"
            result["result"] = "fail"
        res = json.dumps(result)
        return HttpResponse(res.decode("unicode-escape"),
                            content_type="application/json")
示例#7
0
def login_page(request):
    # if request.user.username:
    #     return redirect(homepage)
    message = ''
    form = LoginForm()
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():

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

            if user is None:
                message = 'Invalid login details!'
            else:
                userlogin(request, user)

                return redirect(book_list)
            # if user:
            #     if user.is_active:
            #         userlogin(request,user)
            #         # request.session['username']=username
            #         request.session['username']=(username)
            #         return redirect(homepage)

    return render(request, 'login/login.html', {
        'form': form,
        'message': message
    })
示例#8
0
文件: views.py 项目: shredz/Tool
def login (request):	
	if request.user.is_authenticated():
		return HttpResponseRedirect('/members/')
	
	if request.method == 'POST': 
		form = LoginForm(request.POST)
		if form.is_valid():
			username 				= form.cleaned_data['username']
			password				= form.cleaned_data['password']
			
			user = authenticate(username=username, password=password)
			
			if user is None:
				form.errors["username"]	= ErrorList([u'Invalid Username or Password'])
			else:
				s_user = User.objects.get(id=user.id)
				if s_user.verification.verified == False:
					form.errors["username"]	= ErrorList([u'User must be verified first due to "%s"' % (s_user.verification.purpose)])
				elif user.is_active:
					userlogin(request,user)
					return Response.send_to_destination(request)
				else:
					form.errors["username"]	= ErrorList([u'Account Disabled'])
	else:
		form = LoginForm()
		
	return Response.render_form (request,'members/login.html',form)
示例#9
0
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user and user.is_active:
            userlogin(request, user)
            return redirect('/')
        else:
            return render(request, 'login.html', {'msg': '用户名或密码错误'})
    return render(request, 'login.html')
示例#10
0
def user_register(request):
    if request.method == 'POST':
        form = UserRegisterForm(data=request.POST)
        if form.is_valid():
            new_user = form.save()
            new_user = authenticate(username=form.cleaned_data['username'],
                                    password=form.cleaned_data['password1'])
            userlogin(request, new_user)
            return HttpResponseRedirect(reverse('dashboard'))
    else:
        form = UserRegisterForm()
    return {'form': form}
示例#11
0
def user_register(request):
    if request.method == 'POST':
        form = UserRegisterForm(data=request.POST)
        if form.is_valid():
            new_user = form.save()
            new_user = authenticate(username=form.cleaned_data['username'],
                                    password=form.cleaned_data['password1'])
            userlogin(request, new_user)
            return HttpResponseRedirect(reverse('dashboard'))
    else:
        form = UserRegisterForm()
    return {'form': form}
示例#12
0
def login(request):
    if request.method == 'POST':
        user = authenticate(username=request.POST['username'],
                            password=request.POST['password'])
        if user is not None:
            userlogin(request, user)
            return redirect(reverse('loginapp:home'))
        else:
            loginform = AuthenticationForm(request.POST)
    else:
        loginform = AuthenticationForm()

    return render(request, 'login/login.html', {'login': loginform})
示例#13
0
def register(request):
    if request.method == 'POST':
        # form = UserCreationForm(request.POST)  BASIC USER CREATION FORM
        form = SignUpForm(request.POST)  #EXTENDED USER CREATION FORM
        if form.is_valid():
            form.save()
            user = authenticate(username=form.cleaned_data.get('username'),
                                password=form.cleaned_data.get('password'))
            userlogin(request, user)
            return redirect(reverse('loginapp:home'))

    else:
        form = SignUpForm()

    return render(request, 'login/register.html', {'form': form})
示例#14
0
def inviter_first_step_register(request, inviter_key):
    if not "inviter_key" in request.session:
        request.session['inviter_key'] = str(inviter_key)
    else:
        if request.session['inviter_key'] != str(inviter_key):
            request.session['inviter_key'] = str(inviter_key)

    salida = settings.FECHA_DE_SALIDA
    now = datetime.datetime.now()
    salida = relativedelta(salida, now)
    tipo_referencia = TipoReferencia.objects.filter(activo=True)
    form = FirstStepRegistrationForm()
    referencias = []
    referencias_list = []
    try:
        try:
            id = int(inviter_key[40:])
        except ValueError:
            id = 0
        perfil = Perfil.objects.get(id=id)
        #perfil = Perfil.objects.get(inviter_key=inviter_key)
        for tipo in tipo_referencia:
            referencias.append(
                    {'tipo_referencia': tipo, 'referencias': Referencia.objects.filter(activo=True, tipo=tipo)})
        if request.method == 'POST':
            form = FirstStepRegistrationForm(request.POST)
            referencias_list = map(lambda x: int(x), request.POST.getlist('referencia'))
            if form.is_valid():
                nuevo_perfil = form.save()
                username = form.cleaned_data.get('email1').replace(" ", "").lower()
                password = form.cleaned_data.get('password')
                now = datetime.datetime.now()
                new_contact_register = ContactsRegister.objects.create(invite_profile=nuevo_perfil, user_profile=perfil,
                    creado=now)
                newuser = authenticate(username=username, password=password)
                userlogin(request, newuser)
                if "inviter_key" in request.session: del request.session["inviter_key"]
                return HttpResponseRedirect(reverse('second_step'))
        print request.session['inviter_key']
        template = "templates_game/userprofile/account/registration_first_step.html"
        data = {'form': form, 'tipo_referencia': tipo_referencia, 'referencias': referencias,
                'referencias_list': referencias_list, 'salida': salida}
        return render_to_response(template, data, context_instance=RequestContext(request))
    except Perfil.DoesNotExist:
        raise Http404
示例#15
0
def login(request):
    from datetime import datetime 
    from pyfb import Pyfb
    from NossaCarona.settings import FACEBOOK_APP_ID, FACEBOOK_SECRET_KEY, FACEBOOK_REDIRECT_URL_LOGIN
    if request.GET.get('code'): #Login WITH facebook
        code =  request.GET['code']
        facebook = Pyfb(FACEBOOK_APP_ID)
        facebook.get_access_token(FACEBOOK_SECRET_KEY, code, redirect_uri=FACEBOOK_REDIRECT_URL_LOGIN)
        me = facebook.get_myself()
        userdjango = authenticate(fb_id=me.id)
        if not userdjango:
            userdjango = DjangoUser.objects.create_user(me.email, me.email, None)
            userdjango.first_name = me.first_name
            userdjango.last_name = me.last_name
            userdjango.save()
            usuario = Usuario(user=userdjango, sexo=me.gender[0], fb_id=me.id, dt_nascimento=datetime.strptime(me.birthday,'%m/%d/%Y'))
            usuario.save()
        userlogin(request,userdjango)
    else: #login WITHOUT facebook
        pass
    return HttpResponseRedirect('/')
示例#16
0
def login(request):
    if request.method == "GET":
        form = UserLoginForm()
        return render(request,
                      template_name='store/login.html',
                      context={'form': form})
    else:
        form = UserLoginForm(data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user:
                userlogin(request, user)

                session_cart = request.session.get('cart')
                if session_cart is None:
                    session_cart = []
                else:
                    for c in session_cart:
                        item = c.get('item')
                        quentity = c.get('quentity')
                        cart_obj = Cart()
                        cart_obj.product = Product.objects.get(id=item)
                        cart_obj.quentity = quentity
                        cart_obj.user = user
                        cart_obj.save()
                cart = Cart.objects.filter(user=user)
                session_cart = []
                for c in cart:
                    obj = {'item': c.product.id, 'quentity': c.quentity}
                    session_cart.append(obj)
                request.session['cart'] = session_cart
                return redirect("home")

        else:
            return render(request,
                          template_name='store/login.html',
                          context={'form': form})
示例#17
0
def login(request):
	# if user is already logged redirect to root
	if (request.user.is_authenticated()):
		redirect('')

	# user has posted login form - validate and login
	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:
					userlogin(request, user)
					return redirect('/')
				else: error = 'Потребителят е неактивен'
			else: error = 'Грешна потребителско име или парола'
		else:  error = 'Непозволени символи в потребителско име или парола'
		form = loginForm()
		t = get_template('login.html')
		c = RequestContext(request,{
			'form':form,
			'error': error,
			})
		html = t.render(c)
		return HttpResponse(html)
		
	# user hasnt posted form
	else:
		form = loginForm()
		t = get_template('login.html')
		c = RequestContext(request,{
			'form':form,
			'error':'',
			})
		html = t.render(c)
		return HttpResponse(html)
示例#18
0
def first_step_register(request):
    salida = settings.FECHA_DE_SALIDA
    now = datetime.datetime.now()
    salida = relativedelta(salida, now)
    tipo_referencia = TipoReferencia.objects.filter(activo=True)
    form = FirstStepRegistrationForm()
    referencias = []
    referencias_list = []
    for tipo in tipo_referencia:
        referencias.append({
            'tipo_referencia':
            tipo,
            'referencias':
            Referencia.objects.filter(activo=True, tipo=tipo).order_by('-id')
        })
    if request.method == 'POST':
        form = FirstStepRegistrationForm(request.POST)
        referencias_list = map(lambda x: int(x),
                               request.POST.getlist('referencia'))
        if form.is_valid():
            nuevo_perfil = form.save()
            username = form.cleaned_data.get('email1').replace(" ", "").lower()
            password = form.cleaned_data.get('password')
            newuser = authenticate(username=nuevo_perfil.user.username,
                                   password=password)
            userlogin(request, newuser)
            return HttpResponseRedirect(reverse('second_step'))
    template = "templates_game/userprofile/account/registration_first_step.html"
    data = {
        'form': form,
        'tipo_referencia': tipo_referencia,
        'referencias': referencias,
        'referencias_list': referencias_list,
        'salida': salida
    }
    return render_to_response(template,
                              data,
                              context_instance=RequestContext(request))
def login(request):

	#Load the view variables.
	context = {
		'title': 'User Login',
		'loginerror': False,
	}
	"""
	" This is the login logic.
	"""
	if 'username' in request.POST and 'password' in request.POST:

		#Get the formdata
		formdata = {
			#Get the user input
			'username' : request.POST['username'],
			'password' : request.POST['password'],
		}

		#Authenticate the user based on their input.
		user = authenticate(username=formdata['username'], password=formdata['password'])
		
		#Check if the user authenticated properly.
		if user:
			#Check if the user is active.
			if user.is_active:

				#Login the user
				userlogin(request,user)

				#This is the is_superuser
				if user.is_superuser:
					#If the user is a super user we check to
					#		see if the user groups are created.
					create_groups(user)
					#If there is not an ExtendedUser object associated with
					#		the admin we have to create one for the admin.
					if ExtendedUser.objects.filter(user=user).count() == 0:
						#Create a temporary phone number.
						extendeduser = ExtendedUser(user=user,phonenumber="000000000")
						#Save the ExtendedUser.
						extendeduser.save()
				#Check the next variable in the url
				#	for redirect to the original request.
				if 'next' in request.GET and request.GET['next'] != '/logout/':
					#Redirect to the original request.
					return redirect(request.GET['next'])
				else:
					#Redirect to the default view.
					return redirect('/')
			else:
				context['loginerror'] = "You have not been activated, please check your email"
		else:
			context['loginerror'] = "Incorrect username or password"

	"""
	" End the login logic.
	"""

	"""
	" Load the login form.
	"	This is run if:
	"	-User is not authenticated.
	"	-No POST information.
	"""
	context['AuthenticationForm'] = AuthenticationForm

	return render(request,
		  		  'user_management/login.html',
				  context)
	"""
示例#20
0
文件: views.py 项目: shredz/Tool
def after_connect(request , net_user , network):
	try:
		account = Account.objects.get(uid=net_user['id'])
		
		###
		if request.user.is_authenticated():
			if account.spiffuser.id != request.user.id:
				account.spiffuser = User.instance(request.user)
				
				
				## WARN TO GO WITH THAT ACCOUNT INSTEAD		
		###
		
		backend = get_backends()[0]
		account.spiffuser.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
		userlogin(request,account.spiffuser)
		
		if network == "facebook":
			account.oauth_token = net_user['access_token']
		elif network == "twitter":
			account.oauth_token = net_user['access_token'].key
			account.oauth_token_secret = net_user['access_token'].secret
		account.save()
		
	except Account.DoesNotExist:
		needs_username_correction = False
		
		if request.user.is_authenticated():
			user = User.instance(request.user)
		else:
			country = Country.objects.get(id=1)
				
			phonenumber = PhoneNumber(
				countrycode = 0,
				carriercode = 0,
				number 		= 0,
			)
			phonenumber.save()
				
			address = Address(
				zipcode 		= '',
				street_line_1	= '',	
				street_line_2	= '',
				city			= '',
				state			= '',
				country			= country,
				location 		= country.location,
				phonenumebr		= phonenumber
			)
			
			try:
				loc = get_field(net_user,"location",network)
				address.street_line_1	= loc
				address.city			= loc
			except:
				pass
				
			address.save()
			
			username = get_field(net_user,"username",network)
			
			
			try:
				User.objects.get(username=username)
				username = get_field(net_user,"id",network)
				needs_username_correction = True
				request.session['needs_username_correction'] = True
			except:
				pass
			
			user = User (
				username		= username,
				email			= get_field(net_user,"email",network),
				password		= "******",
				first_name		= '',
				last_name		= '',
				dob				= datetime.datetime.now(),
				gender			= '',
				address			= address,
				verification	= User.create_verification("1",True),
				is_active		= True,
				is_staff		= True,
				points			= 0,
			)
			
			try:
				user.first_name		= get_field(net_user,'first_name',network),
				user.last_name		= get_field(net_user,'last_name',network),
				user.gender			= ValueManager.translate_gender(get_field(net_user,'gender',network))
			except:
				pass
			
			user.save()
			
			backend = get_backends()[0]
			user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
			userlogin(request,user)
		
		token = net_user['access_token']
		del net_user['access_token']
		
		account = Account(
			uid					= get_field(net_user,'id',network),
			oauth_token			= "",
			oauth_token_secret	= "",
			other_data			= json.dumps(net_user),
			spiffuser			= user,
			account_type		= network
		)
		account.save()
		
		if network == "facebook":
			account.oauth_token 		= token
		elif network == "twitter":
			account.oauth_token 		= token.key
			account.oauth_token_secret 	= token.secret
			
		if needs_username_correction:
			return HttpResponseRedirect("/members/profile/")		
			
	return HttpResponseRedirect("/")
示例#21
0
def inviter_first_step_register(request, inviter_key):
    if not "inviter_key" in request.session:
        request.session['inviter_key'] = str(inviter_key)
    else:
        if request.session['inviter_key'] != str(inviter_key):
            request.session['inviter_key'] = str(inviter_key)

    salida = settings.FECHA_DE_SALIDA
    now = datetime.datetime.now()
    salida = relativedelta(salida, now)
    tipo_referencia = TipoReferencia.objects.filter(activo=True)
    form = FirstStepRegistrationForm()
    referencias = []
    referencias_list = []
    try:
        try:
            id = int(inviter_key[40:])
        except ValueError:
            id = 0
        perfil = Perfil.objects.get(id=id)
        #perfil = Perfil.objects.get(inviter_key=inviter_key)
        for tipo in tipo_referencia:
            referencias.append({
                'tipo_referencia':
                tipo,
                'referencias':
                Referencia.objects.filter(activo=True, tipo=tipo)
            })
        if request.method == 'POST':
            form = FirstStepRegistrationForm(request.POST)
            referencias_list = map(lambda x: int(x),
                                   request.POST.getlist('referencia'))
            if form.is_valid():
                nuevo_perfil = form.save()
                username = form.cleaned_data.get('email1').replace(" ",
                                                                   "").lower()
                password = form.cleaned_data.get('password')
                now = datetime.datetime.now()
                new_contact_register = ContactsRegister.objects.create(
                    invite_profile=nuevo_perfil,
                    user_profile=perfil,
                    creado=now)
                newuser = authenticate(username=username, password=password)
                userlogin(request, newuser)
                if "inviter_key" in request.session:
                    del request.session["inviter_key"]
                return HttpResponseRedirect(reverse('second_step'))
        print request.session['inviter_key']
        template = "templates_game/userprofile/account/registration_first_step.html"
        data = {
            'form': form,
            'tipo_referencia': tipo_referencia,
            'referencias': referencias,
            'referencias_list': referencias_list,
            'salida': salida
        }
        return render_to_response(template,
                                  data,
                                  context_instance=RequestContext(request))
    except Perfil.DoesNotExist:
        raise Http404