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})
Beispiel #2
0
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
Beispiel #3
0
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."})
Beispiel #4
0
def register(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)
            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.REQUEST.get('educator', ''):
            form = NewUserForm(initial={'subscribe_educator': True})
        else:
            form = NewUserForm()

    return render_to_response("registration/register.html",
                                {'form' : form, 'next': next},
                                RequestContext(request))
Beispiel #5
0
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 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))
Beispiel #7
0
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
Beispiel #8
0
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', '/'))
Beispiel #9
0
 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
Beispiel #10
0
 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
Beispiel #11
0
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
Beispiel #12
0
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()
            if PARTNER_GROUP_EMAIL_PATTERN_LOOKUP_FILE:
                p.add_partner_group_by_email()
            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
    })
Beispiel #13
0
def unlink_gauth(request):
    profile = UserProfile(id=request.user.id)
    profile.update({"gauth_token": None})
    profile.save()
    return redirect(f"/profile/{profile.slug}")