def fetch_on_orcid_login(sender, sociallogin, **kwargs): """ Here we prepare some things, i.e. create a Researcher and require that the name on the orcid profile is public """ account = sociallogin.account # Only prefetch if the social login refers to a valid ORCID account orcid = validate_orcid(account.uid) if not orcid: raise ImmediateHttpResponse( render(kwargs['request'], 'dissemin/error.html', {'message': _('Invalid ORCID identifier.')})) profile = None # disabled account.extra_data because of API version mismatches user = None if '_user_cache' in account.__dict__: user = account.user r = Researcher.get_or_create_by_orcid(orcid, profile, user) if not r: # invalid ORCID profile (e.g. no name provided) raise ImmediateHttpResponse( render( kwargs['request'], 'dissemin/error.html', { 'message': _('Dissemin requires access to your ORCID name, ' 'which is marked as private in your ORCID profile.') }))
def pre_social_login(self, request, sociallogin): """ Lock down the logins so we only allow permitted domains or emails. If there is a domain whitelist, the email whitelist is ignored. """ user = sociallogin.user if settings.GOOGLE_OAUTH2_WHITELISTED_DOMAINS is not None: # we whitelist anyone from the domain: if user.email.split( '@')[1] not in settings.GOOGLE_OAUTH2_WHITELISTED_DOMAINS: raise ImmediateHttpResponse(render_to_response('error.html')) # skip checking white listed emails: return if settings.GOOGLE_OAUTH2_WHITELISTED_EMAILS is not None: # we whitelist only specified emails: if user.email in settings.GOOGLE_OAUTH2_WHITELISTED_EMAILS: # user is good return else: raise ImmediateHttpResponse(render_to_response('error.html')) # no whitelists found, do not permit any login raise ImmediateHttpResponse(render_to_response('error.html'))
def pre_social_login(self, request, sociallogin): user = sociallogin.user email = user.email if not email.split('@')[1] == 'iiitdmj.ac.in': messages.error(request, 'Use iiitdmj mail to sign in to this account !') raise ImmediateHttpResponse( render_to_response('account/exception.html')) else: if user.id: return try: # if user exists, connect the account to the existing account and login u = User.objects.get(email=email) sociallogin.state['process'] = 'connect' # authenticate(username=u.username, password=u.password) perform_login(request, u, 'none') return redirect('/') except User.DoesNotExist: exception_string = "Seems Like you don't \ have an account here! Contact CC admin for your account." messages.error(request, exception_string) raise ImmediateHttpResponse( render_to_response('account/exception_no_account.html'))
def pre_social_login(self, request, sociallogin): email_address = sociallogin.account.extra_data["email"].split('@')[1] #use for team's test using any gmail account w/o numbers infront #isInstructor = re.findall(r"(^[a-zA-Z.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)",sociallogin.account.extra_data["email"]) #uncomment below for usage on staff email isInstructor = re.findall(r"(^[a-zA-Z.][email protected]+$)",sociallogin.account.extra_data["email"]) # Pretty much hard code the login redirect url as the overwriting method above does not seem to be work if isInstructor != [] or sociallogin.account.extra_data["email"] in ("*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**"): #print("Pushing to instructor's home") settings.LOGIN_REDIRECT_URL = "TMmod:instHome2" elif not email_address == "smu.edu.sg": messages.error(request, "Please use an SMU account") raise ImmediateHttpResponse(HttpResponseRedirect(settings.LOGOUT_REDIRECT_URL)) else: #print("Pushing to student's home") try: stu = Student.objects.get(email=sociallogin.account.extra_data["email"]) stu.loginCounts += 1 stu.save() settings.LOGIN_REDIRECT_URL = "TMmod:home" except: messages.error(request, "SMU Account is not registered for Cloudtopus") raise ImmediateHttpResponse(HttpResponseRedirect(settings.LOGOUT_REDIRECT_URL))
def pre_social_login(self, request, sociallogin): """ Retrieve and verify (again) auth token that was provided with initial connect request. Store as request.user, as required for socialauth connect logic. """ self._update_session(request, sociallogin) try: authcode = get_session_authcode(request) if authcode is not None: accesstoken = accesstoken_for_authcode(authcode) if not accesstoken: raise ImmediateHttpResponse(HttpResponseForbidden()) request.user = accesstoken.user if sociallogin.is_existing and accesstoken.user != sociallogin.user: badgr_app = get_session_badgr_app(self.request) redirect_url = "{url}?authError={message}".format( url=badgr_app.ui_connect_success_redirect, message=urllib.quote( "Could not add social login. This account is already associated with a user." )) raise ImmediateHttpResponse( HttpResponseRedirect(redirect_to=redirect_url)) except AuthenticationFailed as e: raise ImmediateHttpResponse(HttpResponseForbidden(e.detail))
def pre_social_login_(sender, request, sociallogin, **kwargs): ''' Resolve issue of existing email address. When signing up a social account with the existing email address it will logged the existing user. And for security hole issue the account will not successfully logged if their given email address are not verified. To verify ownership of email this function will automatically send a verification link to the given email and only legit user can access the said account. :param sender: :param request: :param sociallogin: :param kwargs: :return: ''' email = sociallogin.account.extra_data['email'] _user = get_user_model() users = _user.objects.filter(email=email) _s_emails = s_emails.objects.filter(email=email) e_existing = _s_emails.exists() u_existing = users.exists() if u_existing : if e_existing: if _s_emails[0].verified: perform_login(request, users[0], app_settings.EMAIL_VERIFICATION) raise ImmediateHttpResponse(redirect(settings.LOGIN_REDIRECT_URL)) send_email_confirmation(request, users[0]) raise ImmediateHttpResponse(render(request, 'account/verification_sent.html', {}))
def is_open_for_signup(self, request: HttpRequest, social_login: SocialLogin) -> bool: """ Checks whether or not the site is open for signups. We override this method in order to prevent users from creating a new account using a non-Discord connection, as we require this connection for our users. """ if social_login.account.provider != "discord": add_message(request, ERROR, ERROR_CONNECT_DISCORD) raise ImmediateHttpResponse(redirect(reverse("home"))) try: user = DiscordUser.objects.get(id=int(social_login.account.uid)) except DiscordUser.DoesNotExist: add_message(request, ERROR, ERROR_JOIN_DISCORD) raise ImmediateHttpResponse(redirect(reverse("home"))) if user.roles.count() <= 1: add_message(request, ERROR, ERROR_JOIN_DISCORD) raise ImmediateHttpResponse(redirect(reverse("home"))) return True
def pre_social_login(self, request, sociallogin): """ Invoked just after a user successfully authenticates via a social provider, but before the login is actually processed. We use it to: 1. Check if the user is connecting accounts via signup page 2. store the name of the socialaccount provider in the user's session. TODO: When legacy Persona sessions are cleared (Nov 1 2016), this function can be simplified. """ session_login_data = request.session.get("socialaccount_sociallogin", None) request_login = sociallogin # Is there already a sociallogin_provider in the session? if session_login_data: session_login = SocialLogin.deserialize(session_login_data) # If the provider in the session is different from the provider in the # request, the user is connecting a new provider to an existing account if session_login.account.provider != request_login.account.provider: # Does the request sociallogin match an existing user? if not request_login.is_existing: # go straight back to signup page with an error message # BEFORE allauth over-writes the session sociallogin level = messages.ERROR message = "socialaccount/messages/account_not_found.txt" get_adapter().add_message(request, level, message) raise ImmediateHttpResponse( redirect("socialaccount_signup")) # Is the user banned? if sociallogin.is_existing: bans = UserBan.objects.filter(user=sociallogin.user, is_active=True) if bans.exists(): banned_response = render( request, "users/user_banned.html", { "bans": bans, "path": request.path }, ) add_never_cache_headers(banned_response) raise ImmediateHttpResponse(banned_response) # sociallogin_provider is used in the UI to indicate what method was # used to login to the website. The session variable # 'socialaccount_sociallogin' has the same data, but will be dropped at # the end of login. request.session["sociallogin_provider"] = sociallogin.account.provider request.session.modified = True
def pre_social_login(self, request, sociallogin): if sociallogin.user not in MyUser.objects.all(): self.save_user(request, sociallogin, None) user_login = login(request, sociallogin.user, 'django.contrib.auth.backends.ModelBackend') raise ImmediateHttpResponse( HttpResponseRedirect(reverse('socialregister'))) else: user_login = login(request, sociallogin.user, 'django.contrib.auth.backends.ModelBackend') raise ImmediateHttpResponse(HttpResponseRedirect(reverse("home")))
def pre_social_login(self, request, sociallogin): """Invoked just after a user successfully authenticates via a social provider, but before the login is actually processed (and before the pre_social_login signal is emitted). You can use this hook to intervene, e.g. abort the login by raising an ImmediateHttpResponse Why both an adapter hook and the signal? Intervening in e.g. the flow from within a signal handler is bad -- multiple handlers may be active and are executed in undetermined order.""" # Ignore existing social accounts, just do this stuff for new ones if sociallogin.is_existing: return # some social logins don't have an email address, e.g. facebook # accounts with mobile numbers only, but allauth takes care of this # case so just ignore it data = sociallogin.account.extra_data email = data.get('email').lower() name = data.get('name') verified = data.get('verified') if not all([email, name, verified]): msg = _(self.not_verified) % {'name': name, 'email': email} messages.error(request, msg) raise ImmediateHttpResponse(redirect('prodsys')) contributor = get_instance( Contributor, dict(status=Contributor.ACTIVE, email=email), dict(status=Contributor.ACTIVE, display_name=name) ) if contributor: user = connect_contributor_to_user(contributor, create=True) else: user = get_instance(User, dict(email=email)) if not user: msg = _(self.unknown_user) % {'name': name, 'email': email} messages.error(request, msg) raise ImmediateHttpResponse(redirect('prodsys')) user.email = email if not user.get_full_name(): user.first_name = data.get('first_name') user.last_name = data.get('last_name') user.save() return sociallogin.connect(request, user)
def pre_social_login(self, request, sociallogin): credential_name = u"{}'s {} credential".format( sociallogin.user.username or request.user.username, sociallogin.token.app.name) if sociallogin.token.app.provider == 'twitter': form = CredentialTwitterForm({ 'name': credential_name, 'platform': Credential.TWITTER, 'consumer_key': sociallogin.token.app.client_id, 'consumer_secret': sociallogin.token.app.secret, 'access_token': sociallogin.token.token, 'access_token_secret': sociallogin.token.token_secret, }) elif sociallogin.token.app.provider == 'tumblr': form = CredentialTumblrForm({ 'name': credential_name, 'platform': Credential.TUMBLR, 'api_key': sociallogin.token.app.client_id, }) elif sociallogin.token.app.provider == 'weibo': form = CredentialWeiboForm({ 'name': credential_name, 'platform': Credential.WEIBO, 'access_token': sociallogin.token.token, }) else: assert False, "Unrecognized social login provider" form.instance.user = request.user try: credential = form.save() except IntegrityError: messages.warning(request, "Credential already exists.") raise ImmediateHttpResponse( HttpResponseRedirect(reverse('credential_list'))) messages.info(request, "New credential created.") raise ImmediateHttpResponse( HttpResponseRedirect( reverse('credential_detail', args=(credential.pk, ))))
def authentication_error( self, request, provider_id, error=None, exception=None, extra_context=None ): if not request.user.is_anonymous: messages.error( request, ( f"You are already logged in as {request.user.username}. " "Please logout first to login as another user" ), ) raise ImmediateHttpResponse(redirect("home")) else: messages.error(request, "Couldn't Log you in.Please Try Again!") raise ImmediateHttpResponse(redirect("home"))
def update_user_fields(self, request, sociallogin=None, user=None): changed = False if user is None: user = sociallogin.account.user office365_provider = registry.by_id(Office365Provider.id, request) false_keys = ["is_staff", "is_superuser"] boolean_keys = false_keys + ["is_active"] copy_keys = boolean_keys + ["first_name", "last_name", "email"] if sociallogin is not None and sociallogin.account.provider == Office365Provider.id: data = sociallogin.account.extra_data values = office365_provider.extract_common_fields(data) for key in copy_keys: # it is assumed that values are cleaned and set for all # fields and if any of the boolean_keys are not provided # in the raw data they should be set to False by # the extract_common_fields method if key in values and getattr(user, key) != values[key]: setattr(user, key, values[key]) changed = True else: for key in false_keys: if getattr(user, key): msg = "Staff users must authenticate via the %s provider!" % office365_provider.name response = HttpResponseForbidden(msg) raise ImmediateHttpResponse(response) return changed, user
def pre_social_login(self, request, sociallogin): u = sociallogin.account.user if not u.email.split('@')[1] in [ 'luizalabs.com', 'magazineluiza.com.br' ]: raise ImmediateHttpResponse('Invalid domain')
def authentication_error(self, request, provider_id, error=None, exception=None, extra_context=None): provider = providers.registry.by_id(provider_id) retry_url = provider.get_login_url(request, **dict(request.GET.iteritems())) tb = traceback.format_exc() log_exception(request, exception, tb) ctx = { 'social_error': jsonify({ 'error': error, 'exception': { 'name': exception.__class__.__name__, 'msg': unicode(exception), }, 'provider': provider.name, 'retry_url': retry_url, }), } raise ImmediateHttpResponse( response=render(request, 'account/social_error.html', ctx))
def pre_social_login(self, request, sociallogin): """Hook to be run after receiving the OK from the social provider but before completing the social login process. At this time no new user accounts have been created and the user is still in the process of signing in. The provider has also pre-filled the user data in `sociallogin.user`. We'll use this hook to customize Allauth's default behavior so that sociallogin users reporting an email address that already exists in the system will need to verify they actually own the user account owning such email in Pootle. """ email_address = sociallogin.user.email # There's a SocialAccount already for this login or the provider # doesn't share an email address: nothing to do here if sociallogin.user.pk is not None or not email_address: return # If there's already an existing email address on the system, # we'll ask for its connected user's password before proceeding. user = get_user_by_email(email_address) if user is not None: # Save `SocialLogin` instance for our custom view request.session['sociallogin'] = sociallogin.serialize() raise ImmediateHttpResponse( response=SocialVerificationView.as_view()(request))
def pre_social_login(self, request, sociallogin): User = get_user_model() # TODO: make sure that the partnership is still in good standing or valid or whatever if sociallogin.user.pk: set_country(sociallogin.user, request) logger.info("setting connection to {}".format( sociallogin.user.profile.country)) return try: # if user exists, connect the account to the existing account and login new_login_user = User.objects.get(email=sociallogin.user.email) except User.DoesNotExist: url = reverse('sociallogin_notamember', kwargs={ 'email': urlsafe_base64_encode(sociallogin.user.email) }) raise ImmediateHttpResponse(HttpResponseRedirect(url)) sociallogin.connect(request, new_login_user) set_country(new_login_user, request) perform_login(request, new_login_user, 'none', redirect_url=sociallogin.get_redirect_url(request), signal_kwargs={"sociallogin": sociallogin})
def pre_social_login(self, request, sociallogin): email = sociallogin.account.extra_data['email'].lower() if not re.match('.*cmu.edu$', email): messages.warning(request, 'You must log in with CMU account.') raise ImmediateHttpResponse(render(request, 'qq/index.html')) else: return
def pre_social_login(self, request, sociallogin): try: user = User.objects.get(username=sociallogin.user.username) sociallogin.connect(request, user) raise ImmediateHttpResponse("Account already exists!!") except Exception as e: print(e)
def pre_social_login(self, request, sociallogin): User = get_user_model() if User.objects.filter(username=sociallogin.user.username, is_researcher=False).exists(): raise ImmediateHttpResponse( redirect(reverse_lazy('local-user-already-exists'))) return super().pre_social_login(request, sociallogin)
def authentication_error(self, request, provider_id, error=None, exception=None, extra_context=None): provider = providers.registry.by_id(provider_id) retry_url = provider.get_login_url(request, **dict(iter(request.GET.items()))) tb = traceback.format_exc() log_exception(request, exception, tb) ctx = { "social_error": { "error": error, "exception": { "name": exception.__class__.__name__, "msg": str(exception), }, "provider": provider.name, "retry_url": retry_url, }, } raise ImmediateHttpResponse( response=render(request, "account/social_error.html", ctx))
def pre_social_login(self, request, sociallogin): u = sociallogin.user if u.email.split("@")[1] not in settings.ALLOWED_DOMAINS: messages.error( request, "Please login through bits-mail or contact the administrator." ) raise ImmediateHttpResponse(render(request, "registration/login.html"))
def pre_social_login(self, request, sociallogin): user = sociallogin.user if user.id: return if not user.email: raise ImmediateHttpResponse( response=HttpResponseRedirect(reverse('home'))) try: # if user exists, connect the account to the existing account and # login user = DplUser.objects.get(email=user.email) sociallogin.state['process'] = 'connect' next_url = request.GET.get('next') if not next_url: next_url = reverse('home') perform_login(request, user, 'none', redirect_url=next_url, signal_kwargs=None, signup=False) except DplUser.DoesNotExist: pass
def pre_social_login(self, request, sociallogin): process = sociallogin.state.get('process', None) if process == 'connect': logger.info("Connecting social account", extra={ "user": request.user, "provider": sociallogin.account.provider, "uid": sociallogin.account.uid, }) return if not sociallogin.is_existing: if not self.check_facebook_groups(sociallogin): logger.warning("Social login denied", extra={ 'user uid': sociallogin.account.uid, 'provider': sociallogin.account.provider, }) raise ImmediateHttpResponse( render(request, "users/fb_group_required.html")) logger.info("pre social login", extra={ "allauth_process": process, "user": request.user, "provider": sociallogin.account.provider, "user_uid": sociallogin.account.uid, })
def pre_social_login(self, request, sociallogin): """ This hook is invoked just after a user successfully authenticates via a social provider, but before the login is actually processed (and before the pre_social_login signal is emitted). TODO: This code is unfortunately tied to a specific client for the edge case of a duplication of social email. In this event, the service will respond with a 302 to the client's login page until REST endpoints for authentication are enabled. """ # Ignore existing social accounts if sociallogin.is_existing: return # Check if given email address already exists try: social_user = sociallogin.user social_email = social_user.email EmailAddress.objects.get(email=social_email) # Email does not exist, allauth will handle a new social account except EmailAddress.DoesNotExist: return # Email exists, redirect to login page client_url = settings.MAGNA_URL + '/login?email=' + social_email raise ImmediateHttpResponse(redirect(client_url))
def pre_social_login(self, request, sociallogin): if not self.is_open_for_signup(request, sociallogin): raise ImmediateHttpResponse( render( request, "account/signup_closed.html", ))
def pre_social_login(self, request, sociallogin): """ Invoked just after a user successfully authenticates via a social provider, but before the login is actually processed. We use it to: 1. Check if the user is connecting accounts via signup page 2. store the name of the socialaccount provider in the user's session. """ session_login_data = request.session.get('socialaccount_sociallogin', None) request_login = sociallogin # Is there already a sociallogin_provider in the session? if session_login_data: session_login = SocialLogin.deserialize(session_login_data) # If the provider in the session is different from the provider in the # request, the user is connecting a new provider to an existing account if session_login.account.provider != request_login.account.provider: # Does the request sociallogin match an existing user? if not request_login.is_existing: # go straight back to signup page with an error message # BEFORE allauth over-writes the session sociallogin level = messages.ERROR message = "socialaccount/messages/account_not_found.txt" get_adapter().add_message(request, level, message) raise ImmediateHttpResponse( redirect('socialaccount_signup')) # TODO: Can the code that uses this just use request.session['socialaccount_sociallogin'].account.provider instead? request.session['sociallogin_provider'] = ( sociallogin.account.provider) request.session.modified = True
def pre_social_login(self, request, sociallogin): if sociallogin.is_existing: return if "email" not in sociallogin.account.extra_data: return qs = models.EmailAddress.objects.filter( email__iexact=sociallogin.account.extra_data["email"]) if qs.exists(): user = qs[0].user account = user.socialaccount_set.first() provider = providers.registry.by_id( account.provider) if account else None social = providers.registry.by_id(sociallogin.account.provider) messages.error( request, _("A {provider} account already exists for {email}. " "Please log in with that account and link with your " "{social} account on the profile page.").format( email=user.email, provider=provider.name if provider else _("local or LDAP"), social=social.name, ), ) raise ImmediateHttpResponse(redirect("/accounts/login"))
def pre_social_login(self, request, sociallogin): email_domain = sociallogin.user.email.split('@')[1].lower() if email_domain not in settings.ALLOWED_EMAIL_DOMAINS: # TODO nice template raise ImmediateHttpResponse( HttpResponse(sociallogin.user.email + ' is not valid member of ' + str(settings.ALLOWED_EMAIL_DOMAINS)))
def pre_social_login(self, request, sociallogin): try: user = User.objects.get( email=sociallogin.account.extra_data['email']) perform_login(request, user, email_verification='optional') raise ImmediateHttpResponse(redirect(settings.LOGIN_REDIRECT_URL)) except User.DoesNotExist: pass