-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
163 lines (142 loc) · 5.28 KB
/
Copy pathapp.py
File metadata and controls
163 lines (142 loc) · 5.28 KB
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
from flask import Flask, render_template, request, redirect, session, url_for, jsonify
from flask_socketio import SocketIO, send
from google_auth_oauthlib.flow import Flow
from google.oauth2 import id_token
import google.auth.transport.requests
from dotenv import load_dotenv
import os
import smtplib
from email.mime.text import MIMEText
from chat_db import init_db, register_user, verify_user, user_exists
# Environment setup
load_dotenv()
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev')
socketio = SocketIO(app, cors_allowed_origins="*")
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
GOOGLE_CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID")
GOOGLE_CLIENT_SECRET = os.getenv("GOOGLE_CLIENT_SECRET")
REDIRECT_URI = "http://localhost:5000/oauth2callback"
flow = Flow.from_client_config(
{
"web": {
"client_id": GOOGLE_CLIENT_ID,
"client_secret": GOOGLE_CLIENT_SECRET,
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"redirect_uris": [REDIRECT_URI]
}
},
scopes=["openid", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"]
)
flow.redirect_uri = REDIRECT_URI
@app.route('/')
def root():
return redirect(url_for('login'))
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
email = request.form['username'].strip()
username = email.split('@')[0]
password = request.form['password']
if register_user(email, username, password):
session['email'] = email
session['username'] = username
return redirect("http://localhost:3000/")
return "Username or email already taken. <a href='/register'>Try again</a>", 400
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
email = request.form['email'].strip()
password = request.form['password']
if verify_user(email, password):
session['email'] = email
session['username'] = email.split('@')[0]
return redirect("http://localhost:3000/")
return "Invalid credentials. <a href='/login'>Try again</a>", 401
return render_template('login.html')
@app.route("/google-login")
def google_login():
authorization_url, state = flow.authorization_url(
access_type="offline",
include_granted_scopes="true"
)
session["state"] = state
return redirect(authorization_url)
@app.route('/oauth2callback')
def oauth2callback():
flow.fetch_token(authorization_response=request.url)
if session.get("state") != request.args.get("state"):
return "State mismatch", 400
credentials = flow.credentials
request_session = google.auth.transport.requests.Request()
try:
id_info = id_token.verify_oauth2_token(
credentials._id_token,
request_session,
GOOGLE_CLIENT_ID
)
except ValueError:
return "Invalid token", 400
email = id_info.get("email")
username = id_info.get("name") or email.split('@')[0]
if not user_exists(email):
register_user(email=email, username=username)
session['email'] = email
session['username'] = username
return redirect("http://localhost:3000/")
@app.route('/send-email', methods=['POST'])
def send_email():
try:
sender = 'dhyantsoni@gmail.com'
receiver = 'aaryavlal12@gmail.com'
password = 'your_app_password' # Replace with actual password or load from env
msg = MIMEText('This is a predetermined message from your app.')
msg['Subject'] = 'Lend Request'
msg['From'] = sender
msg['To'] = receiver
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(sender, password)
smtp.sendmail(sender, receiver, msg.as_string())
return jsonify({'message': 'Email sent successfully!'}), 200
except Exception as e:
print(e)
return jsonify({'message': 'Failed to send email.'}), 500
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('login'))
if __name__ == '__main__':
init_db()
socketio.run(app, host='0.0.0.0', port=5000)
# @app.route('/chat')
# def chat():
# if 'username' not in session:
# return redirect(url_for('login'))
# return render_template('chatter.html', username=session['username'])
# @socketio.on('connect')
# def handle_connect(auth):
# if 'username' not in session:
# return
# messages = retrieve_messages()
# for row in reversed(messages[-50:]):
# send({
# "username": row["user_id"],
# "timestamp": row["timestamp"],
# "message": row["message"]
# })
# @socketio.on('message')
# def handle_message(data):
# username = session.get('username', 'guest')
# message = data.get('message', '')
# timestamp = datetime.now().strftime("%m/%d/%Y %H:%M")
# save_message(username, message, timestamp)
# send({
# "username": username,
# "timestamp": timestamp,
# "message": message
# }, broadcast=True)
if __name__ == '__main__':
init_db()
socketio.run(app, host='0.0.0.0', port=5000)