Replace some special characters from username in django - django

how i can set django username as telegram username characters
example
testuser_user
testuser_user_5
jQuery(function($) {
$("#id_username").on("keyup blur", function() {
$(this).val($(this).val().replace(/[^a-z0-9]/ig, ''));
});
});

Related

AWS-Cognito: How to sign in user with email or username

During AWS Cogito User Pool there are two options for how to let users sign in. One of them is
Username - Users can use a username and optionally multiple alternatives to sign up and sign in.
Also allow sign in with verified email address
I have selected the above and while testing it using aws-amplify I always get __type: "NotAuthorizedException"
message: "Incorrect username or password." if I try to sign in with email but it works fine when I try to sign in with the username.
Here is my signin method
Auth.signIn(email, password)
.then(r => {
setLoggedIn(true);
})
.catch(r => {
setLoggedIn(false);
})
};
I know this is an old thread, but I've recently had this problem and had to figure it out. When you have a user in your user pool that does not have the email_verified set to True, the Auth.signIn method will only work with that user's username.
Not only that, but the Auth.forgotPassword method won't send the code to the user's e-mail. There's possibly more interactions like these.
Make sure you confirm your user's email, that's all!
If you are using a backend to create your users, you can simply do this by:
const signUpParams = {
UserPoolId: "YOUR_USER_POOL_ID",
TemporaryPassword: "TEMP_PW",
Username: "username",
UserAttributes: [
{
Name: 'email',
Value: "USER_EMAIL",
},
{
Name: 'email_verified',
Value: 'true',
},
],
};
const { User } = await cognitoService.adminCreateUser(signUpParams).promise();
aws cognito is case sensitive example if you registered your email with Siyavash#email.com then you cannot sign in with siyavash#email.com
My vuex store action for login:
You may need to set the attribute name to username
async login({ commit },{ email, password }) {
const user = await Auth.signIn({ username: email, password });
commit('set', user)
return user;
},

Got CSRF verification failure when while requesting POST through API

I'm writing a site using REST API. I use django with piston at backend (also using corsheaders.middleware.CorsMiddleware with CORS_ORIGIN_ALLOW_ALL = True). And I use backbone.js for frontend. I'm sending POST request from client-side and get error:
CSRF verification failed. Request aborted.
I've googled a lot and all solutions suggested something like "Use the render shortcut which adds RequestContext automatically". But I have no view, forms will be requested from frontend, that shouldn't know about how backend works. Here's code of my scipt
Question = Backbone.Model.extend({
urlRoot: 'http://example.com/api/questions',
defaults: {
id: null,
title: '',
text: ''
},
initialize: function() {
//alert(this.title);
}
});
var question2 = new Question;
var questionDetails = {title: 'test title', text: 'test text'};
question2.save(questionDetails, {
success: function(question) {
alert(question.toJSON());
}
});
The django docs have instructions on how to set up jquery to send the csrf token via ajax.
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
You should make sure that the template tag {% csrf_token %} renders something in your frontend. That way you know that the token is being created and passed to the frontend. If you follow the instructions from the docs above then your csrf token should always be sent with ajax requests. This is what the javascript looks like for one of my sites (assuming you are using jQuery).
// Set up Django CSRF Token Protection
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Also, make sure that 'django.middleware.csrf.CsrfViewMiddleware' is in your MIDDLEWARE_CLASSES settings.
Sounds like you need to pass the CSRF token through with your save request.
One solution would be to pass the CSRF token back to the model requesting it, then override your model's save method ensuring the model passes the CSRF token back with it.
Question = Backbone.Model.extend({
urlRoot: 'http://example.com/api/questions',
defaults: {
csrf: null,
id: null,
title: '',
text: ''
},
initialize: function() {
//alert(this.title);
}
save: function( data, options ){
data = $.extend( true, {
csrf: this.get( 'csrf' )
}, data );
options = _.extend( options, {
error: onError,
success: onSuccess
} );
// Call super method.
Backbone.Model.prototype.save.apply( this, [ data, options ] );
}
});

Node.js and Mongoose regex query on multiple fields

I would like to query multiple fields using the same regular expression for both. In this query, I would like to accept a single text input and check both the firstName and lastName fields for results. I can query a single field just fine using the regex function in the mongoose documentation, but the syntax for an 'or' clause is giving me trouble.
var re = new RegExp(req.params.search, 'i');
app.User.find().or([{ 'firstName': { $regex: re }}, { 'lastName': { $regex: re }}]).sort('title', 1).exec(function(err, users) {
res.json(JSON.stringify(users));
});
(I'm running mongoose 2.7.1 on node.js 0.6.12)
The code above works fine for a query on multiple fields. Turns out I had some bad data.
My solution is to use $function that allows you to concatenate multiple fields and match their combined value against your regular expression.
const { search } = req.params;
var regex = new RegExp(`.*${search}.*`, 'i');
app.User.find({
$expr: {
$function: {
body: `function(firstName, lastName) { return (firstName+' '+lastName).match(${regex}) }`,
args: ['$firstName', '$lastName'],
lang: "js"
}
}
})
.exec((err, users) => {
res.json(JSON.stringify(users));
});

Testing MongooseJs Validations

Does anyone know how to test Mongoose Validations?
Example, I have the following Schema (as an example):
var UserAccount = new Schema({
user_name : { type: String, required: true, lowercase: true, trim: true, index: { unique: true }, validate: [ validateEmail, "Email is not a valid email."] },
password : { type: String, required: true },
date_created : { type: Date, required: true, default: Date.now }
});
The validateEmail method is defined as such:
// Email Validator
function validateEmail (val) {
return /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(val);
}
I want to test the validations. The end result is that I want to be able to test the validations and depending on those things happening I can then write other tests which test the interactions between those pieces of code. Example: User attempts to sign up with the same username as one that is taken (email already in use). I need a test that I can actually intercept or see that the validation is working WITHOUT hitting the DB. I do NOT want to hit Mongo during these tests. These should be UNIT tests NOT integration tests. :)
Thanks!
I had the same problem recently.
First off I would recommend testing the validators on their own. Just move them to a separate file and export the validation functions that you have.
This easily allows your models to be split into separate files because you can share these validators across different models.
Here is an example of testing the validators on their own:
// validators.js
exports.validatePresenceOf = function(value){ ... }
exports.validateEmail = function(value){ ... }
Here is a sample test for this (using mocha+should):
// validators.tests.js
var validator = require('./validators')
// Example test
describe("validateEmail", function(){
it("should return false when invalid email", function(){
validator.validateEmail("asdsa").should.equal(false)
})
})
Now for the harder part :)
To test your models being valid without accessing the database there is a validate function that can be called directly on your model.
Here is an example of how I currently do it:
describe("validating user", function(){
it("should have errors when email is invalid", function(){
var user = new User();
user.email = "bad email!!"
user.validate(function(err){
err.errors.email.type.should.equal("Email is invalid")
})
})
it("should have no errors when email is valid", function(){
var user = new User();
user.email = "test123#email.com"
user.validate(function(err){
assert.equal(err, null)
})
})
})
The validator callback gets an error object back that looks something like this:
{ message: 'Validation failed',
name: 'ValidationError',
errors:
{ email:
{ message: 'Validator "Email is invalid" failed for path email',
name: 'ValidatorError',
path: 'email',
type: 'Email is invalid'
}
}
}
I'm still new to nodeJS and mongoose but this is how I'm testing my models + validators and it seems to be working out pretty well so far.
You should use validate() method as a promise and test it with a tool that makes asserts for async stuff (ex: Chai as Promised).
First of all, require a promise library and switch out to the promise provider (for example Q):
mongoose.Promise = require('q').Promise;
Afterwards just, use asserts about promises:
it('should show errors on wrong email', function() {
user = new UserModel({
email: 'wrong email adress'
});
return expect(user.validate()).to.be.rejected;
});
it('should not show errors on valid email adress', function() {
user = new UserModel({
email: 'test#test.io'
});
return expect(user.validate()).to.be.fulfilled;
});

Automated facebook post to wall with Javascript

I have a facebook application in which the user is authenticated with PHP and grants permissions to the app, including publish_stream.
During the application, the user is going through several screens.
On the last screen, the is user chooses if they want to share a post on their wall.
If they do, an automated and formatted post should be posted on their wall.
I've tried to do it with Javascript but it didn't work. Can you see what's wrong?
Thanks!
Here's my code:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'MY APP ID',
status : true,
cookie : true,
xfbml : true
});
};
(function() {
var e = document.createElement('script');
e.src = 'http://connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<script>
function postToFacebook() {
var body = '';
var params = {};
params['message'] = 'MESSAGE';
params['name'] = 'NAME';
params['description'] = '';
params['link'] = '';
params['picture'] = 'https://www.URL.com/pic.jpg';
params['caption'] = 'CAPTION';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
// alert('Error occured');
} else {
// alert('Post ID: ' + response);
}
});
}
</script>
From reading your question and the various comments it seems to me that the users session information is not persisting into the JavaScript SDK - this assumes that there is a valid user session being maintained serverside.
First of all you should check that you are using the most up to date PHP SDK. To double check download and install the latest version from GitHub.
I think this should solve your problem as the cookies containing the authorised users session data should be passed between the PHP and JavaScript SDKs.
If that doesn't work I have a suspicion that the user is not being authenticated correctly serverside. In which case you could try the following.
Before you postToFacebook() you should check the users the users logged in status and log them in if necessary. For example:
FB.getLoginStatus(function(response) {
if (response.authResponse) {
// logged in and connected user, someone you know
postToFacebook();
} else {
// no user session available, someone you dont know
FB.login(function(response) {
if (response.authResponse) {
// logged in and connected user
postToFacebook();
} else {
// User cancelled login or did not fully authorize
}
}, {scope: 'YOUR,REQUIRED,PERMISSIONS'});
}
});
You are not calling the function postToFacebook()!
window.fbAsyncInit = function() {
FB.init({
appId : 'MY APP ID',
status : true,
cookie : true,
xfbml : true
});
postToFacebook();
};
When you attempt to do this:
FB.api('/me/feed', 'post', params, function(response) { .. });
You need to pass the access token along with the call. I assume you have it on the php/server side, so then:
FB.api('/me/feed/access_token='[INSERT_ACCESS_TOKEN], 'post', params, function(response) { .. });