-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathotp-service.py
130 lines (100 loc) · 3.83 KB
/
otp-service.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
from flask import Flask, request, jsonify
from flask_mysqldb import MySQL
import random
import datetime
from dotenv import load_dotenv
import os
# For email send OTP
import smtplib
from email.mime.text import MIMEText
# For SMS send OTP
from twilio.rest import Client
# Check if running on local environment
if os.path.exists('.env'):
ENV = 'local'
else:
ENV = 'production'
# Load environment variables
if ENV == 'local':
load_dotenv()
app = Flask(__name__)
# MySQL Configuration
app.config['MYSQL_HOST'] = os.getenv('MYSQL_HOST')
app.config['MYSQL_USER'] = os.getenv('MYSQL_USER')
app.config['MYSQL_PASSWORD'] = os.getenv('MYSQL_PASSWORD')
app.config['MYSQL_DB'] = os.getenv('MYSQL_DB')
# Email Configuration
app.config['EMAIL_HOST'] = os.getenv('EMAIL_HOST')
app.config['EMAIL_PORT'] = int(os.getenv('EMAIL_PORT')) # Convert to int
app.config['EMAIL_USERNAME'] = os.getenv('EMAIL_USERNAME')
app.config['EMAIL_PASSWORD'] = os.getenv('EMAIL_PASSWORD')
# Twilio Configuration
app.config['TWILIO_ACCOUNT_SID'] = os.getenv('TWILIO_ACCOUNT_SID')
app.config['TWILIO_AUTH_TOKEN'] = os.getenv('TWILIO_AUTH_TOKEN')
app.config['TWILIO_PHONE_NUMBER'] = os.getenv('TWILIO_PHONE_NUMBER')
mysql = MySQL(app)
def generate_otp():
return str(random.randint(100000, 999999))
def send_email(to_email, otp):
subject = "Your OTP Code"
body = f"Your one-time password (OTP) is: {otp}"
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = app.config['EMAIL_USERNAME']
msg['To'] = to_email
with smtplib.SMTP(app.config['EMAIL_HOST'], app.config['EMAIL_PORT']) as server:
server.starttls()
server.login(app.config['EMAIL_USERNAME'], app.config['EMAIL_PASSWORD'])
server.send_message(msg)
def send_sms(to_phone, otp):
client = Client(app.config['TWILIO_ACCOUNT_SID'], app.config['TWILIO_AUTH_TOKEN'])
message = client.messages.create(
body=f"Your one-time password (OTP) is: {otp}",
from_=app.config['TWILIO_PHONE_NUMBER'],
to=to_phone
)
@app.route('/generate_otp', methods=['POST'])
def generate_otp_route():
data = request.get_json()
user_id = data.get('user_id')
otp = generate_otp()
expires_at = datetime.datetime.now() + datetime.timedelta(minutes=2) # OTP valid for 2 minutes
cur = mysql.connection.cursor()
cur.execute("INSERT INTO otps (user_id, otp, expires_at) VALUES (%s, %s, %s)", (user_id, otp, expires_at))
mysql.connection.commit()
cur.close()
# Fetch user information from the database
cur = mysql.connection.cursor()
cur.execute("SELECT email, phone FROM users WHERE id = %s", (user_id,))
user_info = cur.fetchone()
cur.close()
if not user_info:
return jsonify({'message': 'User not found.'}), 404
email, phone = user_info
# Send OTP via email and/or SMS if defined
if email:
send_email(email, otp)
if phone:
send_sms(phone, otp)
return jsonify({'message': 'OTP sent via email and/or SMS.'}), 201
# return jsonify({'otp': otp, 'expires_at': expires_at.strftime('%Y-%m-%d %H:%M:%S')}), 201
@app.route('/validate_otp', methods=['POST'])
def validate_otp_route():
data = request.get_json()
user_id = data.get('user_id')
otp = data.get('otp')
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM otps WHERE user_id = %s AND otp = %s AND expires_at >= NOW()", (user_id, otp))
result = cur.fetchone()
cur.close()
if result:
# OTP is valid, delete it from the database
cur = mysql.connection.cursor()
cur.execute("DELETE FROM otps WHERE user_id = %s AND otp = %s", (user_id, otp))
mysql.connection.commit()
cur.close()
return jsonify({'message': 'OTP is valid.'}), 200
else:
return jsonify({'message': 'OTP is invalid or expired.'}), 400
if __name__ == '__main__':
app.run(debug=True)