paint-brush
Dzivisa Email Spam Nekuvaka Yakachengeteka Fomu muPython by@tom2
338 kuverenga
338 kuverenga

Dzivisa Email Spam Nekuvaka Yakachengeteka Fomu muPython

by Rutkat11m2024/09/04
Read on Terminal Reader

Kurebesa; Kuverenga

Kero yeemail inoshanda inzira yekumisikidza kutaurirana zvakananga, kugadzira zvinotungamira, kuwana kutengesa, kukoka kwakavanzika kunharaunda dzepamhepo, nezvimwewo. Hatifanire kuvimba nekushandisa masevhisi ebato seAuth0, Facebook, kana Google kuti tiwane mukana app yako nemasevhisi. Isu tichashandisa iripo Python modules inorerutsa kuchenesa mushandisi kupinza, kugadzira yekutarisa link, uye kutaurirana nedhatabhesi.
featured image - Dzivisa Email Spam Nekuvaka Yakachengeteka Fomu muPython
Rutkat HackerNoon profile picture

Kero yeemail inoshanda isuwo rekumisikidza kutaurirana kwakananga, kugadzira zvinotungamira, kuwana kutengesa, kukoka kwepachivande kunharaunda dzepamhepo, nezvimwewo. Usazvitore sekurerutsa nekuti social media iri kuchinja. Kuburikidza nekushanduka mu tech, email ichiri nzira yakaedzwa uye yechokwadi yekubatanidza. Tichachengeta zvinhu zviri nyore uye kwete kodhi kubva kutanga nekuti Python ine mamodule aripo ekukubatsira iwe kukurumidze kukodha.


Ndakaita kuti vatengi vandikumbire kuti ndivake mafomu ekusayina e-email kuti vasimudzire zvigadzirwa zvavo, asi hapana kana mumwe wevatengi ivavo aida kubhadhara mari dzepamwedzi dzechitatu-party off-the-sherufu, saka ndakavachengetera mari nekuvaka mafomu ekuonana akasarudzika. kuti vanogona kushandisa zvachose. Ini ndinogona kukubatsira kuti uite zvakafanana kungave kwekutanga kwako, mutengi, zvinangwa zvekushambadzira, kana zvakanyanya kupfuura zvese, kudzikisira spam.


Izvi ndezvemunhu wese anoda kudzidza kukodha muPython uye inonyanya kubatsira kune vanotanga vangave vasingatarise maficha ekuchengetedza akadai sesefa mushandisi wekuisa, kusimbisa email kero, uye email kaviri opt-ins. Muchidzidzo ichi, tinovhara matanho 1-3:


  1. Kusefa mushandisi yekero yeimeri inoshanda
  2. Saina-kupinda kaviri
  3. Bot/spam kudzivirira


Hatifanirwe kuvimba nekushandisa 3rd bato masevhisi akadai seAuth0, Facebook, kana Google kuti uwane mukana kune yako app nemasevhisi anogona kukuvhara chero nguva kana kugovera data rako. Chengetedza data rako rekushandisa nderako!


Kutanga, iwe unofanirwa kuve neruzivo muPython nekuti isu tichashandisa iyo Flask framework ine MySQL dhatabhesi . Izvi zvichanyanya kunakidza (pamwe) pane kushandisa WordPress, iyo inonyanya kufarirwa CMS. Iwe waizofanira kubhadhara kune imwe WordPress plugin kuti uve neyakafanana kugona seyemahara Flask yekuwedzera. Ini ndakavaka kare paWordpress (PHP) uye ndinofarira Python Flask yewebhu maapplication kunyangwe Wordpress inokwanisa kwazvo kugadzira mawebhusaiti.


Isu tichashandisa iripo Python modules inorerutsa yekuchenesa mushandisi kupinza, kugadzira yekutarisa link, uye kutaurirana nedhatabhesi.


Imwe neimwe kodhi snippet ichatsanangurwa uye ichasanganisira mamwe mazwi mukodhi. Kana iwe usati wavaka kunyoreswa kwemushandisi kana kuziva nezvekushanda kwemukati, ini ndichakutsanangurira iwo maficha, uye wobva waona iyo yekupedzisira kodhi kumagumo (usasvetukire kumberi).


Heino pfupiso yezvimiro zvatichashandisa sezvataurwa mundima yekutanga:


  1. Kero yeemail inoshanda inogona kutariswa nekupatsanura tambo yekupinda kubva kumushandisi uchishandisa yakajairika kutaura kana Flask yekuwedzera. Hatizobvumiri zvinyorwa zvisina kurongeka kana SQL jekiseni rudzi rwehacks.


  2. Nzira yekupinda mairi inoda kuti mugamuchiri akupe mvumo yekuti uvatumire email nekugamuchira chinongedzo chekusimbisa kubhokisi ravo rekutumira. Izvi zvinonyanya kushandiswa kudzivirira mumwe munhu kushandisa email yako kero. Izvi zvinodzivirirawo vashandisi vebvunzo vanongosaina uye kusiya maakaundi avo.


  3. Kudzivirirwa kwebhoti kunogona kuitwa nemunda wakavanzika usina kuratidzwa kumushandisi asi inowanzozadzwa otomatiki nemabhoti achikambaira kune anotambura kusaina mafomu, asi haina kuvimbika se "captcha" kubva kune yechitatu bato sevhisi.


Ngatitangei kukodha. Gadzira dhairekitori rekushanda:

 mkdir signup cd signup


Gadzira yako Python nharaunda uchishandisa python3 -m venv signup kana conda create -n double-opt-contact python3 . Ini ndinosarudza conda, uye kana iwe uchida kudzidza zvakawanda, unogona kuverenga yangu Python nharaunda chinyorwa.


Isa zvinotevera zvinoenderana:
pip flask flask-mail secure SQLAlchemy Flask-WTF Flask-SQLAlchemy mysql-connector-python bleach

Neimwe nzira, unogona kuva nezvinotsamira zvakafanana zvakanyorwa requirements.txt faira womhanya pip install -r requirements.txt


Gadzira app.py faira ine zvinotevera zvinovimbika zvinosanganisirwa:


 from flask import Flask, render_template, request, url_for, redirect, flash from flask_mail import Mail, Message from datetime import datetime from flask_sqlalchemy import SQLAlchemy from sqlalchemy.sql import func from itsdangerous import URLSafeTimedSerializer, SignatureExpired import secrets import bleach


Tanga chinhu cheapp neiyo default template folda nzvimbo:

 app = Flask(__name__, template_folder='templates')


Pinda yako wega server dhizaini data uchishandisa iyi mitsetse:

 secret = secrets.token_urlsafe(32) app.secret_key = secret app.config['SECRET_KEY'] = secret # auto-generated secret key # SQLAlchemy configurations app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://admin:user@localhost/tablename' # Email configurations app.config['MAIL_SERVER'] = 'smtp.example.com' app.config['MAIL_PORT'] = 465 #check your port app.config['MAIL_USERNAME'] = '[email protected]' app.config['MAIL_PASSWORD'] = 'your_password' app.config['MAIL_USE_TLS'] = True app.config['MAIL_USE_SSL'] = False db = SQLAlchemy(app) mail = Mail(app) sserialzer = URLSafeTimedSerializer(app.config['SECRET_KEY']) #set secret to the serliazer


Chekupedzisira, iwe unofanirwa kuve neyako config info .env faira.


Tichada dhatabhesi reMySQL kuchengetedza vashandisi vanogona kugadzirwa nemaoko kana nePython kodhi. Sechikamu chemaitiro ekudzidza, unogona kuisa kodhi inotevera uchishandisa mutsara wekuraira kana kushandisa Python's with app.app_context() db_create_all() nzira.


Nzvimbo yakasimbiswa ndeye tambo yechiratidzo iyo inobvumira maitiro maviri opt-in.

 CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(120) NOT NULL UNIQUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, validated BOOLEAN DEFAULT FALSE );


Chikamu chinotevera chinoshandisa SQLAlchemy's ORM chimiro kukubvunza iwe dhatabhesi. Ziva kuti zita rekirasi rinofanira kufanana nezita rako retafura yedatabase, zvikasadaro, iwe unowana chikanganiso. Iyo db.model inomiririra zvigadziriso zvetafura yako iyo inosanganisira zita rekoramu, mhando yaro, kureba, kiyi, uye kukosha kusina maturo:


 class User(db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(120), unique=True, nullable=False) created_at = db.Column(db.DateTime, server_default=db.func.now()) validated = db.Column(db.Boolean, default=False)


Kana usati watogadzira tafura yeMySQL dhatabhesi kare, unogona kuzviita neiyi Flask kodhi zvakananga mushure mekirasi class User kodhi block:

 # Create the database table with app.app_context(): db.create_all()


Zvino, isu tinoisa iyo yekumashure-yekupedzisira kodhi inova 2 mapeji/nzira (index, signup), iyo email meseji, uye simbiso. Peji yekusaina inosanganisira nzira GET/POST dzinotendera kuti fomu ritumirwe. Iyo bleach chinhu ndeye Python yekuwedzera iyo inochenesa iyo yekupinza kubva kumushandisi kuti ive nechokwadi chekuchengetedza uye kudzikisira zvinyorwa zvakaipa. Ipapo sserializer inogadzira chiratidzo chenguva-imwe kutumira email iyo yekusimbisa link.


 @app.route('/') def index(): return '<h1>Index page</h1>' @app.route('/signup', methods=['GET', 'POST']) def signup(): if request.method == 'POST': email = bleach.clean(request.form.get('email')) # Insert user into the database new_user = User(email=email) try: db.session.add(new_user) db.session.commit() except Exception as e: print(f"Error occurred saving to db: {e}") # Send confirmation email token = sserialzer.dumps(email, salt='email-confirm') msg = Message('Confirm your Email', sender='[email protected]', recipients=[email]) link = url_for('confirm_email', token=token, _external=True) msg.body = f'Your link is {link}' try: mail.send(msg) except Exception as e: print(f"Error occurred sending message: {e}") flash("Error occurred sending message!") return render_template('signup.html') flash('A confirmation email has been sent to your email address.', 'success') return redirect(url_for('index')) return render_template('signup.html')


Tisati tawedzera fomu rekusaina reHTML, ngatizadzise kuseri nekuwedzera nzira yekusimbisa iyo mbiri yekupinda-mukati. Iyi nzira inoshandisa iyo s chinja yatakagadzira kare iyo inogadzira iyo inobata nguva, yakavanzika tokeni. Maona ma docs kuti uwane ruzivo .


Iyo max-zera masekonzi iyo link isati yapera, saka mune iyi kesi, mushandisi ane maminetsi makumi maviri ekusimbisa email kero yavo.


 @app.route('/confirm_email/<token>') def confirm_email(token): try: email = sserialzer.loads(token, salt='email-confirm', max_age=1200) # Token expires after 1 hour except SignatureExpired: return '<h1>The token is expired!</h1>' # Update field in database user = User.query.filter_by(email=email).first_or_404() user.validated = True db.session.commit() return '<h1>Email address confirmed!</h1>'


Ikozvino, kune iyo ubiquitous chirevo chikuru chinoudza Python kuti iite script kana faira iri kuitwa zvakananga (kusiyana neinounzwa kunze module):

 if __name__ == '__main__': app.run()


Tisati tapedza iyi kodhi yekumashure-yekupedzisira, isu tichiri kuda iyo yekumberi-yekupedzisira HTML yekuisa mushandisi. Tichaita izvi neFlask yakavakirwa-mukati Jinja template. Gadzira faira rine zita rekuti templates/signup.html iro rinofanira kuenderana nemazita awakagadzira pakutanga app.py . Nekutadza, Jinja anoshandisa dhairekitori /templates emafaira ehtml. Unogona kushandura iyi marongero, asi kune ino dzidziso, isu tichashandisa iyo /templates dhairekitori yeapp.

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Email Sign Up</title> </head> <body> <h1>Sign Up</h1> <form action="{{ url_for('signup') }}" method="POST"> <input type="email" name="email" placeholder="Enter your email" required> <input type="submit" value="Sign Up"> </form> {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} <ul> {% for category, message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} </body> </html>


Kodhi yako inofanirwa kunge ichishanda kubva panguva ino kana iwe uchimhanyisa iyo flask command ine debugging inogoneswa. Izvi zvinokutendera kuti uone chero zvikanganiso mumutsara wekuraira pamwe nebrowser hwindo:


 flask --app app.py --debug run


Vhura browser yako kune iyo domain inoratidzwa mumutsara wekuraira (localhost) uye index peji inofanirwa kupa. Edza kuendesa fomu uchishandisa email kero yechokwadi kuti ugamuchire chinongedzo chekusimbisa. Kana wangowana chinongedzo, chinofanira kuita sekuti http://localhost:5000/confirm_email/InRvbUByYXRldG91cmd1aWRlcy5jb20i.ZteEvQ.7o1_L0uM9Wl8uii7KhJdiWAH , unogona kuitevera uye kuwana iyo email kero inoratidzwa uchishandisa iyo nzira ye email inoratidzwa pano:


 @app.route('/confirm_email/<token>') def confirm_email(token): try: email = sserializer.loads(token, salt='email-confirm', max_age=1200) # Token expires after 1 hour except SignatureExpired: return '<h1>Oops, the token expired!</h1>' # Update field in database user = Users.query.filter_by(email=email).first_or_404() user.validated = True try: db.session.commit() except Exception as e: print(f"Error occurred saving to db: {e}") return '<h1>Email address confirmed!</h1>'


Iyi nzira inogamuchira tambo yechiratidzo yakambotumirwa kwauri uye inoitarisa kuti uone kana ichienderana neinopindirana dhatabhesi yekupinda. Kana ikadaro, inovandudza nzvimbo validated kuti True , uye unogona kuzorora uchiziva kuti fomu rako rekusaina harina kusiiwa.


Iri idanho rakakosha ese mabhizinesi akabudirira anoshandisa mumasisitimu avo ekunyoresa uye ikozvino unayo futi. Asi mira, ko kana tikawana bot kurwiswa kuendesa zvisingaite email kero pasina kuvasimbisa? Ipapo iwe unenge uine tsvina dhatabhesi yakazadzwa nezvisina basa. Ngatidzivise izvozvo!


Kuti udzivise kurwiswa kwebhoti kana kuti uderedze iyo yepamusoro, unogona kuvaka yako yega-inopedza nguva mhinduro, kusanganisira iyo IP limiter inoda in-memory dhatabhesi seRedis, kana iwe unogona kushandisa 3rd bato sevhisi senge Google's captcha kana. hCaptcha.


Muchidzidzo chedu, tichawedzera hcaptcha's chirongwa chemahara . Panguva yekunyora uku, google's captcha haisi yemahara uye hcaptcha iri. Kuti uve nekushanda kwesaiti yako, unofanirwa kunyoresa navo kuti utore kiyi yeAPI kubva kucaptcha.


Tinoda zvitsva zvinodiwa saka zviise:
pip install flask-hcaptcha requests


Zvikumbiro zvinodiwa kutumira email kero kuhcaptcha kuti isimbiswe. Tora kiyi, uye batanidza hcaptcha's javascript faira neHTML yako yekusaina fomu. Wedzera iyo faira kumusoro weHTML peji uye yako saiti kiyi kune fomu rako:


 <head> ... <script src="https://hcaptcha.com/1/api.js" async defer></script> </head> <body> ... <form action="{{ url_for('signup') }}" method="POST"> <input type="email" name="email" placeholder="Enter your email" required> <input type="submit" value="Sign Up"> <div class="h-captcha" data-sitekey="b62gbcc-5cg2-41b2-cd5a-de95dd1eg61h" data-size="compact"></div> </form>


Iyo saiti kiyi mune iyi kodhi muenzaniso; iwe uchada yako kubva kuhurongwa hwemahara. Iyi kiyi yepaiti inosimbisa fomu yako uye inoongorora muenzi wesaiti ine yakazara runyorwa rwe spam bots inozivikanwa nehcaptcha.


Tevere, shandura yako app.py faira kuti ubatanidze kiyi yakavanzika yehcaptcha (kwete kiyi yesaiti) muapp.config chinhu, uye tumira mhinduro kune hcaptcha usati waichengeta kune yako wega database.


 app.config['HCAPTCHA_SECRET_KEY'] = 'your-secret-hcaptcha-key' ... @app.route("/signup", methods=['GET', 'POST']) def signup(): if request.method == 'POST': email = bleach.clean(request.form.get('email')) hcaptcha_response = request.form.get('h-captcha-response') # Verify hCaptcha response payload = { 'secret': app.config['HCAPTCHA_SECRET_KEY'], 'response': hcaptcha_response } try: response = requests.post('https://hcaptcha.com/siteverify', data=payload, timeout=10) result = response.json() except requests.exceptions.RequestException as e: print(f"Request failed: {e}") if not result.get('success'): flash('CAPTCHA validation failed, please try again.', 'danger') ... # Insert user into the database new_user = Users(email=email)


Kana izvi zvangoitwa, iwe unenge uine hcaptcha icon inoratidza mune yako kusaina-up fomu, uye inofanirwa kugoneswa kudzivirira chero spam. Iye zvino, une fomu rakasimba reapp yako nyowani.


Kana iwe ukasangana nechero zvikanganiso kana iwe uine typo mune kodhi, unogona kutarisa iyo yapera kodhi pa yangu github.com


Comment kana uchida zvimwe.