def addUser(request): if (request.method == 'POST'): login = request.body.decode("utf-8") parsed_json = json.loads(login) if (not auth.authenticate(username=parsed_json['login'], password=parsed_json['password']) and not User.objects.filter(password=parsed_json['password']).exists() and not User.objects.filter(username=parsed_json['login']).exists() and not User.objects.filter(email=parsed_json['email']).exists()): user = User.objects.create_user(parsed_json['login'], parsed_json['email'], parsed_json['password']) user.last_name = 0 if (len(parsed_json['description'])): user.last_name = 1 user.save() if (len(parsed_json['description'])): userProfile = UserProfile.objects.create(description=parsed_json['description']) userProfile.user_id = User.objects.get(username=parsed_json['login']).id userProfile.save() newuser = auth.authenticate(username=parsed_json['login'], password=parsed_json['password']) auth.login(request, newuser) return JsonResponse({'success': True, 'userId': user.id, 'worker': user.last_name }) elif (User.objects.filter(email=parsed_json['email']).exists()): return JsonResponse({'errorCode': 1 }) elif (User.objects.filter(password=parsed_json['password']).exists()): return JsonResponse({'errorCode': 2 }) elif (User.objects.filter(username=parsed_json['login']).exists()): return JsonResponse({'errorCode': 3 }) elif (auth.authenticate(username=parsed_json['login'], password=parsed_json['password'])): newuser = auth.authenticate(username=parsed_json['login'], password=parsed_json['password']) auth.login(request, newuser) else: return redirect('/')
def test_add_user(self): """ Tests the add_user command. """ with self.assertRaises(User.DoesNotExist): User.objects.get(username='******') call_command('add_user', 'foo', 'bar', '*****@*****.**') user = authenticate(username='******', password='******') self.assertIsNotNone(user) self.assertFalse(user.is_superuser) self.assertFalse(user.is_staff) self.assertTrue(user.is_active) call_command('add_user', 'foo_admin', 'bar', '*****@*****.**', is_superuser=True) user = authenticate(username='******', password='******') self.assertIsNotNone(user) self.assertTrue(user.is_superuser) self.assertFalse(user.is_staff) self.assertTrue(user.is_active) call_command('add_user', 'foo_admin1', 'bar', '*****@*****.**', is_staff=True, is_active=False) user = authenticate(username='******', password='******') self.assertIsNotNone(user) self.assertFalse(user.is_superuser) self.assertTrue(user.is_staff) self.assertFalse(user.is_active) # Make sure no error is thrown when creating a user that already exists call_command('add_user', 'foo_admin1', 'bar', '*****@*****.**', is_staff=True, is_active=False)
def login_view(request): context = {} if request.user.is_authenticated(): return HttpResponseRedirect(reverse('shirtmanager:index')) if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is None: try: email = User.objects.get(email=username) user = authenticate(username=email.username, password=password) except User.DoesNotExist: user = None if user is not None: login(request, user) return HttpResponseRedirect(reverse('shirtmanager:index')) else: messages.error(request, "Invalid credentials, please try again.") return render(request, 'shirtmanager/login.html', context)
def signup(request): if request.user and request.user.is_active: return redirect("hq") errors = {} email = "" password = "" if request.method == "POST": email = request.POST.get("email", None) password = request.POST.get("password", None) if not email: errors["email"] = "Please enter an email" elif not EMAIL_REGEX.match(email): errors["email"] = "Invalid email" if not password: errors["password"] = "******" elif len(password) < 6: errors["password"] = "******" if not len(errors): if User.objects.filter(email=email).exists(): user = authenticate(username=email, password=password) if user is not None and user.is_active: login(request, user) return redirect("hq") errors["email"] = "Email already registered" else: User.objects.create_user(email, email, password) user = authenticate(username=email, password=password) login(request, user) return redirect("hq") d = {"errors": errors, "email": email, "password": password} return render(request, "signup.html", d)
def signup(request): print 'SIGNUP!!!!!!!!!!!!!!!!!' print request.session['currentUrl'] if request.method == "POST" and 'buttonform1' in request.POST: form = SignupConfirmForm(request.POST) if form.is_valid(): user = User.objects.create_user( form.cleaned_data["username"], form.cleaned_data["email"], form.cleaned_data["password"], ) thisUser = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password']) if thisUser is not None and thisUser.is_active: auth.login(request, thisUser) return HttpResponseRedirect(request.session['currentUrl']) elif request.method == "POST" and 'buttonform2' in request.POST: username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None and user.is_active: auth.login(request, user) return HttpResponseRedirect(request.session['currentUrl']) else: return HttpResponse("Your username and password do not match.") else: form1 = SignupConfirmForm() form2 = SigninForm() data = { 'form1': form1, 'form2': form2, } return render(request, 'signup.html', data)
def clean(self): username = self.cleaned_data.get('username', '').lower() password = self.cleaned_data.get('password', '') user = User.objects.filter(Q(username__iexact=username) | Q(email=username)) if username and user: self.user_cache = authenticate(username=user[0].username, password=password) if self.user_cache is None: email_username = User.objects.filter(email=username) if email_username: self.user_cache = authenticate(username=email_username[0].username, password=password) if self.user_cache is None: # logging.info(" ***> [%s] Bad Login: TRYING JK-LESS PASSWORD" % username) jkless_password = password.replace('j', '').replace('k', '') self.user_cache = authenticate(username=username, password=jkless_password) if self.user_cache is None: logging.info(" ***> [%s] Bad Login" % username) raise forms.ValidationError(_("Whoopsy-daisy. Try again.")) else: # Supreme f**k-up. Accidentally removed the letters J and K from # all user passwords. Re-save with correct password. logging.info(" ***> [%s] FIXING JK-LESS PASSWORD" % username) self.user_cache.set_password(password) self.user_cache.save() elif not self.user_cache.is_active: raise forms.ValidationError(_("This account is inactive.")) elif username and not user: raise forms.ValidationError(_("That username is not registered. Create an account with it instead.")) return self.cleaned_data
def login(request): if request.method == 'POST': #check to see if form has been submitted form = LoginForm(request.POST) #capture data if form.is_valid(): #validate data cleaned_data = form.clean() username = cleaned_data['username'] password = cleaned_data['password'] if username and password: try: #attempt to use email to login currentuser = User.objects.get(email = username) user = auth.authenticate(username = currentuser.username, password = password) auth.login(request, user) return HttpResponseRedirect('/') except: #assume that an actual username has been entered user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: # Correct password, and the user is marked "active" auth.login(request, user) # Render home page. return HttpResponseRedirect('/') form = LoginForm() return render(request, 'login.html', {'form': form, 'form_error':True}) else: # Return to login page. form = LoginForm() return render(request, 'login.html', {'form': form, 'form_error':True}) else: form = LoginForm() #load blank form return render(request, 'login.html', {'form': form, 'form_error':False})
def registration(request): if request.user.is_authenticated(): return redirect('access') args = {} args.update(csrf(request)) args['form'] = UserCreationForm() if request.POST: newuser_form = UserCreationForm(request.POST) if len(request.POST.get('username')) < 6 or len(request.POST.get('username')) > 18 or not re.match( r'^[a-zA-Z0-9]+$', request.POST.get('username')): args['incorrect_login'] = "******" return render_to_response('registration/registration.html', args) if len(request.POST.get('password1')) < 6 or len(request.POST.get('password1')) > 18 or not re.match( r'^(?=[0-9+а-яА-ЯёЁa-zA-Z0-9]*(?=.*?\d).*)', request.POST.get('password1')): args['incorrect_password'] = "******" return render_to_response('registration/registration.html', args) if request.POST.get('password1') != request.POST.get('password2'): args['mismatch_passwords'] = "Пароли не совпадают" return render_to_response('registration/registration.html', args) if newuser_form.is_valid(): newuser_form.save() auth.authenticate(username=newuser_form['username'], password=newuser_form['password1']) args['success_registration'] = "Поздравляем! Вы успешно зарегистрировались в системе!" return render_to_response('login/login.html', args) else: args['form'] = newuser_form args['non_unique_login'] = "******" return render_to_response('registration/registration.html', args) else: return render_to_response('registration/registration.html', args)
def api_fetch_api_key(request, username=REQ(), password=REQ()): # type: (HttpRequest, str, str) -> HttpResponse return_data = {} # type: Dict[str, bool] if username == "google-oauth2-token": user_profile = authenticate(google_oauth2_token=password, realm_subdomain=get_subdomain(request), return_data=return_data) else: user_profile = authenticate(username=username, password=password, realm_subdomain=get_subdomain(request), return_data=return_data) if return_data.get("inactive_user") == True: return json_error(_("Your account has been disabled."), data={"reason": "user disable"}, status=403) if return_data.get("inactive_realm") == True: return json_error(_("Your realm has been deactivated."), data={"reason": "realm deactivated"}, status=403) if return_data.get("password_auth_disabled") == True: return json_error(_("Password auth is disabled in your team."), data={"reason": "password auth disabled"}, status=403) if user_profile is None: if return_data.get("valid_attestation") == True: # We can leak that the user is unregistered iff they present a valid authentication string for the user. return json_error(_("This user is not registered; do so from a browser."), data={"reason": "unregistered"}, status=403) return json_error(_("Your username or password is incorrect."), data={"reason": "incorrect_creds"}, status=403) return json_success({"api_key": user_profile.api_key, "email": user_profile.email})
def get_resource(request, file_location): try: username = request.session.get('username', None) remote_ip = request.META.get('REMOTE_ADDR', None) if remote_ip is not None: # Authenticated if the instance requests resource. instances = Instance.objects.filter(ip_address=remote_ip) authenticated = len(instances) > 0 elif username is not None: authenticate(username=username, password="") # User Authenticated by this line authenticated = True if not authenticated: raise Exception("Unauthorized access") path = settings.PROJECT_ROOT + "/init_files/" + file_location if os.path.exists(path): file = open(path, 'r') content = file.read() response = HttpResponse(content) # Download it, even if it looks like text response['Content-Disposition'] = \ 'attachment; filename=%s' % file_location.split("/")[-1] return response template = get_template('404.html') variables = RequestContext(request, { 'message': '%s not found' % (file_location,) }) output = template.render(variables) return HttpResponse(output) except Exception as e: logger.debug("Resource request failed") logger.exception(e) return HttpResponseRedirect(settings.REDIRECT_URL + "/login")
def test_authenticate(self): get_user_model()._default_manager.create_user(**self.user_data) user = authenticate(username='******', password='******') self.assertEqual(None, user) user = authenticate(username='******', password='******') db_user = User.objects.get(username='******') self.assertEqual(user.id, db_user.id)
def login_user(request): state = "Please log in below..." template="index.html" salon = None username = password = '' client_id='' if request.POST: username = request.POST.get('username') password = request.POST.get('password') user=None #print username; #print password; try : user=User.objects.get(email=username); if user is not None: user=authenticate(username=user.username,password=password) else : user = authenticate(username=username, password=password) except : user = authenticate(username=username, password=password) state="user is none" if user is not None: if user.is_active: login(request, user) else: state = "Your account is not active, please contact the site admin." else: state = "Your username and/or password were incorrect." page_context={"state":state} return render_to_response(template,page_context, context_instance=RequestContext(request))
def create_user(self): from django.contrib.auth import authenticate, login from django.contrib.auth.models import User if self.request.method == 'POST': form = UserForm(self.request.POST) if form.is_valid(): name = form.cleaned_data['fb_id'] password = form.cleaned_data['name'] #if the user already exists, log them in, o/w create them user = authenticate(username=name, password=password) if user is not None: login(self.request, user) else: user = User.objects.create_user(name, '', password) user.save() user = authenticate(username=name, password=password) login(self.request, user) else: #if a mobile user goes to the non mobile site, redirect them to the mobile site if self.request.MOBILE and not self.mobile: return HttpResponseRedirect(reverse('pickup_finder.views.mobile_home')) form = UserForm() if self.request.user.is_authenticated(): if self.mobile: return HttpResponseRedirect(reverse('pickup_finder.views.mobile_view_games')) else: return HttpResponseRedirect(reverse('pickup_finder.views.dashboard')) context = RequestContext(self.request, {'form' : form, 'facebook_id' : APIKeys.FACEBOOK_PROD, 'mobile' : self.mobile}) return render_to_response("index.html", context)
def lti(request, gid): graph = get_object_or_404(Graphs, pk=gid) if request.method != 'POST' or 'oauth_consumer_key' not in request.POST: return HttpResponse("Improper LTI request method", status=405) # confirm oauth credentials with ims_lti tool tool_provider = DjangoToolProvider(graph.lti_key, graph.lti_secret, request.POST) try: if tool_provider.valid_request(request) is False: raise PermissionDenied() except: raise PermissionDenied() # build username from userid userid = getattr(tool_provider, "user_id", None) if userid is None: raise PermissionDenied() username = "******" % (userid) # try to get the user user = authenticate(username=username) if user is None: u = User.objects.create_user(username=username) u.set_unusable_password() u.save() user = authenticate(username=username) # have the user ready to go, login login(request, user) # LTI user logged in, forward to map return HttpResponseRedirect(reverse("maps:display", kwargs={"gid":gid}))
def autenticar(request, matricula, rowguid): aluno = PreInscricao.objects.get(matricula=matricula) try: user = aluno.user_info.user user = authenticate(username=matricula, password=rowguid) if not user: user = aluno.user_info.user user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) request.session['site_interno'] = True return HttpResponseRedirect(reverse('portal.accounts.views.user_info', args=[request.user.id,])) except: aluno_role = UserDisciplineRole.objects.student_role() User.objects.create_user(aluno.email, aluno.email, rowguid).save() user = authenticate(username=aluno.email, password=rowguid) user_info = UserInfo(name=aluno.nome,city=aluno.cidade,province=aluno.estado,email=aluno.email, user=user, birth_date=aluno.data_nasc) user_info.save() aluno.user_info = user_info aluno.save() login(request, user) institutions = set() courses = set() for id_disc in aluno.disciplinas: try: disciplina = DisciplineMetadata.objects.get(cod_turma=id_disc, periodo=PERIODO_ATUAL).discipline institutions.add(disciplina.course.institution.id) courses.add(disciplina.course.id) #Associando a disciplina ao aluno queryset = RelUserDiscipline.objects.filter(role=aluno_role, user=user_info, discipline=disciplina, period=PERIODO_ATUAL) if not queryset.exists(): RelUserDiscipline(user=user_info, discipline=disciplina, role=aluno_role, period=PERIODO_ATUAL).save() #Associando o aluno ao curso queryset = RelUserCourse.objects.filter(role=UserCourseRole.objects.student_role(), user=user_info, course=disciplina.course, period=PERIODO_ATUAL) if not queryset.exists(): RelUserCourse(role=UserCourseRole.objects.student_role(), user=user_info, course=disciplina.course, period=PERIODO_ATUAL).save() #Associando o aluno à instituição de ensino queryset = RelUserInstitution.objects.filter(role=UserInstitutionRole.objects.student_role(), user=user_info, institution=disciplina.course.institution, period=PERIODO_ATUAL) if not queryset.exists(): RelUserInstitution(role=UserInstitutionRole.objects.student_role(), user=user_info, institution=disciplina.course.institution, period=PERIODO_ATUAL).save() except Exception, e: logging.exception(e) logging.error("[confirma_adicionar_aluno] - Nao foi possivel localizar a disciplina %s" % id_disc) #Para cada uma das instituicoes afetadas for inst in institutions: rebuild_caches_institution(inst) #Reconstroi a sua cache #Para cada um dos cursos afetados for course in courses: rebuild_caches_course(course) request.session['site_interno'] = True return HttpResponseRedirect(reverse('portal.accounts.views.user_info', args=[request.user.id,]))
def weibo_auth_end(request): code = request.GET['code'] client = APIClient(app_key=weibo_app_key, app_secret=weibo_app_secret, redirect_uri=weibo_call_back) r = client.request_access_token(code) uid = r.uid access_token = r.access_token expires_in = r.expires_in client.set_access_token(access_token, expires_in) response = HttpResponseRedirect("/") response.set_cookie('token', access_token) response.set_cookie('expires_in', str(int(expires_in))) response.set_cookie('weibo_uid', str(uid)) show=client.users.show.get(access_token=access_token, uid=uid) username = '******' + str(uid) password = '******' first_name = 'weibo' last_name = show['screen_name'] user = auth.authenticate(username=username, password=password) if user is None: user = User.objects.create_user(username=username, password=password) user.first_name = first_name user.last_name = last_name user.save() user = auth.authenticate(username=username, password=password) auth.login(request, user) return response
def process_registration(request): #See if registration already exists. If yes + correct PW, login + index.html. If yes + wrong PW, back to register 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 HttpResponseRedirect(reverse('homePage')) else: messages.success(request, "you're a user, but you have been disabled.") return HttpResponseRedirect(reverse('registration')) else: #If username isn't taken, create user and login try: new_user = User.objects.create_user(username=username, password=password) new_user.save() except: #TODO: specify exception classes messages.error(request, "Failed on create new user. Username is probably taken, try another.") return HttpResponseRedirect(reverse('registration')) try: #Now that the user has been created, we can authenticate with the user/pass we used to create them user_trying_again = authenticate(username=username, password=password) login(request, user_trying_again) except: messages.error(request, "Login failed after (possibly) creating user " + str(new_user)) return HttpResponseRedirect(reverse('homePage'))
def register_loginza_user(uid, provider, defaults, request): """ Register user in the system from Loginza OpenID :rtype: Profile """ # Check if user already exists but uses different OpenID if 'email' in defaults: try: user = Profile.objects.get(email=defaults['email']) except Profile.DoesNotExist: pass else: user = authenticate(email=user.email) auth_login(request, user) return user user, created = Profile.objects.get_or_create(uid=uid, provider=provider, is_active=True, defaults=defaults) if created: user.set_unusable_password() user.save() transfer_objects(request.user, user) user = authenticate(uid=uid, provider=provider) if user.is_active: auth_login(request, user) return user
def testFullProcess(self): """ Tests the full registration process for new accounts """ post_data = { 'username' : 'testActivationCodeUser', 'email' : '*****@*****.**', 'password1' : 'password', 'password2' : 'password', 'name' : 'pen_name', 'date_of_birth_year' : 1986, 'date_of_birth_month' : 8, 'date_of_birth_day' : 16, 'timezone' : 'Europe/London', 'country' : 'GB', } response = self.client.post(reverse('accounts:register'), post_data) self.assertEqual(response.status_code, 302) self.assertRedirects(response, reverse('accounts:register-done')) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Welcome to RPG Engine!') user = authenticate(username='******', password='******') self.assertFalse(user.is_active) user = User.objects.get(username="******") response = self.client.get(reverse('accounts:activate', args=[ user.registrationprofile_set.all()[0].activation_key])) self.assertEqual(response.status_code, 302) self.assertRedirects(response, reverse('accounts:activate-done')) user = authenticate(username='******', password='******') self.assertTrue(user.is_active)
def test_user_can_authenticate_with_username_parameter(self): auth = authenticate(username=self.email, password=self.password) self.assertEquals(self.user, auth) # Invalid username should be ignored auth = authenticate(email=self.email, password=self.password, username='******') self.assertEquals(self.user, auth)
def login(request): """Procesa el login""" if not request.user.is_authenticated(): username = request.POST.get('correo') password = request.POST.get('password') user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user) messages.success(request, '¡Bienvenido!') else: messages.error(request, 'Lo sentimos, esta cuenta está desactivada') else: # buscamos el correo, si no existe, lo mandamos a registro if existe_usuario(email=request.POST.get('correo', '')): messages.error(request, 'contraseña incorrecta') else: # lo procedemos a inscribir formulario = APILoginForm(request.POST) if formulario.is_valid(): nuevo_usuario = MODELO_USUARIO(username=username, email=username) nuevo_usuario.set_password(password) nuevo_usuario.save() user = auth.authenticate(username=username, password=password) auth.login(request, user) messages.success(request, 'Te has registrado!!') messages.info(request, 'Termina de llenar tu perfil') return HttpResponseRedirect('/perfil') else: messages.warning(request, 'datos de registro inválidos') return HttpResponseRedirect('/') messages.error(request, 'Nadie registrado con ese correo, verifique por favor') else: messages.warning(request, 'Ya tienes una sesión') return HttpResponseRedirect('/')
def test_delete(self): view_name='user_delete' """ User logged in should be able to delete user UMCloudDj.views.user_delete """ self.c = Client(); self.user = User.objects.get(username="******") self.user.set_password('hello') self.user.save() self.user = authenticate(username='******', password='******') login = self.c.login(username='******', password='******') testuser2 = User.objects.get(username="******") testuser2id = testuser2.id; requesturl = reverse(view_name, kwargs={'pk':testuser2id}) response = self.c.get(requesturl) self.assertEquals(response.status_code,200) view_name="user_delete" """ Logged in user deleting unknown user: 4040 UMCloudDj.views.user_delete """ self.c = Client(); self.user = User.objects.get(username="******") self.user.set_password('hello') self.user.save() self.user = authenticate(username='******', password='******') login = self.c.login(username='******', password='******') requesturl = reverse(view_name, kwargs={'pk':42}) response = self.c.get(requesturl) self.assertEqual(response.status_code, 404)
def test_authentication(self): auth_user = authenticate(username=self.my_user.email, password=self.my_user_raw_password) self.assertEqual(auth_user, self.my_user) auth_user = authenticate(username='******', password='******') self.assertIsNone(auth_user)
def make_and_login_participant(id_string, request): """ If there is a participant with this id_string, log them in. If not, create one and log them in. See: http://stackoverflow.com/questions/3222549/ how-to-automatically-login-a-user-after-registration-in-django """ # you'd better check before invoking this function. assert request.user.is_staff participant = get_object_or_404(Participant, id_string=id_string) if not participant.user: assert participant.user is None # do not mock this line. new_user = User() new_user.set_unusable_password() new_user.username = id_string new_user.save() participant.user = new_user participant.save() participant.user.backend = 'django.contrib.auth.backends.ModelBackend' assert participant.user is not None messages.info(request, "Logged in!") authenticate( username=participant.user.username, password=participant.user.password) login(request, participant.user) return participant
def openid_done(request, provider=None): """ When the request reaches here, the user has completed the Openid authentication flow. He has authorised us to login via Openid, so request.openid is populated. After coming here, we want to check if we are seeing this openid first time. If we are, we will create a new Django user for this Openid, else login the existing openid. """ if not provider: provider = request.session.get("openid_provider", "") if hasattr(request, "openid") and request.openid: # check for already existing associations openid_key = str(request.openid) if request.user and request.user.is_authenticated(): res = authenticate(openid_key=openid_key, request=request, provider=provider, user=request.user) if res: return HttpResponseRedirect(ADD_LOGIN_REDIRECT_URL + "?add_login=true") else: return HttpResponseRedirect(ADD_LOGIN_REDIRECT_URL + "?add_login=false") else: # authenticate and login user = authenticate(openid_key=openid_key, request=request, provider=provider) if user: login(request, user) if "openid_next" in request.session: openid_next = request.session.get("openid_next") if len(openid_next.strip()) > 0: return HttpResponseRedirect(openid_next) return HttpResponseRedirect(LOGIN_REDIRECT_URL) else: return HttpResponseRedirect(LOGIN_URL) else: return HttpResponseRedirect(LOGIN_URL)
def linkedin_login_done(request): request_token = request.session.get("linkedin_request_token", None) # If there is no request_token for session # Means we didn't redirect user to linkedin if not request_token: # Send them to the login page return HttpResponseRedirect(reverse("socialauth_login_page")) linkedin = LinkedIn(LINKEDIN_CONSUMER_KEY, LINKEDIN_CONSUMER_SECRET) verifier = request.GET.get("oauth_verifier", None) access_token = linkedin.getAccessToken(request_token, verifier) request.session["access_token"] = access_token if request.user and request.user.is_authenticated(): res = authenticate(linkedin_access_token=access_token, user=request.user) if res: return HttpResponseRedirect(ADD_LOGIN_REDIRECT_URL + "?add_login=true") else: return HttpResponseRedirect(ADD_LOGIN_REDIRECT_URL + "?add_login=false") else: user = authenticate(linkedin_access_token=access_token) # if user is authenticated then login user if user: login(request, user) else: # We were not able to authenticate user # Redirect to login page del request.session["access_token"] del request.session["request_token"] return HttpResponseRedirect(reverse("socialauth_login_page")) # authentication was successful, use is now logged in return HttpResponseRedirect(LOGIN_REDIRECT_URL)
def _func(request, *args, **kwargs): user = getattr(request, 'user', None) is_authenticated = getattr(user, 'is_authenticated', lambda: False) if ((user is not None and callable(is_authenticated) and not is_authenticated()) or user is None): user = None try: creds = args[:2] user = authenticate(username=creds[0], password=creds[1]) if user is not None: args = args[2:] except IndexError: if 'username' in kwargs and 'password' in kwargs: user = authenticate(username=kwargs['username'], password=kwargs['password']) if user is not None: kwargs.pop('username') kwargs.pop('password') else: raise InvalidParamsError( 'Authenticated methods require at least ' '[username, password] or {username: password:} arguments') if user is None: raise InvalidCredentialsError request.user = user return func(request, *args, **kwargs)
def reg_or_bind(request, uid, thrid, name='', avatar=''): if request.user.is_authenticated(): # login, bind new thrid account if not is_bound_by_other(request.user, uid, thrid): print 'bind new third account', uid to_eval = 'bind_%s_account(request.user,uid)' % thrid.lower() eval(to_eval) return HttpResponseRedirect('/account/') else: return HttpResponseRedirect('/login/bound/') else: # loggout or create new if not is_existed(uid): # not is User.username account = is_bound(uid, thrid) if account: # in Account.weibo_uid\douban_uid\qq_number print 'login bound third account', uid print 'user.username', account.user.username user = authenticate(uid=account.user.username) login(request, user) return HttpResponseRedirect('/account/') else: # create new account print 'create new account', uid to_eval = 'create_%s_account(uid=uid,name=name,avatar=avatar)' % thrid.lower( ) account = eval(to_eval) login(request, account.user) return HttpResponseRedirect('/account/') else: # login print 'login account', uid user = authenticate(uid=uid) login(request, user) return HttpResponseRedirect('/account/')
def login(request): if request.method == 'POST': try: user = request.POST['user'].strip() pwd = request.POST['pwd'].strip() except: return HttpResponseBadRequest() from django.contrib.auth import authenticate, login auth = authenticate(username = user , password = pwd) if auth is not None: login(request, auth) return HttpResponse() else: url = 'http://ws.espol.edu.ec/saac/wsandroid.asmx?WSDL' #http://ws.espol.edu.ec/saac/wsandroid.asmx?WSDL imp = Import('http://www.w3.org/2001/XMLSchema') imp.filter.add('http://tempuri.org/') doctor = ImportDoctor(imp) client = Client(url, doctor=doctor) auth = client.service.autenticacion(user,pwd) if auth == True: auth = User.objects.create_user(username=user, password=pwd) auth.save() auth = authenticate(username = user , password = pwd) login(request, auth) return HttpResponse() else: return HttpResponseBadRequest() else: return HttpResponseBadRequest()
def clean(self): data = self.cleaned_data # pylint: disable=no-member username = data.get('username') password = data.get('password') user = authenticate(username=username, password=password) # If the username was not found try the user using username as # the email address. It is valid because the edx-platform has # a unique constraint placed on the email field. if user is None: try: user_obj = User.objects.get(email=username) user = authenticate(username=user_obj.username, password=password) except User.DoesNotExist: user = None if ( user is None # TODO This is a temporary workaround while the is_active field on the # user is coupled with whether or not the user has verified ownership # of their claimed email address. Once is_active is decoupled from # verified_email, we can uncomment the following line. # or not user.is_active ): raise OAuthValidationError({'error': 'invalid_grant'}) data['user'] = user return data
password = form.cleaned_data['password'] try: validate_email(username_or_email) except Exception, e: username = username_or_email else: email = username_or_email try: user = User.objects.get(email=email) except Exception, e: username = '' else: username = user.username user = authenticate(username=username, password=password) login_error = False if user is not None and not user.groups.filter( name__exact='strangers').count(): if user.is_active: django_user_login(request, user) next_page = request.GET.get('next') if (next_page): return HttpResponseRedirect(next_page) else: return HttpResponseRedirect( reverse('bitfund.core.views.index')) else: login_error = 'your account is disabled' else: login_error = 'login / password key pair is wrong'
def test_login(request): test_user = authenticate(username='******', password='******') login(request, test_user) return redirect('/polls/new')
def clean(self): user = authenticate(username=self.cleaned_data.get('username')) return self.cleaned_data
def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials")
def token(request): data = request.data err = {} expire = 3600*720 if 'clientid' not in data: err['clientid'] = 'required' if 'clientsecret' not in data: err['clientsecret'] = 'required' if 'granttype' not in data: err['granttype'] = 'required' if err: return Response({'error/s':err},status= status.HTTP_400_BAD_REQUEST) if data['granttype'] == 'password': if 'username' not in data: err['username'] = '******' if 'password' not in data: err['password'] = '******' if 'usertype' not in data: err['usertype'] = 'required' else: if data['usertype'] not in ('intern','company'): err['usertype'] = 'invalid user' elif data['granttype'] == 'refeshtoken': if 'refreshtoken' not in data: err['refreshtoken'] = 'required' else: return Response({'error':'unsupported grant type'}) if err: return Response({'error/s':err},status= status.HTTP_400_BAD_REQUEST) else: client = Client.objects.filter(client_id = data['clientid'],client_secret = data['clientsecret']) if client.exists(): if data['granttype'] == 'password': if data['usertype'] == 'intern': user = Intern.objects.select_related('user__user','sub').filter(user__user__email = data['username']) if data['usertype'] == 'company': user = Company_User.objects.select_related('user__user').filter(user__user__email = data['username']) if not user.exists(): return Response({'error':'Invalid user'},status= status.HTTP_401_UNAUTHORIZED) else: user = list(user)[0] auth = authenticate(username=data['username'], password=data['password']) if auth: if 'sub' in request.GET and data['usertype'] == 'company' and request.GET['sub'] !='main': if user.sub.link != request.GET['sub']: return Response({'error':'Invalid Credentials'},status=status.HTTP_401_UNAUTHORIZED) token = AuthToken(client = list(client)[0],user = user.user.user,expires = expire) token.save() return Response({ 'token':token.token, 'refreshtoken':token.refresh_token, 'expires':token.expires, 'user':data['username'] }) else: return Response({'error':'Invalid Credentials'},status=status.HTTP_401_UNAUTHORIZED) elif data['granttype'] == 'refeshtoken': token = AuthToken.objects.select_related('user').filter(refresh_token = data['refreshtoken']) if token.exists() and not token.first().revoked: if (datetime.now - token.added).total_seconds > token.expire : return Response({'error':'time expired'},status= status.HTTP_401_UNAUTHORIZED) token = list(token)[0] refresh(token) return Response({ 'token':token.token, 'refreshtoken':token.refresh_token, 'expires':token.expires, 'user':token.user.username }) else: err = 'invalid token' else: return Reponse({'error':'unsupported grant type'}) else: err = 'invalid client' return Response({'error/s':err},status= status.HTTP_400_BAD_REQUEST)
def login(request): if request.method == 'POST': name=request.POST['name'] password=request.POST['password'] user=authenticate(request, us) return render(request,'authentication/login.html')
def test_authenticate_no_code(self): user = authenticate(self.request) self.assertIs(user, None)
def test_authenticates(self): self.assertEqual(authenticate(username='******', password='******'), self.user1)
def create_user_and_login(self, username: str, password: str): User.objects.create_user(username=username, password=password) user = authenticate(self.request, username=username, password=password) if user is not None: login(self.request, user)
def form_valid(self, form): response = super(RegistrationView, self).form_valid(form) user = authenticate(username=form.cleaned_data["username"], password=form.cleaned_data["password1"]) login(self.request, user) return response
def jwt_get_username_from_payload_handler(payload): username = payload.get('sub') authenticate(remote_user=username) return username
def clean(self): email = self.cleaned_data['email'] password = self.cleaned_data['password'] if not authenticate(email=email, password=password): raise forms.ValidationError("Invalid login")
def test_permission_denied(self): "user is not authenticated after a backend raises permission denied #2550" self.assertEqual(authenticate(username='******', password='******'), None)
def login(self, request, **kwargs): self.method_check(request, allowed=['post']) data = self.deserialize(request, request.body, format=request.META.get( 'CONTENT_TYPE', 'application/json')) email = data.get('email') new_user = False try: user = User.objects.get(email=email) new_user = False except User.DoesNotExist: u = User() u.email = data.get('email') u.first_name = data.get('first_name', "") u.last_name = data.get('last_name', "") u.profile_pic_url = data.get('profile_pic_url', "") u.details = data.get('details', "") u.user_type = data.get('user_type') u.save() new_user = True user = authenticate(email=email) if user and request.GET.get('type') == 'user': if user.user_type > 0: return self.create_response( request, { 'success': False, 'details': 'An vendor account is existed with the same email, try to login with another email' }) login(request, user) bundle = self.build_bundle(obj=user, request=request) bundle = self.full_dehydrate(bundle) return self.create_response( request, { 'success': True, 'sessionKey': request.session.session_key, 'user': bundle, 'new_user': new_user }) elif user and request.GET.get('type') == 'vendor': if user.user_type == 0: return self.create_response( request, { 'success': False, 'details': 'An User account is existed with the same email, try to login with another email' }) login(request, user) bundle = self.build_bundle(obj=user, request=request) bundle = self.full_dehydrate(bundle) return self.create_response( request, { 'success': True, 'sessionKey': request.session.session_key, 'user': bundle, 'new_user': new_user }) else: return self.create_response(request, { 'success': False, 'details': 'login failed' })
def clean(self): username = self.cleaned_data['username'] password = self.cleaned_data['password'] if not authenticate(username=username, password=password): raise forms.ValidationError(self.error_messages['password_incorrect'], code='password_incorrect', ) return self.cleaned_data
def clean_old_password(self): if not authenticate(username=self.username, password=self.cleaned_data.get('old_password')): raise ValidationError('旧密码输入错误') else: return self.cleaned_data.get('old_password')
def post(self, request): body = json.loads(request.body) if not body.get('method'): return Response(status=400) if body['method'] == 'google': try: googleUser = id_token.verify_oauth2_token( body['id_token'], requests.Request(), settings.GOOGLE_CLIENT_ID) except Exception as ex: return Response(str(ex), status=status.HTTP_404_NOT_FOUND, template_name=None, content_type=None) if googleUser['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: return Response(data={"Google internal problem."}, status=400) try: user = User.objects.get(email=googleUser['email']) except Exception as ex: if body.get('email'): username = body['email'] password = User.objects.make_random_password() user = User.objects.create_user(username, username) user.set_password(password) token, _ = Token.objects.get_or_create(user=user) print("google - created account for ", username) return Response({'token': token.key}, status=200) else: return Response(data={"Error creating google account."}, status=400) print("google - logged on ", body['email']) token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=200) if (body['method'] == 'password'): if body.get('email'): try: username = User.objects.get(email=body['email']).username except User.DoesNotExist: return Response(data={"Email not registered."}, status=400) elif body.get('username'): username = body['username'] else: return Response(data={"Username not registered."}, status=400) if not body.get('password'): return Response(data={"Missing or invalid password."}, status=400) user = authenticate(username=username, password=body['password']) if user is None: return Response(data={"Username or password invalid."}, status=400) token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=200) else: return Response(data={"Missing authentication method."}, status=400)
def home_view(request): context = common_data() context['active'] = 'home' context['company'] = CompanyRegister context['candidate'] = CandidateRegister context['loginform'] = LoginForm context['categories'] = models.CategoryModel.objects.all() context['posts'] = CompanyVacancy.objects.all()[:4] if not request.user.is_authenticated: if request.method == "POST": if request.is_ajax(): country = request.POST.get('country') countryModel = CountryModel.objects.filter(id=int(country)).last() data = CityModel.objects.filter(country=countryModel) result = [] for i in data: obj = { 'name': i.name, 'id': i.id } result.append(obj) return JsonResponse({ 'data': result }) if 'company' in request.POST: form = CompanyRegister(request.POST) if form.is_valid(): user = form.save(commit=False) # user.username = user.email user.set_password(request.POST.get('password1')) user.check = 'COM' user.city = CityModel.objects.filter(id=request.POST.get('city')).last() user.is_active = False user.save() messages.info( request, 'please verify your email' ) return redirect('home') else: context['company'] = form elif 'candidate' in request.POST: print('ASDGRHJM') form = CandidateRegister(request.POST) if form.is_valid(): user = form.save(commit=False) # user.username = user.email user.set_password(request.POST.get('password1')) user.check = 'CAN' user.is_active = False user.save() messages.info( request, 'please verify your email' ) return redirect('home') else: context['candidate'] = form else: login_form = LoginForm(request.POST) if login_form.is_valid(): username = login_form.cleaned_data.get('username') password = login_form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return redirect('home') else: apply = notifications(request) context['notifications'] = apply context['comps'] = MyUser.objects.filter(check='COM')[1:] return render(request, 'home.html', context)
def login(request): user = auth.authenticate(uid=request.GET.get('token')) if user: auth.login(request, user) return redirect('/')
def get(self, request): app = request.query_params.get('app', c.GURU) redirect_uri = '{}/auth/login-callback'.format( settings.FRONTEND_URL ) if app == c.USERS: redirect_uri = '{}/auth/login-callback'.format( settings.GLUU_USER_APP ) query_params = { 'code': request.query_params.get('code', ''), 'redirect_uri': redirect_uri, 'state': request.query_params.get('state', '') } token_json = api.get_token_from_callback(query_params) access_token = token_json.get('access_token') id_token = token_json.get('id_token') if not access_token: raise e.OxdError('Invalid token') user = authenticate( request, access_token=access_token, id_token=id_token ) if user is not None: company = user.company if not company: domain = user.email email_parts = user.email.split('@') if len(email_parts) > 1: domain = email_parts[1] companies = m.Company.objects.filter( website__icontains=domain ) if companies.count() == 1: membership, created = m.Membership.objects.get_or_create( user=user, company=companies[0] ) if created: membership.role = im.UserRole.objects.get(name='user') membership.is_primary = True membership.save() else: company = m.Company.objects.create( name=user.email ) m.Membership.objects.create( user=user, company=company, role=im.UserRole.objects.get(name='admin'), is_primary=True ) user_serializer = s.UserSerializer(user) return Response( { 'results': user_serializer.data }, status=status.HTTP_200_OK ) return Response( { 'user': '******' }, status=status.HTTP_403_FORBIDDEN )
def __call__(self, request, invitation_id, **kwargs): logging.info("Don't use this view in more apps until it gets cleaned up.") # add the correct parameters to this instance self.request = request self.inv_id = invitation_id if 'domain' in kwargs: self.domain = kwargs['domain'] if request.GET.get('switch') == 'true': logout(request) return redirect_to_login(request.path) if request.GET.get('create') == 'true': logout(request) return HttpResponseRedirect(request.path) try: invitation = Invitation.get(invitation_id) except ResourceNotFound: messages.error(request, _("Sorry, it looks like your invitation has expired. " "Please check the invitation link you received and try again, or request a " "project administrator to send you the invitation again.")) return HttpResponseRedirect(reverse("login")) if invitation.is_accepted: messages.error(request, _("Sorry, that invitation has already been used up. " "If you feel this is a mistake please ask the inviter for " "another invitation.")) return HttpResponseRedirect(reverse("login")) self.validate_invitation(invitation) if invitation.is_expired: return HttpResponseRedirect(reverse("no_permissions")) # Add zero-width space to username for better line breaking username = self.request.user.username.replace("@", "​@") context = { 'create_domain': False, 'formatted_username': username, 'domain': self.domain, 'invite_to': self.domain, 'invite_type': _('Project'), 'hide_password_feedback': settings.ENABLE_DRACONIAN_SECURITY_FEATURES, } if request.user.is_authenticated: context['current_page'] = {'page_name': _('Project Invitation')} else: context['current_page'] = {'page_name': _('Project Invitation, Account Required')} if request.user.is_authenticated: is_invited_user = request.couch_user.username.lower() == invitation.email.lower() if self.is_invited(invitation, request.couch_user) and not request.couch_user.is_superuser: if is_invited_user: # if this invite was actually for this user, just mark it accepted messages.info(request, _("You are already a member of {entity}.").format( entity=self.inviting_entity)) invitation.is_accepted = True invitation.save() else: messages.error(request, _("It looks like you are trying to accept an invitation for " "{invited} but you are already a member of {entity} with the " "account {current}. Please sign out to accept this invitation " "as another user.").format( entity=self.inviting_entity, invited=invitation.email, current=request.couch_user.username, )) return HttpResponseRedirect(self.redirect_to_on_success) if not is_invited_user: messages.error(request, _("The invited user {invited} and your user {current} do not match!").format( invited=invitation.email, current=request.couch_user.username)) if request.method == "POST": couch_user = CouchUser.from_django_user(request.user, strict=True) self._invite(invitation, couch_user) track_workflow(request.couch_user.get_email(), "Current user accepted a project invitation", {"Current user accepted a project invitation": "yes"}) send_hubspot_form(HUBSPOT_EXISTING_USER_INVITE_FORM, request) return HttpResponseRedirect(self.redirect_to_on_success) else: mobile_user = CouchUser.from_django_user(request.user).is_commcare_user() context.update({ 'mobile_user': mobile_user, "invited_user": invitation.email if request.couch_user.username != invitation.email else "", }) return render(request, self.template, context) else: if request.method == "POST": form = WebUserInvitationForm(request.POST) if form.is_valid(): # create the new user user = activate_new_user(form, domain=invitation.domain) user.save() messages.success(request, _("User account for %s created!") % form.cleaned_data["email"]) self._invite(invitation, user) authenticated = authenticate(username=form.cleaned_data["email"], password=form.cleaned_data["password"]) if authenticated is not None and authenticated.is_active: login(request, authenticated) track_workflow(request.POST['email'], "New User Accepted a project invitation", {"New User Accepted a project invitation": "yes"}) send_hubspot_form(HUBSPOT_NEW_USER_INVITE_FORM, request, user) return HttpResponseRedirect(reverse("domain_homepage", args=[invitation.domain])) else: if CouchUser.get_by_username(invitation.email): return HttpResponseRedirect(reverse("login") + '?next=' + reverse('domain_accept_invitation', args=[invitation.domain, invitation.get_id])) form = WebUserInvitationForm(initial={ 'email': invitation.email, 'hr_name': invitation.domain, 'create_domain': False, }) context.update({"form": form}) return render(request, self.template, context)
def authenticate_with_username(password: str, username: str, request: HttpRequest = None) -> Union[UserModel, None]: return authenticate(request=request, username=username, password=password)
def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Unable to log in with provided credentials.")
def alumneRecoverPasswd( request , username, oneTimePasswd ): client_address = getClientAdress( request ) infoForm = [ ('Usuari',username,),] if request.method == 'POST': form = recuperacioDePasswdForm( request.POST ) errors = [] if form.is_valid( ): passwd = form.cleaned_data['p1'] data_neixement = form.cleaned_data['data_neixement'] alumneOK = True try: alumneUser = AlumneUser.objects.get( username = username) dataOK = data_neixement == alumneUser.getAlumne().data_neixement a_temps = datetime.now() - timedelta( minutes = 30 ) codiOK = OneTimePasswd.objects.filter( usuari = alumneUser.getUser(), clau = oneTimePasswd, moment_expedicio__gte = a_temps, reintents__lt = 3 ) except AlumneUser.DoesNotExist: alumneOK = False if not alumneOK: errors.append( u'Dades incorrectes. Demaneu un altre codi de recuperació. Si el problema persisteix parleu amb el tutor.') elif codiOK and not dataOK: errors.append( u'La data proporcionada no és correcta.') codiOK[0].reintents += 1 codiOK[0].save() elif dataOK and not codiOK: errors.append( u"L'enllaç que esteu utilitzant està caducat o no és correcta. Demaneu un altre codi de recuperació.") elif not dataOK and not codiOK: errors.append( u"Dades incorrectes. Demaneu un altre codi de recuperació.") #todoBloquejar oneTimePasswd elif alumneUser.alumne.esBaixa(): errors.append( u'Cal parlar amb el tutor per recuperar accés a aquest compte.') elif codiOK and dataOK and not alumneUser.alumne.esBaixa(): alumneUser.set_password( passwd ) alumneUser.is_active = True alumneUser.save() if alumneUser.alumne.motiu_bloqueig: alumneUser.alumne.motiu_bloqueig = u"" alumneUser.alumne.save() user = authenticate(username=alumneUser.username, password=passwd) login( request, user ) if not errors: codiOK.update( reintents = 3 ) #apunto el login: LoginUsuari.objects.create( usuari = user, exitos = True, ip = client_address) url_next = '/' return HttpResponseRedirect( url_next ) else: try: #apunto el login: LoginUsuari.objects.create( usuari = alumneUser, exitos = False, ip = client_address) except: pass form._errors.setdefault(NON_FIELD_ERRORS, []).extend( errors ) else: form = recuperacioDePasswdForm( ) return render( request, 'form.html', {'form': form, 'infoForm':infoForm, 'head': u'Recuperació de Contrasenya' } )
def EditProfile(request): userdata = UserDetail.objects.filter(usr=request.user).first() first = FirstTask.objects.filter(usr=request.user).first() skdata = UserSkills.objects.filter(usr=request.user).first() up = UserPort.objects.filter(usr=request.user).first() pdata = Project.objects.all() error = False if request.method == "POST": if 'img' in request.FILES: i = request.FILES['img'] userdata.image = i userdata.save() return redirect('EditProfile') elif 'phone' in request.POST: phone = request.POST['phone'] userdata.phone = phone userdata.save() return redirect('EditProfile') elif 'projectname' in request.POST: Projectname = request.POST['projectname'] Profiletitle = request.POST['projecttype'] projectimg = request.FILES['projectimg'] Project.objects.create(usr=request.user, ProjectName=Projectname, ProjectType=Profiletitle, ProjectImg=projectimg) return redirect('EditProfile') elif 'skill' in request.POST: sk = request.POST['skill'] UserSkills.objects.update(usr=request.user, Skills=sk) return redirect('EditProfile') elif 'Linkedin' in request.POST: linkedin = request.POST['Linkedin'] UserPort.objects.update(usr=request.user, LinkedIn=linkedin) return redirect('EditProfile') elif 'Behance' in request.POST: linkedin = request.POST['Behance'] UserPort.objects.update(usr=request.user, Behance=linkedin) return redirect('EditProfile') elif 'Instagram' in request.POST: linkedin = request.POST['Instagram'] UserPort.objects.update(usr=request.user, Instagram=linkedin) return redirect('EditProfile') elif 'Twitter' in request.POST: linkedin = request.POST['Twitter'] UserPort.objects.update(usr=request.user, Twitter=linkedin) return redirect('EditProfile') elif 'Github' in request.POST: linkedin = request.POST['Github'] UserPort.objects.update(usr=request.user, Github=linkedin) return redirect('EditProfile') elif 'old' in request.POST: o = request.POST['old'] n = request.POST['new'] data = authenticate(usr=request.user.username, pas=o) if data: data.set_password(n) data.save() Logout(request) return SignIn(data) else: error = True else: return redirect('EditProfile') dis = { 'userdata': userdata, 'first': first, 'skill': skdata, 'userport': up, 'error': error, 'pdata': pdata } return render(request, 'profile_edit.html', dis)