-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
255 lines (180 loc) · 7.27 KB
/
app.py
File metadata and controls
255 lines (180 loc) · 7.27 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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import os
import pathlib
import requests
import cachecontrol
import psycopg2
from flask import Flask,request,render_template,session,abort,redirect,jsonify
from flask_sqlalchemy import SQLAlchemy
from google_auth_oauthlib.flow import Flow
from google.oauth2 import id_token
import google.auth.transport.requests
app=Flask(__name__)
app.secret_key="InfyInterns"
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://InfyAdmin@knowledge-portal-db:Assignment2022@knowledge-portal-db.postgres.database.azure.com:5432/knowledge_portal'
app.config['SQLAlCHEMY_TRACK_MODIFICATIONS']=False
db=SQLAlchemy(app)
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
GOOGLE_CLIENT_ID="1005262086641-mmfblvv9m16293ufmop8tufas7qcsqsv.apps.googleusercontent.com"
client_secrets_file=os.path.join(pathlib.Path(__file__).parent,"client_secret.json")
flow=Flow.from_client_secrets_file(
client_secrets_file=client_secrets_file,
scopes=["https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email", "openid"],
redirect_uri="http://127.0.0.1:5000/callback"
)
#Decorator for Authentication
def login_is_required(function):
def wrapper(*args,**kwargs):
if "google_id" not in session:
return abort(401)
else:
return function()
wrapper.__name__=function.__name__
return wrapper
#Topic Table
class Topic(db.Model):
__tablename__ = 'topic'
id = db.Column(db.Integer, primary_key = True)
topic_title = db.Column(db.String(100), nullable = False)
topic_description = db.Column(db.String(500), nullable = False)
posts = db.relationship('Post', backref='topic', lazy='dynamic')
#Post Table
class Post(db.Model):
__tablename__ = 'post'
id = db.Column(db.Integer, primary_key = True)
topic_id = db.Column(db.Integer, db.ForeignKey('topic.id'))
user_id=db.Column(db.String(100), nullable=False)
post_title = db. Column(db.String(100), nullable = False)
post_description = db.Column(db.String(500), nullable = False)
#User Table
class User(db.Model):
__tablename__ = 'user'
google_id = db.Column(db.String(100), primary_key = True)
name = db. Column(db.String(100), nullable = False)
email=db.Column(db.String(100),nullable = False)
#Google Login
@app.route('/login')
def login():
authorization_url, state = flow.authorization_url()
session["state"] = state
return redirect(authorization_url)
#Call back after Google Id Verification
@app.route('/callback')
def callback():
flow.fetch_token(authorization_response=request.url)
credentials = flow.credentials
request_session = requests.session()
cached_session = cachecontrol.CacheControl(request_session)
token_request = google.auth.transport.requests.Request(session=cached_session)
id_info = id_token.verify_oauth2_token(
id_token=credentials._id_token,
request=token_request,
audience=GOOGLE_CLIENT_ID
)
session["google_id"] = id_info.get("sub")
session["name"] = id_info.get("name")
session["email"]=id_info.get("email")
if User.query.get(session["google_id"]) is None:
user = User(google_id=session["google_id"],name=session["name"],email=session["email"] )
db.session.add(user)
db.session.commit()
return redirect('/authorized_area')
#Logout
@app.route('/logout')
def logout():
session.clear()
return redirect('/')
#Authorized Page
@app.route('/authorized_area')
@login_is_required
def authorized_area():
return render_template('authorized_page.html')
#Home page
@app.route('/')
def index():
return render_template('index.html')
#Get all the topics with description
@app.route('/topics', methods = ['GET'])
def gettopics():
all_topics = []
topics = Topic.query.all()
for topic in topics:
results = {
"topic_id":topic.id,
"topic_title":topic.topic_title,
"topic_description":topic.topic_description, }
all_topics.append(results)
return render_template('topics_page.html', all_topics=all_topics)
#Create Post under a specific topic - Authorized Area
@app.route('/post', methods = ['GET','POST'])
@login_is_required
def create_post():
if request.method == 'POST':
post_data = request.form
topic_id= db.session.query(Topic).filter_by(topic_title=post_data['topic_title']).first().id
user_id=session["google_id"]
post_title = post_data['post_title']
post_description = post_data['post_description']
post = Post(topic_id=topic_id,user_id=user_id,post_title =post_title ,post_description =post_description )
db.session.add(post)
db.session.commit()
return render_template('success_page.html')
else:
return render_template('createpost_page.html')
#Get all my posts - Authorized Area
@app.route('/myposts')
@login_is_required
def get_my_posts():
all_my_posts = []
id=session["google_id"]
myposts=db.session.query(Post).filter_by(user_id=id).all()
for post in myposts:
results = {
"topic_title":db.session.query(Topic).filter_by(id=post.topic_id).first().topic_title,
"topic_id":post.topic_id,
"post_id":post.id,
"post_title":post.post_title,
"post_description":post.post_description, }
all_my_posts.append(results)
return render_template('myposts_page.html', all_posts=all_my_posts)
#Get all the posts with description under a specific topic
@app.route('/topics/<int:id>', methods = ['GET'])
def getposts_under_specific_topic(id):
topic=db.session.query(Topic).filter_by(id=id).first()
topic_title=topic.topic_title
all_posts = []
posts = db.session.query(Post).filter_by(topic_id=id).all()
for post in posts:
results = {
"post_id":post.id,
"post_title":post.post_title,
"post_description":post.post_description, }
all_posts.append(results)
return render_template('posts_page.html', all_posts=all_posts,topic_title=topic_title)
#Update the post under a specific topic - Authorized Area
@app.route('/update/<int:post_id>', methods = ['GET','PUT'])
def updatepost_under_specific_topic(post_id):
if "google_id" not in session:
return abort(401)
else:
post_to_be_update=Post.query.get(post_id)
if request.method == 'PUT':
post_title = request.json['post_title']
post_description = request.json['post_description']
post_to_be_update.post_title=post_title
post_to_be_update.post_description=post_description
db.session.commit()
return jsonify({"success": True, "response": "updated"})
else:
return render_template('updatepost_page.html',post_to_be_update=post_to_be_update)
#Delete a post under a specific topic - Authorized Area
@app.route('/delete/<post_id>')
def deletepost_under_specific_topic(post_id):
if "google_id" not in session:
return abort(401)
else:
post_to_be_delete=Post.query.get(post_id)
db.session.delete(post_to_be_delete)
db.session.commit()
return render_template('success_page.html')
if __name__=='__main__':
app.run(debug=True)