def user_and_notifications(request): if not request.user.is_authenticated(): return {} profile = UserProfile(id=request.user.id) notifications = profile.recent_notifications() notifications_json = "[" + ",".join([n.to_JSON() for n in notifications]) + "]" interrupting_message = profile.interrupting_message() if interrupting_message: interrupting_message_json = json.dumps({ "name": interrupting_message, "html": render_to_string("messages/%s.html" % interrupting_message) }) else: interrupting_message_json = "null" return { "notifications": notifications, "notifications_json": notifications_json, "notifications_html": notifications.to_HTML(), "notifications_count": profile.unread_notification_count(), "interrupting_message_json": interrupting_message_json, "partner_group": profile.partner_group, "partner_role": profile.partner_role }
def notifications(request): if not request.user.is_authenticated(): if request.COOKIES.get("_ga", None) and not request.COOKIES.get("welcomeToS2LoggedOut", None): # Welcome returning visitors only to the new Sefaria. TODO this should be removed after some time. interrupting_message_json = json.dumps({ "name": "welcomeToS2LoggedOut", "html": render_to_string("messages/welcomeToS2LoggedOut.html") }) else: interrupting_message_json = "null" return {"interrupting_message_json": interrupting_message_json} profile = UserProfile(id=request.user.id) notifications = profile.recent_notifications() notifications_json = "[" + ",".join([n.to_JSON() for n in notifications]) + "]" interrupting_message = profile.interrupting_message() if interrupting_message: interrupting_message_json = json.dumps({"name": interrupting_message, "html": render_to_string("messages/%s.html" % interrupting_message)}) else: interrupting_message_json = "null" return { "notifications": notifications, "notifications_json": notifications_json, "notifications_html": notifications.to_HTML(), "notifications_count": profile.unread_notification_count(), "interrupting_message_json": interrupting_message_json, }
def register(request): request_context = RequestContext(request) if request.user.is_authenticated(): return HttpResponseRedirect("/login") next = request.REQUEST.get('next', '') if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): new_user = form.save() user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password1']) auth_login(request, user) p = UserProfile(id=user.id).assign_slug() p.settings["interface_language"] = request_context.get("interfaceLang") p.save() if "noredirect" in request.POST: return HttpResponse("ok") elif "new?assignment=" in request.POST.get("next",""): next = request.POST.get("next", "") return HttpResponseRedirect(next) else: next = request.POST.get("next", "/") + "?welcome=to-sefaria" return HttpResponseRedirect(next) else: form = NewUserForm() return render_to_response("registration/register.html", {'form' : form, 'next': next}, RequestContext(request))
def subscribe_to_list(lists, email, first_name=None, last_name=None, direct_sign_up=False, bypass_nationbuilder=False): from sefaria.model.user_profile import UserProfile if not sls.NATIONBUILDER: return if bypass_nationbuilder: name = first_name + " " + last_name if first_name and last_name else "" method = "Signed up directly" if direct_sign_up else "Signed up during account creation" message_html = "%s<br>%s<br>%s" % (name, email, method) subject = "Mailing list signup" from_email = "Sefaria <*****@*****.**>" to = "*****@*****.**" msg = EmailMultiAlternatives(subject, message_html, from_email, [to]) msg.content_subtype = "html" # Main content is now text/html msg.send() return True tags = lists post = { "person": { "email": email, "tags": tags, } } if first_name: post["person"]["first_name"] = first_name if last_name: post["person"]["last_name"] = last_name session = get_nationbuilder_connection() r = session.put("https://" + sls.NATIONBUILDER_SLUG + ".nationbuilder.com/api/v1/people/push", data=json.dumps(post), params={'format': 'json'}, headers={'content-type': 'application/json'}) try: # add nationbuilder id to user profile nationbuilder_user = r.json() nationbuilder_id = nationbuilder_user["person"][ "id"] if "person" in nationbuilder_user else nationbuilder_user[ "id"] user_profile = UserProfile(email=email) if user_profile.id != None and user_profile.nationbuilder_id != nationbuilder_id: user_profile.nationbuilder_id = nationbuilder_id user_profile.save() except: pass session.close() return r
def process_register_form(request, auth_method='session'): form = SefariaNewUserForm( request.POST) if auth_method == 'session' else SefariaNewUserFormAPI( request.POST) token_dict = None if form.is_valid(): with transaction.atomic(): new_user = form.save() user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password1']) p = UserProfile(id=user.id) p.assign_slug() p.join_invited_collections() if hasattr(request, "interfaceLang"): p.settings["interface_language"] = request.interfaceLang p.save() if auth_method == 'session': auth_login(request, user) elif auth_method == 'jwt': token_dict = TokenObtainPairSerializer().validate({ "username": form.cleaned_data['email'], "password": form.cleaned_data['password1'] }) return { k: v[0] if len(v) > 0 else str(v) for k, v in list(form.errors.items()) }, token_dict, form
def user_and_notifications(request): """ Load data that comes from a user profile. Most of this data is currently only needed view /data.js (currently Node does not get access to logged in version of /data.js) """ if not request.user.is_authenticated: return { "interrupting_message_json": InterruptingMessage(attrs=GLOBAL_INTERRUPTING_MESSAGE, request=request).json() } profile = UserProfile(id=request.user.id) if request.path == "/texts": return { "saved": profile.get_user_history(saved=True, secondary=False, serialized=True), "last_place": profile.get_user_history(last_place=True, secondary=False, serialized=True) } notifications = profile.recent_notifications() notifications_json = "[" + ",".join([n.to_JSON() for n in notifications]) + "]" interrupting_message_dict = GLOBAL_INTERRUPTING_MESSAGE or { "name": profile.interrupting_message() } interrupting_message = InterruptingMessage(attrs=interrupting_message_dict, request=request) interrupting_message_json = interrupting_message.json() return { "notifications": notifications, "notifications_json": notifications_json, "notifications_html": notifications.to_HTML(), "notifications_count": profile.unread_notification_count(), "saved": profile.get_user_history(saved=True, secondary=False, serialized=True), "last_place": profile.get_user_history(last_place=True, secondary=False, serialized=True), "interrupting_message_json": interrupting_message_json, "partner_group": profile.partner_group, "partner_role": profile.partner_role, "following": json.dumps(profile.followees.uids) }
def user_and_notifications(request): if not request.user.is_authenticated(): import urlparse recent = json.loads( urlparse.unquote(request.COOKIES.get("recentlyViewed", '[]'))) recent = [] if len(recent) and isinstance( recent[0], dict) else recent # ignore old style cookies return {"recentlyViewed": recent} profile = UserProfile(id=request.user.id) notifications = profile.recent_notifications() notifications_json = "[" + ",".join([n.to_JSON() for n in notifications]) + "]" interrupting_message = profile.interrupting_message() if interrupting_message: interrupting_message_json = json.dumps({ "name": interrupting_message, "html": render_to_string("messages/%s.html" % interrupting_message) }) else: interrupting_message_json = "null" mock_recent = [{ "ref": "Orot, Lights from Darkness, Land of Israel 5", "heRef": "אורות, אורות מאופל, ארץ ישראל ה׳", "book": "Orot", "version": None, "versionLanguage": None, "position": 0 }, { "ref": "Genesis 1", "heRef": "בראשית א׳", "book": "Genesis", "version": None, "versionLanguage": None, "position": 0 }, { "ref": "Berakhot 2a", "heRef": "ברכות ב׳ א", "book": "Berakhot", "version": None, "versionLanguage": None, "position": 0 }] return { "notifications": notifications, "notifications_json": notifications_json, "notifications_html": notifications.to_HTML(), "notifications_count": profile.unread_notification_count(), "recentlyViewed": profile.recentlyViewed, "interrupting_message_json": interrupting_message_json, "partner_group": profile.partner_group, "partner_role": profile.partner_role }
def user_profile(request, username, page=1): """ User's profile page. """ try: profile = UserProfile(slug=username) user = get_object_or_404(User, id=profile.id) except: # Couldn't find by slug, try looking up by username (old style urls) # If found, redirect to new URL # If we no longer want to support the old URLs, we can remove this user = get_object_or_404(User, username=username) profile = UserProfile(id=user.id) return redirect("/profile/%s" % profile.slug, permanent=True) following = profile.followed_by(request.user.id) if request.user.is_authenticated() else False page_size = 20 page = int(page) if page else 1 query = {"user": profile.id} filter_type = request.GET["type"] if "type" in request.GET else None activity, apage= get_maximal_collapsed_activity(query=query, page_size=page_size, page=page, filter_type=filter_type) notes, npage = get_maximal_collapsed_activity(query=query, page_size=page_size, page=page, filter_type="add_note") contributed = activity[0]["date"] if activity else None scores = db.leaders_alltime.find_one({"_id": profile.id}) score = int(scores["count"]) if scores else 0 user_texts = scores.get("texts", None) if scores else None sheets = db.sheets.find({"owner": profile.id, "status": {"$in": LISTED_SHEETS }}, {"id": 1, "datePublished": 1}).sort([["datePublished", -1]]) next_page = apage + 1 if apage else None next_page = "/profile/%s/%d" % (username, next_page) if next_page else None return render_to_response("profile.html", { 'profile': profile, 'following': following, 'activity': activity, 'sheets': sheets, 'notes': notes, 'joined': user.date_joined, 'contributed': contributed, 'score': score, 'scores': scores, 'user_texts': user_texts, 'filter_type': filter_type, 'next_page': next_page, "single": False, }, RequestContext(request))
def register(request): if request.user.is_authenticated: return redirect("login") next = request.GET.get('next', '') if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): new_user = form.save() user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password1']) auth_login(request, user) p = UserProfile(id=user.id) p.assign_slug() p.join_invited_groups() p.settings["interface_language"] = request.interfaceLang p.save() if "noredirect" in request.POST: return HttpResponse("ok") elif "new?assignment=" in request.POST.get("next",""): next = request.POST.get("next", "") return HttpResponseRedirect(next) else: next = request.POST.get("next", "/") + "?welcome=to-sefaria" return HttpResponseRedirect(next) else: if request.GET.get('educator', ''): form = NewUserForm(initial={'subscribe_educator': True}) else: form = NewUserForm() return render(request, "registration/register.html", {'form': form, 'next': next})
def user_and_notifications(request): """ Load data that comes from a user profile. Most of this data is currently only needed view /data.js (currently Node does not get access to logged in version of /data.js) """ if not request.user.is_authenticated: return { "interrupting_message_json": InterruptingMessage(attrs=GLOBAL_INTERRUPTING_MESSAGE, request=request).json() } profile = UserProfile(id=request.user.id) if request.path == "/texts": return { "saved": profile.get_user_history(saved=True, secondary=False, serialized=True), "last_place": profile.get_user_history(last_place=True, secondary=False, serialized=True) } notifications = profile.recent_notifications() notifications_json = "[" + ",".join([n.to_JSON() for n in notifications]) + "]" interrupting_message_dict = GLOBAL_INTERRUPTING_MESSAGE or {"name": profile.interrupting_message()} interrupting_message = InterruptingMessage(attrs=interrupting_message_dict, request=request) interrupting_message_json = interrupting_message.json() return { "notifications": notifications, "notifications_json": notifications_json, "notifications_html": notifications.to_HTML(), "notifications_count": profile.unread_notification_count(), "saved": profile.get_user_history(saved=True, secondary=False, serialized=True), "last_place": profile.get_user_history(last_place=True, secondary=False, serialized=True), "interrupting_message_json": interrupting_message_json, "partner_group": profile.partner_group, "partner_role": profile.partner_role, }
def process_request(self, request): lang = current_domain_lang(request) if "set-language-cookie" in request.GET and lang: params = request.GET.copy() params.pop("set-language-cookie") params_string = params.urlencode() params_string = "?" + params_string if params_string else "" domain = [d for d in DOMAIN_LANGUAGES if DOMAIN_LANGUAGES[d] == lang][0] response = redirect(domain + request.path + params_string) response.set_cookie("interfaceLang", lang) if request.user.is_authenticated: p = UserProfile(id=request.user.id) p.settings["interface_language"] = lang p.save() return response
def user_and_notifications(request): """ Load data that comes from a user profile. Most of this data is currently only needed view /data.js /texts requires `recentlyViewed` which is used for server side rendering of recent section (currently Node does not get access to logged in version of /data.js) """ if not request.user.is_authenticated: import urlparse recent = json.loads( urlparse.unquote(request.COOKIES.get("recentlyViewed", '[]'))) recent = [] if len(recent) and isinstance( recent[0], dict) else recent # ignore old style cookies return { "recentlyViewed": recent, "interrupting_message_json": InterruptingMessage(attrs=GLOBAL_INTERRUPTING_MESSAGE, request=request).json() } profile = UserProfile(id=request.user.id) if request.path == "/texts": return { "recentlyViewed": profile.recentlyViewed, } notifications = profile.recent_notifications() notifications_json = "[" + ",".join([n.to_JSON() for n in notifications]) + "]" interrupting_message_dict = GLOBAL_INTERRUPTING_MESSAGE or { "name": profile.interrupting_message() } interrupting_message = InterruptingMessage(attrs=interrupting_message_dict, request=request) interrupting_message_json = interrupting_message.json() return { "notifications": notifications, "notifications_json": notifications_json, "notifications_html": notifications.to_HTML(), "notifications_count": profile.unread_notification_count(), "recentlyViewed": profile.recentlyViewed, "interrupting_message_json": interrupting_message_json, "partner_group": profile.partner_group, "partner_role": profile.partner_role, }
def sheet_to_dict(sheet): """ Returns a JSON serializable dictionary of Mongo document `sheet`. Annotates sheet with user profile info that is useful to client. """ profile = UserProfile(id=sheet["owner"]) sheet_dict = { "id": sheet["id"], "title": sheet["title"] if "title" in sheet else "Untitled Sheet", "author": sheet["owner"], "ownerName": profile.full_name, "ownerImageUrl": profile.gravatar_url_small, "size": len(sheet["sources"]), "views": sheet["views"], "modified": dateutil.parser.parse(sheet["dateModified"]).strftime("%m/%d/%Y"), "tags": sheet["tags"] if "tags" in sheet else [], } return sheet_dict
def language_settings(request): # CONTENT # Pull language setting from cookie or Accept-Lanugage header or default to english content = request.COOKIES.get( 'contentLang') or request.LANGUAGE_CODE or 'english' # URL parameter trumps cookie content = request.GET.get("lang", content) content = "bilingual" if content in ("bi", "he-en", "en-he") else content content = 'hebrew' if content in ('he', 'he-il') else content content = "english" if content in ('en') else content # Don't allow languages other than what we currently handle content = 'english' if content not in ('english', 'hebrew', 'bilingual') else content # INTERFACE interface = None if request.user.is_authenticated(): profile = UserProfile(id=request.user.id) interface = profile.settings[ "interface_language"] if "interface_language" in profile.settings else None if not interface: # Pull language setting from cookie or Accept-Lanugage header or default to english interface = request.COOKIES.get( 'interfaceLang') or request.LANGUAGE_CODE or 'english' interface = 'hebrew' if interface in ('he', 'he-il') else interface # Don't allow languages other than what we currently handle interface = 'english' if interface not in ('english', 'hebrew') else interface return {"contentLang": content, "interfaceLang": interface}
def language_settings(request): # INTERFACE interface = None if request.user.is_authenticated(): profile = UserProfile(id=request.user.id) interface = profile.settings[ "interface_language"] if "interface_language" in profile.settings else None if not interface: # Pull language setting from cookie or Accept-Lanugage header or default to english interface = request.COOKIES.get( 'interfaceLang') or request.LANGUAGE_CODE or 'english' interface = 'hebrew' if interface in ('he', 'he-il') else interface # Don't allow languages other than what we currently handle interface = 'english' if interface not in ('english', 'hebrew') else interface # CONTENT default_content_lang = 'hebrew' if interface == 'hebrew' else 'bilingual' # Pull language setting from cookie or Accept-Lanugage header or default to english content = request.COOKIES.get('contentLang') or default_content_lang content = short_to_long_lang_code(content) # Don't allow languages other than what we currently handle content = default_content_lang if content not in ('english', 'hebrew', 'bilingual') else content # Note: URL parameters may override values set her, handled in reader view. return {"contentLang": content, "interfaceLang": interface}
def process_request(self, request): excluded = ('/linker.js', "/api/", "/interface/", "/apple-app-site-association", STATIC_URL) if any([request.path.startswith(start) for start in excluded]): return # Save looking up a UserProfile, or redirecting when not needed # INTERFACE # Our logic for setting interface lang checks (1) User profile, (2) cookie, (3) geolocation, (4) HTTP language code interface = None if request.user.is_authenticated and not interface: profile = UserProfile(id=request.user.id) interface = profile.settings["interface_language"] if "interface_language" in profile.settings else interface if not interface: # Pull language setting from cookie, location (set by Cloudflare) or Accept-Lanugage header or default to english interface = request.COOKIES.get('interfaceLang') or request.META.get("HTTP_CF_IPCOUNTRY") or request.LANGUAGE_CODE or 'english' interface = 'hebrew' if interface in ('IL', 'he', 'he-il') else interface # Don't allow languages other than what we currently handle interface = 'english' if interface not in ('english', 'hebrew') else interface # Check if the current domain is pinned to particular language in settings domain_lang = current_domain_lang(request) if domain_lang and domain_lang != interface: # For crawlers, don't redirect -- just return the pinned language no_direct = ("Googlebot", "Bingbot", "Slurp", "DuckDuckBot", "Baiduspider", "YandexBot", "Facebot", "facebookexternalhit", "ia_archiver", "Sogou", "python-request", "curl", "Wget", "sefaria-node") if any([bot in request.META.get('HTTP_USER_AGENT', '') for bot in no_direct]): interface = domain_lang else: redirect_domain = None for domain in DOMAIN_LANGUAGES: if DOMAIN_LANGUAGES[domain] == interface: redirect_domain = domain if redirect_domain: # When detected language doesn't match current domain langauge, redirect path = request.get_full_path() path = path + ("&" if "?" in path else "?") + "set-language-cookie" return redirect(redirect_domain + path) # If no pinned domain exists for the language the user wants, # the user will stay on this domain with the detected language # CONTENT default_content_lang = 'hebrew' if interface == 'hebrew' else 'bilingual' # Pull language setting from cookie or Accept-Lanugage header or default to english content = request.GET.get('lang') or request.COOKIES.get('contentLang') or default_content_lang content = short_to_long_lang_code(content) # Don't allow languages other than what we currently handle content = default_content_lang if content not in ('english', 'hebrew', 'bilingual') else content # Note: URL parameters may override values set here, handled in reader view. if not SITE_SETTINGS["TORAH_SPECIFIC"]: content = "english" request.LANGUAGE_CODE = interface[0:2] request.interfaceLang = interface request.contentLang = content translation.activate(request.LANGUAGE_CODE)
def profile_api(request): """ API for user profiles. """ if not request.user.is_authenticated(): return jsonResponse({"error": "You must be logged in to update your profile."}) if request.method == "POST": profileJSON = request.POST.get("json") if not profileJSON: return jsonResponse({"error": "No post JSON."}) profileUpdate = json.loads(profileJSON) profile = UserProfile(id=request.user.id) profile.update(profileUpdate) error = profile.errors() #TODO: should validation not need to be called manually? maybe inside the save if error: return jsonResponse({"error": error}) else: profile.save() return jsonResponse(profile.to_DICT()) return jsonResponse({"error": "Unsupported HTTP method."})
def notifications(request): if not request.user.is_authenticated(): return {} profile = UserProfile(id=request.user.id) notifications = profile.recent_notifications() notifications_json = "[" + ",".join([n.to_JSON() for n in notifications]) + "]" interrupting_message = profile.interrupting_message() if interrupting_message: interrupting_message_json = json.dumps({"name": interrupting_message, "html": render_to_string("messages/%s.html" % interrupting_message)}) else: interrupting_message_json = "null" return { "notifications": notifications, "notifications_json": notifications_json, "notifications_html": notifications.to_HTML(), "notifications_count": profile.unread_notification_count(), "interrupting_message_json": interrupting_message_json, }
def calendar_links(request): if request.user.is_authenticated: profile = UserProfile(id=request.user.id) custom = profile.settings.get("textual_custom", "ashkenazi") else: custom = "ashkenazi" # this is default because this is the most complete data set return { "calendars": json.dumps( calendars.get_todays_calendar_items(diaspora=request.diaspora, custom=custom)) }
def user_and_notifications(request): """ Load data that comes from a user profile. Most of this data is currently only needed view /data.js /texts requires `recentlyViewed` which is used for server side rendering of recent section (currently Node does not get access to logged in version of /data.js) """ if not request.user.is_authenticated: import urlparse recent = json.loads(urlparse.unquote(request.COOKIES.get("recentlyViewed", '[]'))) recent = [] if len(recent) and isinstance(recent[0], dict) else recent # ignore old style cookies return { "recentlyViewed": recent, "interrupting_message_json": InterruptingMessage(attrs=GLOBAL_INTERRUPTING_MESSAGE, request=request).json() } profile = UserProfile(id=request.user.id) if request.path == "/texts": return { "recentlyViewed": profile.recentlyViewed, } notifications = profile.recent_notifications() notifications_json = "[" + ",".join([n.to_JSON() for n in notifications]) + "]" interrupting_message_dict = GLOBAL_INTERRUPTING_MESSAGE or {"name": profile.interrupting_message()} interrupting_message = InterruptingMessage(attrs=interrupting_message_dict, request=request) interrupting_message_json = interrupting_message.json() return { "notifications": notifications, "notifications_json": notifications_json, "notifications_html": notifications.to_HTML(), "notifications_count": profile.unread_notification_count(), "recentlyViewed": profile.recentlyViewed, "interrupting_message_json": interrupting_message_json, "partner_group": profile.partner_group, "partner_role": profile.partner_role, }
def sync_sustainers_to_mongo(): sustainers = { profile["id"]: profile for profile in db.profiles.find({"is_sustainer": True}) } added_count = 0 removed_count = 0 no_profile_count = 0 already_synced_count = 0 for nationbuilder_sustainer in nationbuilder_get_all( get_by_tag, ['sustainer_current_engineering']): nationbuilder_sustainer_profile = UserProfile( email=nationbuilder_sustainer['email']) if (nationbuilder_sustainer_profile.id != None): # has user profile existing_sustainer = sustainers.get( nationbuilder_sustainer_profile.id) is not None if existing_sustainer: # remove sustainer from dictionary; already synced del sustainers[nationbuilder_sustainer_profile.id] already_synced_count += 1 else: # add new sustainer to db update_user_flags(nationbuilder_sustainer_profile, "is_sustainer", True) added_count += 1 else: no_profile_count += 1 for sustainer_to_remove in sustainers: profile = UserProfile(sustainer_to_remove) update_user_flags(profile, "is_sustainer", False) removed_count += 1 print("added: {}".format(added_count)) print("removed: {}".format(removed_count)) print("no_profile: {}".format(no_profile_count)) print("already synced: {}".format(already_synced_count))
def auth_return(request): """ Step 2 of Google OAuth 2.0 flow. """ state = request.GET.get('state', None) if not state: return redirect('gauth_index') flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( settings.GOOGLE_OAUTH2_CLIENT_SECRET_FILEPATH, scopes=request.session.get('gauth_scope', ''), state=state) redirect_url = request.build_absolute_uri( reverse('gauth_callback')).replace("http:", "https:") flow.redirect_uri = redirect_url # flow.redirect_uri = request.session.get('next_view', '/') authorization_response = request.build_absolute_uri().replace( "http:", "https:") flow.fetch_token(authorization_response=authorization_response) credentials = flow.credentials credentials_dict = { 'token': credentials.token, 'refresh_token': credentials.refresh_token, 'id_token': credentials.id_token, 'token_uri': credentials.token_uri, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'scopes': credentials.scopes, 'expiry': datetime.datetime.strftime(credentials.expiry, '%Y-%m-%d %H:%M:%S') } profile = UserProfile(user_obj=request.user) if profile.gauth_token and profile.gauth_token[ "refresh_token"] and credentials_dict["refresh_token"] is None: credentials_dict["refresh_token"] = profile.gauth_token[ "refresh_token"] profile.update({"gauth_token": credentials_dict}) profile.save() # return credentials return redirect(request.session.get('next_view', '/'))
def notifications(request): if not request.user.is_authenticated(): if request.COOKIES.get("_ga", None) and not request.COOKIES.get( "welcomeToS2LoggedOut", None): # Welcome returning visitors only to the new Sefaria. TODO this should be removed after some time. interrupting_message_json = json.dumps({ "name": "welcomeToS2LoggedOut", "html": render_to_string("messages/welcomeToS2LoggedOut.html") }) else: interrupting_message_json = "null" return {"interrupting_message_json": interrupting_message_json} profile = UserProfile(id=request.user.id) notifications = profile.recent_notifications() notifications_json = "[" + ",".join([n.to_JSON() for n in notifications]) + "]" interrupting_message = profile.interrupting_message() if interrupting_message: interrupting_message_json = json.dumps({ "name": interrupting_message, "html": render_to_string("messages/%s.html" % interrupting_message) }) else: interrupting_message_json = "null" return { "notifications": notifications, "notifications_json": notifications_json, "notifications_html": notifications.to_HTML(), "notifications_count": profile.unread_notification_count(), "interrupting_message_json": interrupting_message_json, }
def dafroulette_js(request): """ Javascript for dafroulette [required to pass server attribute]. """ client_user = UserProfile(id=request.user.id) attrs = { "rtc_server": RTC_SERVER, "client_name": client_user.first_name + " " + client_user.last_name, "client_uid": client_user.id } return render(request, "js/dafroulette.js", attrs, content_type="text/javascript")
def register(request): if request.user.is_authenticated: return redirect("login") next = request.GET.get('next', '') if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): new_user = form.save() user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password1']) auth_login(request, user) p = UserProfile(id=user.id) p.assign_slug() p.join_invited_groups() p.settings["interface_language"] = request.interfaceLang p.save() if "noredirect" in request.POST: return HttpResponse("ok") elif "new?assignment=" in request.POST.get("next", ""): next = request.POST.get("next", "") return HttpResponseRedirect(next) else: next = request.POST.get("next", "/") if "?" in next: next += "&welcome=to-sefaria" else: next += "?welcome=to-sefaria" return HttpResponseRedirect(next) else: if request.GET.get('educator', ''): form = NewUserForm(initial={'subscribe_educator': True}) else: form = NewUserForm() return render(request, "registration/register.html", { 'form': form, 'next': next })
def chavruta_js(request): """ Javascript for chavruta [required to pass server attribute]. """ client_user = UserProfile(id=request.user.id) roulette = request.GET.get("roulette", "0") attrs = { "rtc_server": RTC_SERVER, "client_name": client_user.first_name + " " + client_user.last_name, "client_uid": client_user.id, "roulette": roulette } return render(request, "js/chavruta.js", attrs, content_type="text/javascript; charset=utf-8")
def check_condition(self): """Returns true if this interrupting message should be shown given its conditions""" # Always show to debug if self.condition.get("debug", False): return True # Nameless is useless if not self.name: return False # Don't show this name/repetiion pair more than once if self.request.COOKIES.get(self.cookie_name, False): return False # Limit to returning visitors only if self.condition.get("returning_only", False): if not self.request.COOKIES.get("_ga", False): return False # Filter mobile traffic if self.condition.get("desktop_only", True): if self.request.user_agent.is_mobile: return False # Filter non English interface traffic if self.condition.get("english_only", True): if self.request.LANGUAGE_CODE != "en": return False # Filter non Hebrew interface traffic if self.condition.get("hebrew_only", False): if self.request.LANGUAGE_CODE != 'he': return False # Filter logged out users if self.condition.get("logged_in_only", False): if not self.request.user.is_authenticated: return False if self.is_fundraising: if self.request.user.is_authenticated: profile = UserProfile(id=self.request.user.id) if (profile.is_sustainer): return False return True
def order_tags_for_user(tag_counts, uid): """ Returns of list of tag/count dicts order according to user's preference, Adds empty tags if any appear in user's sort list but not in tags passed in """ profile = UserProfile(id=uid) tag_order = getattr(profile, "tag_order", None) if tag_order: empty_tags = tag_order[:] tags = [tag_count["slug"] for tag_count in tag_counts] empty_tags = [tag for tag in tag_order if tag not in tags] for tag in empty_tags: tag_counts.append({"tag": tag, "count": 0}) try: tag_counts = sorted(tag_counts, key=lambda x: tag_order.index(x["tag"])) except: pass return tag_counts
def process_request(self, request): excluded = ('/linker.js',) if request.path.startswith("/api/") or request.path in excluded: return # Save potentially looking up a UserProfile when not needed # INTERFACE interface = None domain = request.get_host() try: if "https://" + domain in DOMAIN_LANGUAGES: interface = DOMAIN_LANGUAGES["https://" + domain] elif "http://" + domain in DOMAIN_LANGUAGES: interface = DOMAIN_LANGUAGES["http://" + domain] except: pass if request.user.is_authenticated() and not interface: profile = UserProfile(id=request.user.id) interface = profile.settings["interface_language"] if "interface_language" in profile.settings else interface if not interface: # Pull language setting from cookie, location (set by Cloudflare) or Accept-Lanugage header or default to english interface = request.COOKIES.get('interfaceLang') or request.META.get("HTTP_CF_IPCOUNTRY") or request.LANGUAGE_CODE or 'english' interface = 'hebrew' if interface in ('IL', 'he', 'he-il') else interface # Don't allow languages other than what we currently handle interface = 'english' if interface not in ('english', 'hebrew') else interface # CONTENT default_content_lang = 'hebrew' if interface == 'hebrew' else 'bilingual' # Pull language setting from cookie or Accept-Lanugage header or default to english content = request.COOKIES.get('contentLang') or default_content_lang content = short_to_long_lang_code(content) # Don't allow languages other than what we currently handle content = default_content_lang if content not in ('english', 'hebrew', 'bilingual') else content # Note: URL parameters may override values set her, handled in reader view. request.LANGUAGE_CODE = interface[0:2] request.interfaceLang = interface request.contentLang = content translation.activate(request.LANGUAGE_CODE)
def inner(request, *args, **kwargs): # Try grabbing credential from storage profile = UserProfile(user_obj=request.user) credentials_dict = profile.gauth_token if credentials_dict is None: request.session['next_view'] = request.path request.session['gauth_scope'] = scope return (HttpResponse('Unauthorized', status=401) if ajax else redirect('gauth_index')) credentials = google.oauth2.credentials.Credentials( credentials_dict['token'], refresh_token=credentials_dict['refresh_token'], id_token=credentials_dict['id_token'], token_uri=credentials_dict['token_uri'], client_id=credentials_dict['client_id'], client_secret=credentials_dict['client_secret'], scopes=[credentials_dict['scopes']], ) expiry = datetime.datetime.strptime(credentials_dict['expiry'], '%Y-%m-%d %H:%M:%S') credentials.expiry = expiry auth_request = google.auth.transport.requests.Request() if credentials.expired: try: credentials.refresh(auth_request) except: request.session['next_view'] = request.path request.session['gauth_scope'] = scope return (HttpResponse('Unauthorized', status=401) if ajax else redirect('gauth_index')) # Everything went well, call wrapped view and give credential to it kwargs['credential'] = credentials return func(request, *args, **kwargs)
def process_register_form(request, auth_method='session'): form = NewUserForm( request.POST) if auth_method == 'session' else NewUserFormAPI( request.POST) token_dict = None if form.is_valid(): try: with transaction.atomic(): new_user = form.save() user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password1']) p = UserProfile(id=user.id) p.assign_slug() p.join_invited_groups() if PARTNER_GROUP_EMAIL_PATTERN_LOOKUP_FILE: p.add_partner_group_by_email() if hasattr(request, "interfaceLang"): p.settings["interface_language"] = request.interfaceLang p.save() except Exception: return {"error": "something went wrong"} if auth_method == 'session': auth_login(request, user) elif auth_method == 'jwt': token_dict = TokenObtainPairSerializer().validate({ "username": form.cleaned_data['email'], "password": form.cleaned_data['password1'] }) return { k: v[0] if len(v) > 0 else unicode(v) for k, v in form.errors.items() }, token_dict, form
# Get list of sustainers sustainers = { profile["id"]: profile for profile in db.profiles.find({"is_sustainer": True}) } added_count = 0 removed_count = 0 no_profile_count = 0 already_synced_count = 0 for nationbuilder_sustainer in nationbuilder_get_all( get_by_tag, ['sustainer_current_engineering']): nationbuilder_sustainer_profile = UserProfile( email=nationbuilder_sustainer['email']) if (nationbuilder_sustainer_profile.id != None): # has user profile existing_sustainer = sustainers.get( nationbuilder_sustainer_profile.id) is not None if existing_sustainer: # remove sustainer from dictionary; already synced del sustainers[nationbuilder_sustainer_profile.id] already_synced_count += 1 else: # add new sustainer to db update_user_flags(nationbuilder_sustainer_profile, True) added_count += 1 else: no_profile_count += 1 for sustainer_to_remove in sustainers:
# -*- coding: utf-8 -*- """ Give every user a profile URL based on their name """ import sys import os import re p = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, p) sys.path.insert(0, p + "/sefaria") os.environ['DJANGO_SETTINGS_MODULE'] = "settings" from django.contrib.auth.models import User from sefaria.model.user_profile import UserProfile from sefaria.system.database import db db.profiles.ensure_index("slug") users = User.objects.all() for user in users: profile = UserProfile(id=user.id) profile.assign_slug().save()
def process_register_form(request, auth_method='session'): from sefaria.utils.util import epoch_time from sefaria.helper.file import get_resized_file import hashlib import urllib.parse, urllib.request from google.cloud.exceptions import GoogleCloudError from PIL import Image form = SefariaNewUserForm(request.POST) if auth_method == 'session' else SefariaNewUserFormAPI(request.POST) token_dict = None if form.is_valid(): with transaction.atomic(): new_user = form.save() user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password1']) p = UserProfile(id=user.id) p.assign_slug() p.join_invited_collections() if hasattr(request, "interfaceLang"): p.settings["interface_language"] = request.interfaceLang # auto-add profile pic from gravatar if exists email_hash = hashlib.md5(p.email.lower().encode('utf-8')).hexdigest() gravatar_url = "https://www.gravatar.com/avatar/" + email_hash + "?d=404&s=250" try: with urllib.request.urlopen(gravatar_url) as r: bucket_name = GoogleStorageManager.PROFILES_BUCKET with Image.open(r) as image: now = epoch_time() big_pic_url = GoogleStorageManager.upload_file(get_resized_file(image, (250, 250)), "{}-{}.png".format(p.slug, now), bucket_name, None) small_pic_url = GoogleStorageManager.upload_file(get_resized_file(image, (80, 80)), "{}-{}-small.png".format(p.slug, now), bucket_name, None) p.profile_pic_url = big_pic_url p.profile_pic_url_small = small_pic_url except urllib.error.HTTPError as e: logger.info("The Gravatar server couldn't fulfill the request. Error Code {}".format(e.code)) except urllib.error.URLError as e: logger.info("HTTP Error from Gravatar Server. Reason: {}".format(e.reason)) except GoogleCloudError as e: logger.warning("Error communicating with Google Storage Manager. {}".format(e)) p.save() if auth_method == 'session': auth_login(request, user) elif auth_method == 'jwt': token_dict = TokenObtainPairSerializer().validate({"username": form.cleaned_data['email'], "password": form.cleaned_data['password1']}) return { k: v[0] if len(v) > 0 else str(v) for k, v in list(form.errors.items()) }, token_dict, form
import sys import os import pymongo from sefaria.settings import * from sefaria.system.database import db from sefaria.model.user_profile import UserProfile from django.contrib.auth.models import User out = "" users = User.objects.all() for user in users: profile = UserProfile(id=user.id) if profile.organization != "" or profile.position != "": out += "%s\t%s\t%s\t%s\t%s\n" % (user.email, user.first_name, user.last_name, profile.organization, profile.position) print out f = open('contacts.csv', 'w') f.write(out.encode('utf-8')) f.close()
def unlink_gauth(request): profile = UserProfile(id=request.user.id) profile.update({"gauth_token": None}) profile.save() return redirect(f"/profile/{profile.slug}")
# -*- coding: utf-8 -*- """ Give every user a profile URL based on their name """ import sys import os import re p = os.path.dirname(os.path.dirname(os.path.dirname( os.path.abspath(__file__)))) sys.path.insert(0, p) sys.path.insert(0, p + "/sefaria") os.environ['DJANGO_SETTINGS_MODULE'] = "settings" from django.contrib.auth.models import User from sefaria.model.user_profile import UserProfile from sefaria.system.database import db db.profiles.ensure_index("slug") users = User.objects.all() for user in users: profile = UserProfile(id=user.id) profile.assign_slug().save()
from sefaria.system.database import db from sefaria.sheets import LISTED_SHEETS from sefaria.model.user_profile import UserProfile contenders = db.profiles.find({ "bio": { "$ne": "" }, "jewish_education": { "$ne": [] } }) points = {} users = {} for contender in contenders: user = UserProfile(id=contender["id"]) users[user.id] = user gravatar = "http://www.gravatar.com/avatar/" + hashlib.md5( user.email.lower()).hexdigest() + "?d=404" r = urllib.urlopen(gravatar) if r.getcode() == 404: points[user.id] = 0 else: sheets = db.sheets.find({ "owner": user.id, "status": { "$in": LISTED_SHEETS } }).count() points[user.id] = 1 + sheets