Django Allauth Prevent Email Verification & Password Reset Email Abuse/Spam - django

I need to stop users from abusing allauth's ability to send users verification & password reset emails so that my email provider does not temporarily suspend my email address for sending too many emails.
On the /accounts/email/ page, a user could click the re-send verification all they want and an email gets sent every click.
I noticed an ACCOUNT_EMAIL_CONFIRMATION_COOLDOWN setting but am not entirely sure how it works. I tried testing it and am still able to spam click and have the emails get sent every click.
On the /accounts/password/reset/ page, this issue occurs:
https://github.com/pennersr/django-allauth/issues/2167
The creator mentions doing something like this to alleviate it:
https://github.com/pennersr/django-allauth/issues/1008
Maybe this can be used to solve both problems? How would you implement it with the allauth code?
https://stackoverflow.com/a/2157688/13955916
Would rate limiting or throttling solve this? If so, what would a code example be for this?
I have recaptcha v3 on both pages. But that doesn't stop human spam farms.
I came up with a client side javascript cookie solution but am afraid it will not be effective to stop these problems since it is not a server side solution:
button.disabled,
button[disabled] {
box-shadow: none;
cursor: not-allowed;
opacity: 0.5;
pointer-events: none;
}
​
<button id="re-send" class="secondaryAction" type="submit" name="action_send" >{% trans 'Re-send Verification' %}</button>
​
​
<script>
const resendBtn = document.getElementById("re-send");
resendBtn.addEventListener("click", disable);
​
var cookieString = getCookie("cookieName");
if(cookieString == "mysite"){
var btn = document.querySelector('#re-send');
btn.classList.add('disabled');
}
​
function setCookie(){
days=1;
myDate = new Date();
myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
document.cookie = 'cookieName=mysite; expires=' + myDate.toGMTString();
}
​
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
​
function disable() {
var btn = document.querySelector('#re-send');
btn.classList.add('disabled');
setCookie();
};
​
​
function runFunction(){
var testElement = document.getElementById('re-send');
if (!testElement.classList.contains('disabled') && (getCookie("cookieName") == "mysite")) {
var btn = document.querySelector('#re-send');
btn.classList.add('disabled');
}
};
​
setInterval(runFunction,1000);
​
</script>

Related

StateHasChanged() does not reload page

Issue:
As mentioned in Title, StateHasChanged does not re-render the page
Objective:
I want to Refresh the page when a button is clicked
Current Code
<button #onclick="CreatePlayer">Create User</button>
#functions {
string username;
[CascadingParameter]
Task<AuthenticationState> authenticationStateTask { get; set; }
async Task CreatePlayer()
{
var authState = await authenticationStateTask;
var user = authState.User;
var player = await PlayerData.GetByEmail(user.Identity.Name);
if (player == null)
{
player = new Player()
{
Email = user.Identity.Name,
UserName = username
};
await PlayerData.Create(player);
}
await Task.Delay(50);
StateHasChanged();
}
}
Just for the record, I add my comment in an answer :
StateHasChanged just inform the component that something changes in is state, that doesn't rerender it. The component choose by itself if it has to rerender or not. You can override ShouldRender to force the component to rerender on state changed.
#code {
bool _forceRerender;
async Task CreatePlayer()
{
var authState = await authenticationStateTask;
var user = authState.User;
var player = await PlayerData.GetByEmail(user.Identity.Name);
if (player == null)
{
player = new Player()
{
Email = user.Identity.Name,
UserName = username
};
await PlayerData.Create(player);
}
_forceRerender = true;
StateHasChanged();
}
protected override bool ShouldRender()
{
if (_forceRerender)
{
_forceRerender = false;
return true;
}
return base.ShouldRender();
}
}
On the one hand, you tell the compiler that she should create an event handler for the click event, named CreatePlayer: #onclick="CreatePlayer . This attribute compiler directive, behind the scenes, creates an EventCallback<Task> handler for you, the implication of which is that you do not need to use StateHasChanged in your code at all, as this method ( StateHasChanged ) is automatically called after UI events take place.
On the other hand, you tell the compiler that the type of the button should be set to "submit". This is wrong of course... You can't have it both. Setting the type attribute to "submit", normally submit form data to the server, but In Blazor it is prevented to work that way by code in the JavaScript portion of Blazor. Do you want to submit a form data to the server ? Always recall Blazor is an SPA Application. No submit ?
Your code should be:
<button #onclick="CreatePlayer" >Create User</button>
Just for the records, ordinarily you should inject the AuthenticationStateProvider object into your components, like this:
#inject AuthenticationStateProvider AuthenticationStateProvider
and then retrieve the AuthenticationState object. This is how your code may be rewritten:
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;

Django has no response to anchor tag

test
...
<div class="tab-pane " id="test">
<table>
...
</table>
</div>
When #test anchor is clicked, the behavior should be logged in the server. So in urls.py, I defined something like this
url(r'#test$', views.log())
or
url(r'.*#test$', views.log())
But it seems it doesn't work.
I have to use anchor here, because I don't want to refresh the page.
Any ideas?
Here is some JavaScript that takes links with a href attribute starting with # and makes a request to https://localhost:8000/<whatever was after the hash sign> whenever the links are clicked. It's not robust and it needs to be modified for your circumstances, but maybe it works as a starting point.
var hashLinks = document.querySelectorAll('a[href^="#"]');
var i;
function hashLinkClicked(event) {
var hash, url, request;
// You probably want to allow default link behaviour here
event.preventDefault();
hash = this.hash;
// Cut hash character out of URL
url = 'http:/localhost:8000/' + hash.slice(1);
request = new XMLHttpRequest();
request.onreadystatechange = function () { /* Handle response here */ };
request.open('GET', url);
request.send();
}
for (i = 0; i < hashLinks.length; i++) {
hashLinks[i].addEventListener('click', hashLinkClicked);
}

Sitecore 8 EXM add a contact to list from listmanager

I'm using Sitecore 8 and the new Email Experience Manager module.
I have configured a newsletter email message with an empty list from the listmanager as recipients.
When subscribing for the newsletter via a selfmade form, I receive an email address and a name.
Now I want to make a new contact with this mail and name and add it to the list in my listmanager via code.
Is there any way to call this list via the api and add a contact to it?
To create a contact, you can use the sample code below, the contact name is usually the domain name plus the username, e.g. domain\username.
public static Contact CreateContact([NotNull] string contactName, [NotNull] string contactEmail, [NotNull] string contactLanguage)
{
Assert.ArgumentNotNullOrEmpty(contactName, "contactName");
Assert.ArgumentNotNullOrEmpty(contactEmail, "contactEmail");
Assert.ArgumentNotNullOrEmpty(contactLanguage, "contactLanguage");
var contactRepository = new ContactRepository();
var contact = contactRepository.LoadContactReadOnly(contactName);
if (contact != null)
{
return contact;
}
contact = contactRepository.CreateContact(ID.NewID);
contact.Identifiers.AuthenticationLevel = AuthenticationLevel.None;
contact.System.Classification = 0;
contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
contact.Identifiers.Identifier = contactName;
contact.System.OverrideClassification = 0;
contact.System.Value = 0;
contact.System.VisitCount = 0;
var contactPreferences = contact.GetFacet<IContactPreferences>("Preferences");
contactPreferences.Language = contactLanguage;
var contactEmailAddresses = contact.GetFacet<IContactEmailAddresses>("Emails");
contactEmailAddresses.Entries.Create("test").SmtpAddress = contactEmail;
contactEmailAddresses.Preferred = "test";
var contactPersonalInfo = contact.GetFacet<IContactPersonalInfo>("Personal");
contactPersonalInfo.FirstName = contactName;
contactPersonalInfo.Surname = "recipient";
contactRepository.SaveContact(contact, new ContactSaveOptions(true, null));
return contact;
}
After creating the contact, use the following sample code to add the contact to a recipient list.
var repository = new ListManagerCollectionRepository();
var recipientList = repository.GetEditableRecipientCollection(recipientListId);
if (recipientList != null)
{
var xdbContact = new XdbContactId(contactId);
if (!recipientList.Contains(xdbContact, true).Value)
{
recipientList.AddRecipient(xdbContact);
}
}
Essentially you can follow this example
<%# Page Language="c#" %>
<%# Import Namespace="Sitecore.Analytics" %>
<%# Import Namespace="Testing.ContactFacets.Model" %>
<!DOCTYPE html>
<html>
<head>
<title>Add Employee Data</title>
</head>
<body>
<%
var contact = Tracker.Current.Contact;
var data = contact.GetFacet<IEmployeeData>("Employee Data");
data.EmployeeId = "ABC123";
%>
<p>Employee data contact facet updated.</p>
<p>Contact ID: <b><%=contact.ContactId.ToString()%></b></p>
<p>Employee #: <b><%=data.EmployeeId%></b></p>
</body>
</html>
The changes are then written when the session is abandoned, like so
<%# Page language="c#" %>
<script runat="server">
void Page_Load(object sender, System.EventArgs e) {
Session.Abandon();
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>Session Abandon</title>
</head>
<body>
</body>
</html>
Follow this link for the source and more information - http://www.sitecore.net/learn/blogs/technical-blogs/getting-to-know-sitecore/posts/2014/09/introducing-contact-facets
I have had the exact same issue, i.e. the list manager reports 0 contacts after adding the contact to the recipient list.
I have investigated the issue closer and found that adding a contact to a recipient list actually just sets a field on the contact in the "sitecore_analytics_index" index (assuming you use Mongo/XDB as the underlying storage). Specifically, Sitecore should update the "contact.tags" field on the contact document with the value "ContactLists:{recipientListGuid}". I tried opening the index with Luke to verify that this field was indeed not being set in the index. The index is located in C:\inetpub\wwwroot[Sitename]\Data\indexes\sitecore_analytics_index.
This led me to the conclusion, that you have to save the contact after adding him to the recipient list.
Summing up, the following code works for me:
var ecm = EcmFactory.GetDefaultFactory();
XdbContactId contactId = /* some valid contact id */;
LeaseOwner leaseOwner = new LeaseOwner("UpdateContact-" + Guid.NewGuid().ToString(), LeaseOwnerType.OutOfRequestWorker);
Sitecore.Analytics.Tracking.Contact contact;
string webClusterName;
var status = ecm.Gateways.AnalyticsGateway.TryGetContactForUpdate(contactId.Value,
leaseOwner,
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(5),
out contact, out webClusterName);
var recipientList = ecm.Bl.RecipientCollectionRepository.GetEditableRecipientCollection(recipientListId);
if (recipientList != null)
{
if (!recipientList.Contains(contactId, true).Value)
{
recipientList.AddRecipient(contactId);
}
}
contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
var contactRepository = new ContactRepository();
var success = contactRepository.SaveContact(contact, new ContactSaveOptions(true, leaseOwner));
Note, the above code is used in an update-scenario. In your case, I guess you just have to move this code:
contactRepository.SaveContact(contact, new ContactSaveOptions(true, null));
After this:
var recipientList = EcmFactory.GetDefaultFactory().Bl.RecipientCollectionRepository.GetEditableRecipientCollection(recipientListId);
if (recipientList != null)
{
var xdbContact = new XdbContactId(contactId);
if (!recipientList.Contains(xdbContact, true).Value)
{
recipientList.AddRecipient(xdbContact);
}
}
UPDATE: Actually the above only works if the contact saved is the contact currently tracked by Sitecore Analytics.
in case you have a tracker available and you dont need the update immediately, the following should work (note that the contact is added to the list upon session expiration):
//private const string ContactListTagName = "ContactLists";
var contact = Tracker.Current.Contact;
// Identify
if (contact.Identifiers.IdentificationLevel < ContactIdentificationLevel.Known)
{
Tracker.Current.Session.Identify(email);
}
// Set Email
var contactEmail = contact.GetFacet<IContactEmailAddresses>("Emails");
// Create an email address if not already present
// This can be named anything, but must be the same as "Preferred" if you want
// this email to show in the Experience Profiles backend.
if (!contactEmail.Entries.Contains("Preferred"))
contactEmail.Entries.Create("Preferred");
// set the email
var emailEntry = contactEmail.Entries["Preferred"];
emailEntry.SmtpAddress = email;
contactEmail.Preferred = "Preferred";
// set FirstName and Surname (required for List Manager, "N/A" might not be ideal but I don't know how Sitecore behaves with empty strings)
var personal = contact.GetFacet<IContactPersonalInfo>("Personal");
personal.FirstName = personal.FirstName ?? "N/A";
personal.Surname = personal.Surname ?? "N/A";
// Add preferred language
var preferences = contact.GetFacet<IContactPreferences>("Preferences");
preferences.Language = Context.Language.Name;
// Here is the actual adding to the list by adding tags
using (new SecurityDisabler())
{
var id = ID.Parse("CONTACTLISTID");
contact.Tags.Set(ContactListTagName, id.ToString().ToUpperInvariant());
}
Greetz,
Markus

angularjs not responding the GET method

i am relatively new in django and angualarJs.The problem is that angularJs is not responding the get method properly.I have a webpage developed by django where i have a search field.For the execution of search i use a angularJs functionality that is ng-submit and write angularJs code to return value using get method.May be i made a mistake here.you can see my code... here is my template which containing the angularJs also...
<div class="navbar navbar-default " ng-controller="NavCtrl">
<form action="" class="navbar-form navbar-right" ng-submit="search()">
<input class="form-control col-lg-8" type="text" placeholder="Search" ng-model="term"></input>
</form>
</div>
<script>
app.controller("NavCtrl", ['$scope', '$http', '$location', '$q', '$timeout',
function NavCtrl($scope, $http, $location, $q, $timeout) {
$scope.results = ["Test"];
$scope.term = "";
$scope.reqs = "5";
$scope.pics = "45";
$scope.ddata = "asdasd";
$scope.ddata = $http.post("{% url 'get-nav-info' %}").success(
function (result) {
//$scope.reqs = result.data.data.num_request;
//$scope.pics = result.data.data.num_photo;
return result.data;
}
);
//$scope.reqs = $scope.ddata.num_request;
//$scope.pics = $scope.ddata.num_photo;
$scope.search = function () {
//alert("test");
//$location.absUrl("{% url 'search-term-show' %}").search({'term':$scope.term}).apply();
//$location.path("{% url 'search-term-show' %}").search({'term':$scope.term}).apply();
$http.get("{% url 'search-term-show' %}?term=" + $scope.term).success(function (result) {
return result.data;
});
//$scope.$apply();
}
}
]);
</script>
now the problem is that while i press enter ,there is no result,but if i manually write this URL which is http://www.kothay.com/searchphoto/?term=a in the address bar then the result is showing .In mention,this url is the that url which should be appear in the address bar when i press the enter to search my photos.But with the enter press its not appearing in the address bar and that's why the results are not showing.I hope you can understand what i am trying to say.May be there is a mistake in my code.Please help me to fix this problem.
You are doing thing wrong.
1st, the success is a defer of get, so return result.data and returns it to the get deferred and there it goes to the heaven. So if you would like to keep the current architecture it should look more like this
$scope.search = [];
getsearch = function () {
$http.get("{% url 'search-term-show' %}?term=" + $scope.term).success(function (result) {
$scope.search = result.data;
});
};
getsearch();
2nd that can still not update your UI cuz if the ctrl function is over and the digest is over before your response it wont update your UI cuz its in another scope (not $scope, but the programmatically term scope). The solution to this is to put your data in a service and in your ctr just do.
function ctrl($scope, myservice){
$scope.data = myservice;
}
ng-repeat="x in data.results"
Here is a full tutorial http://bresleveloper.blogspot.co.il/2013/08/breslevelopers-angularjs-tutorial.html
And last thing its just a good practice to always have .error(...)

Facebook Login Button: Workaround for bug of Chrome on iOS

Currently, I am trying to solve a bug logged in Facebook Developer:
https://developers.facebook.com/bugs/325086340912814/
I am using ASP.NET MVC 3 with Facebook C# SDK and Facebook Javascript SDK.
Here is javascript code:
window.fbAsyncInit = function () {
// init the FB JS SDK
FB.init({
appId: '298365513556623', // App ID from the App Dashboard
channelUrl: 'http://www.christianinfoportal.com/channel.html', // Channel File for x-domain communication
status: true, // check the login status upon init?
cookie: true, // set sessions cookies to allow your server to access the session?
xfbml: true // parse XFBML tags on this page?
});
// Additional initialization code such as adding Event Listeners goes here
FB.Event.subscribe('auth.authResponseChange', function (response) {
if ((response.status == 'connected')) {
if (fbIgnoreFirstEventFire)
fbIgnoreFirstEventFire = false;
else {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
// TODO: Handle the access token
// Do a post to the server to finish the logon
// This is a form post since we don't want to use AJAX
var form = document.createElement("form");
form.setAttribute("method", 'post');
form.setAttribute("action", '/FBLogin');
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'accessToken');
field.setAttribute("value", accessToken);
form.appendChild(field);
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'returnUrl');
field.setAttribute("value", window.location.href);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
}
} else if (response.status == 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
};
// Load the SDK's source Asynchronously
(function (d, debug) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);
}(document, /*debug*/ false));
The View code is pretty simple:
<div id="fbLoginButton" class="fb-login-button" data-show-faces="false" data-width="50" data-max-rows="1" data-scope="email"></div>
I basically forward the access token to a server side code page:
public ActionResult FBLogin(String returnUrl)
{
var accessToken = Request["accessToken"];
//FB fires even without the user clicking the Log In button
Session["FBLoginFirstClick"] = true;
//Session["AccessToken"] = accessToken;
//this.lblAccessToken.Text = accessToken;
//Response.Redirect("/MyUrlHere");
var client = new Facebook.FacebookClient(accessToken);
dynamic me = client.Get("me");
String email, fullName;
fullName = me.first_name + " " + me.last_name;
email = me.email;
Models.User.ThirdPartyLogin(email, fullName, Session);
if (!string.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
Solved by using Facebook authentication redirect.
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/