Hi I want to validate the email address, i find the mailgun flanker email validation python library but it's not working.
>>> from flanker.addresslib import address
>>>
>>> address.validate_address('foo#mailgun.com')
None
Please help me!
Thanks
it's better to use mailgun api validor,for example.
def get_validate():
return requests.get(
"https://api.mailgun.net/v3/address/validate",
auth=("api", "pubkey-5ogiflzbnjrljiky49qxsiozqef5jxp7"),
params={"address": "foo#mailgun.net"}
Example: https://github.com/diegovalle/crimenmexico/blob/master/api/forms.py
view.py:
def get_validate(email):
return requests.get(
"https://api.mailgun.net/v3/address/validate",
auth=("api", "pubkey-f387c7feae844803cdda9c99d4b976cb"),
params={'address': email})
rq = get_validate(email)
if rq is not None:
data_email = rq.json()
if data_email['is_valid'] == False:
if data_email['did_you_mean'] is not None:
print("Error, Wrong Email")
else:
print("Error, Wrong Email")
else:
print("Ok, Email Correct")
Related
I'm trying to add this email verification process in to my flask app.
Within app/models.py I have this:
def get_confirm_account_token(self, expires_in=600):
return jwt.encode(
{'confirm_account': self.id, 'exp': time() + expires_in},
current_app.config['SECRET_KEY'], algorithm='HS256')
#staticmethod
def verify_confirm_account_token(token):
try:
id = jwt.decode(token, current_app.config['SECRET_KEY'],
algorithms=['HS256'])['confirm_account']
except:
return
return User.query.get(id)
In my route.py I call send_account_verify_email(user) after the user registers which in turn generates a token:
token = user.get_confirm_account_token()
In my route.py I then have this:
#bp.route('/confirm/<token>')
#login_required
def confirm_email(token):
if current_user.is_confirmed:
flash('Account already confirmed')
return redirect(url_for('main.index'))
if not user:
return redirect(url_for('main.index'))
user = User.verify_confirm_account_token(token)
# HOW DO I CHECK TOKEN VALIDITY BEFORE SETTING CONFIRMED?
user.is_confirmed = True
user.confirmed_on = datetime.now()
db.session.add(user)
db.session.commit()
flash('You have confirmed your account')
else:
flash('The confirmation link is invalid or has expired')
return redirect(url_for('main.index'))
The part I'm struggling with is how to check if the token the user entered is correct - i.e what is stopping them from entering any old token - before I then mark them as confirmed?
The jwt.decode() method will raise an ExpiredSignatureError if your token is expired.
This article explains it pretty good:
https://auth0.com/blog/how-to-handle-jwt-in-python/
This morning I tried to login in my account from my website(deployed on pythonanywhere
After that, I tried to login from my main device. It worked perfectly. I checked if I entered the same credentials and I did.
The view function:
#application.route('/logmein', methods=['POST'])
def logmein():
password = request.form['password']
email = request.form['email']
user = User.query.filter_by(email=email).first()
spass = check_password_hash(user.password, password)
if not user:
return '<h1>We could not find the account!try again</h1>'
else:
if spass == True:
login_user(user, remember=True)
return redirect('/')
else:
return '<body style="background: yellow"><h1>The password is incorrect! go back</h1></body>'
Thanks for help!!!
You should see whats being sent over when you post by printing the form data.
#application.route('/logmein', methods=['POST'])
def logmein():
print(request.form)
# print each method so you can look around
print(dir(request.form))
return 'test'
AttributeError: 'NoneType' object has no attribute 'password' < Leads me to beleive the issue is that password doesnt exist as you reference it.
guys. I have been searching all over the internet but I could not get what is the problem with my code. I am actually a Frontend developer. However, I am trying to learn Python Flask for backend part of my project.
Here is the code for login endpoint and another one which can be accessed only after we are logged in.
#app.route("/login", methods=['GET', 'POST'])
def login():
if request.method == 'POST':
phone_number = request.form.get("phone_number")
password = request.form.get("password")
user = Auth.query.filter_by(phone_number=phone_number).first()
if user and check_password_hash(user.password, password):
userlogin = UserLogin().create(user)
rm = True if request.form.get('remainme') else False
login_user(user, remember=rm)
access_token = create_access_token(identity=phone_number)
response = jsonify(access_token=access_token, role=user.role)
set_access_cookies(response, access_token)
response.headers.add('Access-Control-Allow-Origin', 'http://localhost:3000')
response.headers['Access-Control-Allow-Credentials'] = 'true'
return response
else:
return jsonify(status=False), 401
return redirect(url_for("all_tours"))
#app.route("/admin/all_tours")
#jwt_required()
def all_tours():
all_tours = Tour.query.filter_by(owner=get_jwt_identity()).all()
response = jsonify(all_tours=[i.serialize for i in all_tours])
response.headers.add('Access-Control-Allow-Origin', 'http://localhost:3000')
return response
When I try to send request to use all_tours endpoint, I get
msg: "Missing cookie \"access_token_cookie\""
Have no idea what is wrong.
I even tried to add these lines into def all_tours():
access_token = request.headers['Authorization'].replace("Bearer ", "")
set_access_cookies(response, access_token)
But still useless. Could you please help me to get an idea how to fix it, please?
I am new to django and python development and am naive in my understanding of how to handle exceptions.
I am registering a user through an api call by calling the method register, and would like to push the success status or the error messages while registration.
def register(self,request, **kwargs):
try:
data = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
email = data['email']
password = data['password']
firstname = data['firstname']
lastname = data['lastname']
newdata = {'email' : email , 'password1': password , 'password2':password, 'firstname':'firstname' , 'lastname':lastname }
registrationform = UserEmailRegistrationForm(newdata)
print registrationform.errors.as_text
print registrationform.cleaned_data
cleaned_data = registrationform.cleaned_data
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
new_user = RegistrationProfile.objects.create_inactive_user(cleaned_data['username'],cleaned_data['email'],cleaned_data['password1'], site)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request,**cleaned_data)
registerUser = collections.OrderedDict()
registerUser['return']='0'
registerUser['code']='0'
registerUser['message']='registered user'
return HttpResponse(registerUser, content_type="application/json")
except Exception, e:
logging.exception(e)
registerUser = collections.OrderedDict()
registerUser['return']='0'
registerUser['code']='0'
registerUser['message']='registered user'
return HttpResponse(registerUser, content_type="application/json")
When I execute this, for example with an already registered email, I get the following in registrationform.errors.as_text
bound method ErrorDict.as_text of {'email': [u'A user with that email already exists.']}>
What would be the right way to code exceptions so that I can pass the success message if the form was validated and user was registered, and the error message if there was a validation error?
Any help is much appreciated!
You might want to have a look in the form's is_valid() method: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.is_valid
For example
if registrationform.is_valid():
//do your stuff
....
register['error'] = False
else:
//return the errors
registerUser['message'] = _('Oops! Please fix the following errors')
register['error'] = True
register['errors'] = registrationform.errors
....
This is my view that I want to be tested.
def logIn(request):
"""
This method will log in user using username or email
"""
if request.method == 'POST':
form = LogInForm(request.POST)
if form.is_valid():
user = authenticate(username=form.cleaned_data['name'],password=form.cleaned_data['password'])
if user:
login(request,user)
return redirect('uindex')
else:
error = "Nie prawidlowy login lub haslo.Upewnij sie ze wpisales prawidlowe dane"
else:
form = LogInForm(auto_id=False)
return render_to_response('login.html',locals(),context_instance=RequestContext(request))
And here's the test
class LoginTest(unittest.TestCase):
def setUp(self):
self.client = Client()
def test_response_for_get(self):
response = self.client.get(reverse('logIn'))
self.assertEqual(response.status_code, 200)
def test_login_with_username(self):
"""
Test if user can login wit username and password
"""
user_name = 'test'
user_email = 'test#test.com'
user_password = 'zaq12wsx'
u = User.objects.create_user(user_name,user_email,user_password)
response = self.client.post(reverse('logIn'),data={'name':user_name,'password':user_password},follow=True)
self.assertEquals(response.request.user.username,user_name)
u.delete()
And when i run this test i got failure on test_login_with_username:
AttributeError: 'dict' object has no attribute 'user'
When i use in views request.user.username in works fine no error this just fails in tests. Thanks in advance for any help
edit:Ok I replace the broken part with
self.assertEquals(302, response.status_code)
But now this test breaks and another one too.
AssertionError: 302 != 200
Here is my code for the view that now fail. I want email and username to be unique.
def register(request):
"""
Function to register new user.
This function will have to care for email uniqueness,and login
"""
if request.method == 'POST':
error=[]
form = RegisterForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
if form.cleaned_data['password'] == form.cleaned_data['password_confirmation']:
password = form.cleaned_data['password']
if len(User.objects.filter(username=username)) == 0 and len(User.objects.filter(email=email)) == 0:
#email and username are bouth unique
u = User()
u.username = username
u.set_password(password)
u.email = email
u.is_active = False
u.is_superuser = False
u.is_active = True
u.save()
return render_to_response('success_register.html',locals(),context_instance=RequestContext(request))
else:
if len(User.objects.filter(username=username)) > 0:
error.append("Podany login jest juz zajety")
if len(User.objects.filter(email=email)) > 0:
error.append("Podany email jest juz zajety")
else:
error.append("Hasla nie pasuja do siebie")
#return render_to_response('register.html',locals(),context_instance=RequestContext(request))
else:
form = RegisterForm(auto_id=False)
return render_to_response('register.html',locals(),context_instance=RequestContext(request))
And here is the test that priviously work but now it is broken
def test_user_register_with_unique_data_and_permission(self):
"""
Will try to register user which provided for sure unique credentials
And also make sure that profile will be automatically created for him, and also that he he have valid privileges
"""
user_name = 'test'
user_email = 'test#test.com'
password = 'zaq12wsx'
response = self.client.post(reverse('register'),{'username': user_name,'email':user_email,
'password':password,'password_confirmation':password},follow=True)
#check if code is 200
self.assertEqual(response.status_code, 200)
u = User.objects.get(username=user_name,email = user_email)
self.assertTrue(u,"User after creation coudn't be fetched")
self.assertFalse(u.is_staff,msg="User after registration belong to staff")
self.assertFalse(u.is_superuser,msg="User after registration is superuser")
p = UserProfile.objects.get(user__username__iexact = user_name)
self.assertTrue(p,"After user creation coudn't fetch user profile")
self.assertEqual(len(response.context['error']),0,msg = 'We shoudnt get error during valid registration')
u.delete()
p.delete()
End here is the error:
AssertionError: We shoudnt get error during valid registration
If i disable login test everything is ok. How this test can break another one? And why login test is not passing. I try it on website and it works fine.
The documentation for the response object returned by the test client says this about the request attribute:
request
The request data that stimulated the response.
That suggests to me one of two things. Either it's just the data of the request, or it's request object as it was before you handled the request. In either case, you would not expect it to contain the logged in user.
Another way to write your test that the login completed successfully would be to add follow=False to the client.post call and check the response code:
self.assertEquals(302, response.status_code)
This checks that the redirect has occurred.
response.request is not the HttpRequest object in the view you are expecting. It's a dictionary of data that stimulated the post request. It doesn't have the user attribute, hence the AttributeError
You could rewrite your test to:
use the RequestFactory class introduced in Django 1.3 and call logIn in your test directly instead of using client.post.
inspect client.session after the post to check whether the user has been logged in.
Why one failing test can break another
When you edited the question, you asked
How this test can break another one?
The test_login_with_username was failing before it reached u.delete, so the user created in that test was not deleted. That caused test_user_register_with_unique_data_and_permission because the user test already existed.
If you use the django.test.TestCase class, the database will be reset in between each test, so this wouldn't be a problem.