paint-brush
Correo electrónico spam kaqmanta karunchakuy huk Seguro Formulariota Python kaqpi ruwaspa by@tom2
327 ñawinchasqakuna
327 ñawinchasqakuna

Correo electrónico spam kaqmanta karunchakuy huk Seguro Formulariota Python kaqpi ruwaspa

by Rutkat11m2024/09/04
Read on Terminal Reader

Nishu unay; Ñawinchanapaq

Huk allin correo electrónico direccion huk punku kanku chiqa willayta sayarichinapaq, pusaykunata paqarichiypaq, rantiyta, sapalla invitacionkunata internetpi ayllukunaman, wakkunaman ima appniyki chaymanta serviciokunayki. Kunan kaq Python módulos kaqwan llamk'asaqku mayqinkunachus ruwaqpa yaykuyninta pichayta, chiqaqchay tinkiyta ruwayta, chaymanta willaypa tiyapuyninwan willayta pisiyachinku.
featured image - Correo electrónico spam kaqmanta karunchakuy huk Seguro Formulariota Python kaqpi ruwaspa
Rutkat HackerNoon profile picture

Huk allin correo electrónico direccionqa huk punku kan chiqa willayta sayachinapaq, pusaqkunata paqarichiypaq, rantiyta, sapalla invitacionkunata internetpi ayllukunaman, wakkunaman ima.. Ama chayta hap'iychu imaraykuchus social medios tikrakun. Tecnología kaqpi evoluciones kaqnintakama, correo electrónico kunankamapas pruebasqa chaymanta chiqa ñan tinkinapaq kachkan. Imakunatapas sasallawan waqaychasaqku chaymanta mana zeromanta codificasaqkuchu imaraykuchus Python kunan kaq módulosniyuq kachkan codificación usqhaylla yanapasunaykipaq.


Ñuqaqa rantiqkuna mañawarqanku correo electrónico qillqakuy formulariokuna ruwayta rurunkuta riqsichinapaq, ichaqa mana mayqinpas chay rantiqkunamanta sapa killa qullqita quyta munarqankuchu huk 3 kaq partimanta mana estante serviciopaq, chayrayku qullqita waqaycharqani ruwasqa formulariokuna tinkiyta ruwaspa chayta wiñaypaq apaykachanankupaq. Yanapaykiman kaqllata ruwanaykipaq sichus qallariyniykipaq, clientepaq, qhatuypaq propósitos kaqpaq utaq aswan allin, spam pisiyachinapaq.


Kayqa pillapas Python kaqpi codificayta yachayta munaqpaq chaymanta aswan allin qallariqkunapaq mayqinkunachus mana harkasqa ruwanakunata qhawankumanchu kayhinata ruwaqpa yaykuynin filtrayta, correo electrónico direccionkunata chiqaqchay, chaymanta correo electrónico iskay akllanakuna. Kay yachachiypi, 1-3 ruwaykunata qhawarisunchik:


  1. Ruwaqpa yaykuyninta filtray huk allin correo electrónico direccionpaq
  2. Iskay kutita akllanapaq qillqakuy
  3. Bot/spam hark'ay


Mana 3 kaq parti serviciokuna Auth0, Facebook utaq Google hina llamk'achiyta hapipakunaykuchu tiyan appniykiman chaymanta yanapakuyniykiman yaykuypaq mayqinkunachus mayk'aqllapas wichq'asunkiman utaq willayniyki qunakunkuman. ¡App datuykikunata qampaq waqaychay!


Qallariypi, wakin experienciayuq kanayki tiyan Python kaqpi imaraykuchus Flask marcota huk MySQL willaypa tiyapuyninwan llamk'achisaqku . Kayqa aswan kusikuy kanqa (ichapas) WordPress llamk'achiyta, aswan riqsisqa CMS kaqmanta. Wakin WordPress plugin kaqmanta qullqita qunayki kanman huk mana qullqiyuq Flask mast'ariy hina kikin atiyniyuq kananpaq. Ñawpaqta Wordpress (PHP) kaqpi ruwarqani chaymanta Python Flask web ruwanakunapaq aswan allin kani Wordpress web ruwanakuna ruwanapaq ancha atiq kaptinpas.


Kunan kaq Python módulos kaqwan llamk'asaqku mayqinkunachus ruwaqpa yaykuyninta pichayta, chiqaqchay tinkiyta ruwayta, chaymanta willaypa tiyapuyninwan willayta pisiyachinku.


Sapa codigo fragmento sut'inchasqa kanqa, wakin rimaykunata codigopi churanqa. Sichus mana ruwaqpa registronta ruwarqankichu utaq ukhu llamk'aykunata yachankichu, qampaq detallekunata willasqayki, chaymanta tukukuy codigo tukukuypi qhawayta atikunki (ama ñawpaqman saltaychu).


Kaypim kachkan punta kaq parrafopi nisqanchikman hina implementasunchik ruwaykunamanta:


  1. Huk allin correo electrónico direccionta qhawayta atikunman yaykusqa watiqata ruwaqmanta t'aqwispa huk sapa kuti rimaywan utaq huk Flask mast'ariywan. Mana permitisaqkuchu random texto utaq SQL inyección laya hacks kaqmanta.


  2. Iskay kuti akllana ñanqa chaskiqman permisota qunanpaq mañan paykunaman correo electrónico kaqpi apachinaykipaq huk chiqaqchay tinkiyta paykunap yaykuyninkuman chaskispa. Kayqa aswanta huk runa correo electrónico direccionniykita mana llamk'achinanpaq llamk'achkan. Kayqa hark'antaq prueba ruwaqkunata mayqinkunachus qillqakullanku chaymanta yupayninkuta saqinku.


  3. Bot hark'ayqa huk pakasqa pampawan ruwakunman mayqinchus mana ruwaqman rikuchisqachu ichaqa sapa kuti auto-hunt'asqa bots kaqwan rastreo kaqwan mana allin qillqakuy formulariokuna kaqpaq, ichaqa mana huk "captcha" hinachu huk 3 kaq parti serviciomanta.


Codificayta qallarisun. Llamk'ana qillqana mayt'uta ruray:

 mkdir signup cd signup


Python muyuriqniykita ruway python3 -m venv signup utaq conda create -n double-opt-contact python3 . Conda nisqatam aswan allinta munani, aswan yachayta munaspaqa, Python muyuriqkunamanta qillqasqayta ñawinchayta atinki.


Kay dependenciakunata churay:
pip flask flask-mail secure SQLAlchemy Flask-WTF Flask-SQLAlchemy mysql-connector-python bleach

Hukninpi, kikin dependenciakuna huk requirements.txt willañiqipi listasqayuq kayta atikunki chaymanta pip install -r requirements.txt purichiy


app.py willañiqita ruway kay qatiq dependenciakuna churasqawan:


 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


App objeto qallariy plantilla carpeta ñawpaqmanta churasqa maypi kasqanwan:

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


Kikin sirwiq wakichiy willayta kay chirukunata llamk'achispa qillqay:

 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


Qhipaman, config info nisqayki .env willañiqipi kanan tiyan.


Huk MySQL willaypa tiyapuyninta necesitasaqku ruwaqkunata waqaychaypaq mayqinchus makiwan utaq Python codigowan ruwasqa kanman. Yachay ruwaypa huknin hina, kay qatiq codigo kamachiy-chiruwan utaq Python's with app.app_context() db_create_all() ruwaywan yaykuchiyta atikunki.


Chiqachasqa pampaqa huk token watiqapaq kachkan mayqinchus iskay akllana ruwayta saqin.

 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 );


Qatiqnin t'aqa SQLAlchemy kaqpa ORM ruwayninta llamk'achin qampaq willaypa tiyapuyninta tapunapaq. Reparay, clase sutiqa willay tantana tabla sutiykiwan tupanan tiyan, mana hina kaqtinqa, pantayta tarinki. db.model tabla churanaykikunata rikuchin mayqinkunachus sapaq sutita, laya kayninta, sayayninta, llaventa, chaymanta ch'usaq chaninninta ima churan:


 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)


Sichus manaraq makiwan MySQL willaypa tiyapuynin tablata ruwarqankiñachu, kay Flask codigowan chiqalla ruwayta atikunki class User codigo bloquemanta:

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


Kunan, qhipa-tukuy codigota yaykuchiyku mayqinchus 2 p'anqakuna/rutas (índice, qillqakuy), correo electrónico willayta, chaymanta takyachiy. Inscribikuy p'anqapiqa GET/POST ruwaykunam kachkan, chaykunam formulariota apachiyta saqin. bleach objeto huk Python mast'ariy kachkan chaymanta yaykusqata ruwaqmanta pichan seguridadta qhawanapaq chaymanta mana allin scriptkunata pisiyachinapaq. Chaymanta sserializer huk kutilla token ruwan chiqaqchay t'inki correo electrónico kaqman.


 @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')


Manaraq HTML qillqakuy formulariota yapachkaspa, qhipa ruwayta hunt'asun iskay kuti akllana ruwayta chiqaqchaypaq ñanta yapaspa. Kay ñanqa ñawpaq ruwasqayku s variableta llamk'achin mayqinchus pacha-sensible, pakasqa tokenta paqarichimun. Qaway chay docs nisqakunata detallespaq .


Max-edadqa segundos manaraq t'inki tukukuchkaptin, chayrayku kayhinapi, ruwaq 20 minutoyuq correo electrónico direccionninta takyachinanpaq.


 @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>'


Kunan, tukuyniqpi kaq hatun willakuypaq mayqinchus Pythonman nin qillqa mayt'uta ruwananpaq sichus willañiqi chiqalla ruwasqa kachkan (huk hawamanta apamusqa módulo kaqmanta):

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


Manaraq kay qhipa-tukuy codigo tukuchkaptiyku, ñawpaq-tukuy HTML kaqnintaraq necesitanchik user yaykuypaq. Kayta ruwasaqku Flaskpa Jinja plantilla incorporada nisqawan. Huk willañiqita ruway templates/signup.html sutiyuq mayqinchus sutiwan tupanan tiyan ñawpaq ruwasqayki ñanwan app.py kaqpi. Ñawpaqmanta, Jinja /templates willañiqita html willañiqikunapaq llamk'achin. Kay churayta tikrayta atikunki, ichaqa kay yachachiypaq, /templates directorio app kaqmanta llamk'achisaqku.

 <!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>


Codigoykiqa kaymanta llamk'anan tiyan mayk'aq flask kamachiyta pantasqa allichay atichisqawan purichichkanki. Kayqa kamachiy chirupi ima pantasqatapas qhawayta atikunki chaymanta maskaqpa ventananta:


 flask --app app.py --debug run


Navegadorniyki kamachiy-chirupi rikuchisqa kamachiyman (localhost) kichay chaymanta indis p'anqa ruwanan tiyan. Chiqaqchay tinkiyta chaskinaykipaq allin correo electrónico direccionta llamk'achispa formulariota apachiyta kallpachakuy. Huk kuti t'inkita chaskinki, kayhina rikch'akunan tiyan http://localhost:5000/confirm_email/InRvbUByYXRldG91cmd1aWRlcy5jb20i.ZteEvQ.7o1_L0uM9Wl8uii7KhJdiWAH , qatiyta atikunki chaymanta correo electrónico direccionta validasqata tarinki kaypi rikuchisqa validador ñanta llamk'achispa:


 @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>'


Kay ñanqa ñawpaq apachisqa token kaskaqta chaskikun chaymanta qhawan sichus tupaq willaypa tiyapuynin yaykuywan tupan icha manachu. Sichus ruwan, validated pampata musuqchan True kaqman , chaymanta samayta atikunki yachaspa qillqakuy formularioyki mana saqisqachu.


Kayqa huk importante paso llapa negociokuna allin ruwaqkuna sistemakuna registronkupi llamk'achinku chaymanta kunan qampas chayta kanki. Ichaqa suyay, ¿imataq kanman sichus bot ataques nisqakunata chaskiykuman correo electrónico al azar direccionkunata apachispa mana validaspa? Chaymantaqa qhilli willay tantanayuqmi kanki, mana imapaqpas valeq qillqakunawan hunt'asqa. ¡Chayta hark'asun!


Bot ataques hark'anapaq utaq aswan pisi ñawpaq kaqkunata pisiyachinapaq, kikiyki pacha hap'iq allichayta ruwayta atikunki, chaymanta huk IP limitador kaqwan mayqinchus huk yuyarina ukhupi willaypa tiyapuyninta Redis hina munan, utaq huk 3 kaq yanapakuyta llamk'achiy atikunki kayhina Google captcha utaq hCaptcha.


Yachachiyniykupi, yapasaqku hcaptchapa plan gratis . Kay qillqasqa kachkaptinqa, googlepa captchanqa manam gratischu, hcaptchañataqmi. Kay llamk'ayta kitiykipaq kananpaq, paykunawan qillqakunayki tiyan API llaveta captcha kaqmanta jap'inaykipaq.


Musuq mañakuykunata necesitayku chayrayku churay:
pip install flask-hcaptcha requests


Mañakuykuna necesitakun correo electrónico direccionta hcaptchaman apachinapaq chiqaqchaypaq. Llaveta hapiy, chaymanta hcaptcha javascript willañiqita HTML qillqakuy formularioykiwan tinkiy. Willayta HTML p'anqaykipa umanman yapay chaymanta sitioykipa llaventa formularioykiman:


 <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>


Kay codigopi sitio llaveqa huk ejemplon; necesitanki kikiykita chay plan gratismanta. Kay sitio llave formularioyki validan chaymanta sitio watukuqta huk tukuypaq listawan spam bots hcaptcha kaqwan riqsisqa kaqwan qhawan.


Chaymanta, app.py willañiqiykita tikray hcaptcha pakasqa llaventa (mana sitio llavetachu) app.config kaqpi churanapaq, chaymanta hcaptchaman kutichiyta churay manaraq kikin willaypa tiyapuyninman waqaychaspa.


 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)


Huk kuti kay ruwasqa, hcaptcha icono rikuchikunki qillqakuy formularioykipi, chaymanta atichisqa kanan tiyan ima spam hark'anapaq. Kunanqa, musuq appniykipaq aswan kallpasapa formularioyuq kanki.


Sichus ima pantaywanpas tupanki utaq huk pantasqa qillqana codigopi kanki, hunt'asqa codigota qhawayta atikunki mi github.com nisqa


Astawan munaspaqa comentay.