-
Notifications
You must be signed in to change notification settings - Fork 0
/
practice5.py
258 lines (233 loc) · 7.49 KB
/
practice5.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
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
256
257
from fastapi import FastAPI, HTTPException,Response,Request,Depends
import psycopg2
from pydantic import BaseModel
from passlib.context import CryptContext
import jwt
from datetime import datetime,timedelta
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
oauth_scheme = OAuth2PasswordBearer(tokenUrl="login")
def check_token(token:str = Depends(oauth_scheme)):
if not token:
raise HTTPException(status_code=404,detail="Unauthorized")
try:
decode = jwt.decode(token,"secret","HS256")
username = decode.get("sub")
except Exception as e:
raise HTTPException(status_code=500,detail="Invalid token")
return username
def create_token(username)-> str:
payload = {
"sub" : username,
"exp" : datetime.utcnow() + timedelta(minutes = 1)
}
token = jwt.encode(payload,"secret","HS256")
return token
pwd_context = CryptContext(schemes=["bcrypt"],deprecated="auto")
def db_connect():
conn = psycopg2.connect(
host = "localhost",
dbname = "postgres",
user = "postgres",
password = "ganesh",
port = 5432,
)
return conn
class Post(BaseModel):
title : str
content : str
author : str
class User(BaseModel):
username : str
email : str
password : str
@app.get("/")
def test():
return {"message" : "Test"}
#Post routes
@app.get("/all-posts", tags=["posts"])
def all_posts():
conn = db_connect()
try:
with conn.cursor() as cur:
cur.execute(
"""
SELECT id,title,content,author FROM posts
"""
)
rows = cur.fetchall()
if not rows:
raise HTTPException(status_code=404,detail="Posts not found")
posts = [
{
"id" : row[0],
"title" : row[1],
"content" : row[2],
"author" : row[3]
}
for row in rows
]
return posts
except Exception as e:
conn.rollback()
raise HTTPException(status_code=500,detail="Internal Server Error")
finally:
conn.close()
@app.post("/new-post",tags=["posts"])
def new_post(post : Post,current_user = Depends(check_token)):
conn = db_connect()
try:
with conn.cursor() as cur:
cur.execute(
"""
CREATE TABLE IF NOT EXISTS posts(
id SERIAL PRIMARY KEY,
title VARCHAR(255),
content TEXT,
author VARCHAR(255)
)
"""
)
cur.execute(
"""
INSERT INTO posts(title,content,author)
VALUES (%s,%s,%s)
RETURNING id
""",
(post.title,post.content,post.author)
)
new_id = cur.fetchone()[0]
conn.commit()
return {
"message" : "Post created",
"id" : new_id
}
except Exception as e:
conn.rollback()
raise HTTPException(status_code=500,detail="Internal Server Error")
finally:
conn.close()
@app.post("/update-post/{id}",tags=["posts"])
def update_post(updated_post : Post,id:int,current_user = Depends(check_token)):
conn = db_connect()
try:
with conn.cursor() as cur:
cur.execute(
"""
UPDATE posts
SET title = %s,content = %s,author=%s
WHERE id = %s
RETURNING id, title,content,author
""",
(updated_post.title,updated_post.content,updated_post.author,id)
)
updated_row = cur.fetchone()
if not updated_row:
raise HTTPException(status_code=404,detail="Post not found")
conn.commit()
return {
"id": updated_row[0],
"title": updated_row[1],
"author": updated_row[2],
"content": updated_row[3]
}
except Exception as e:
conn.rollback()
raise HTTPException(status_code=500,detail="Internal Server Error")
finally:
conn.close()
@app.delete("/delete-post/{id}",tags=["posts"])
def delete_post(id : int,current_user = Depends(check_token)):
conn = db_connect()
try:
with conn.cursor() as cur:
cur.execute(
"""
DELETE FROM posts
WHERE id = %s
RETURNING ID
""",
(id,)
)
deleted_id = cur.fetchone()[0]
if not deleted_id:
raise HTTPException(status_code=404,detail="Post not found")
cur.execute("SELECT COUNT(*) FROM posts")
count = cur.fetchone()[0]
if count == 0:
cur.execute("ALTER SEQUENCE posts_id_seq RESTART WITH 1")
conn.commit()
conn.commit()
return {
"message" : f"Post with id {id} removed"
}
except Exception as e:
conn.rollback()
raise HTTPException(status_code=500,detail="Internal Server Error")
finally:
conn.close()
#User routes
@app.post("/signup",tags=["users"])
def signup(user : User,response:Response):
conn = db_connect()
try:
with conn.cursor() as cur:
cur.execute(
"""
CREATE TABLE IF NOT EXISTS users(
id SERIAL PRIMARY KEY,
username VARCHAR(255) UNIQUE,
email VARCHAR(255) UNIQUE,
password VARCHAR(255)
)
"""
)
hash_password = pwd_context.hash(user.password)
cur.execute(
"""
INSERT INTO users(username,email,password)
VALUES (%s,%s,%s)
RETURNING id
""",
(user.username,user.email,hash_password)
)
conn.commit()
token = create_token(user.username)
response.set_cookie(key="token",value=f"{token}",httponly=True)
return {
"message" : "Signup successful"
}
except Exception as e:
conn.rollback()
raise HTTPException(status_code=500,detail="Internal Server Error")
finally:
conn.close()
@app.post("/login",tags=['users'])
def login(email:str,password:str,response:Response):
conn = db_connect()
try:
with conn.cursor() as cur:
cur.execute(
"""
SELECT username,email,password FROM users WHERE email = %s
""",
(email,)
)
user = cur.fetchone()
if user is None:
raise HTTPException(status_code=404, detail="User not found")
db_username,db_email,db_password = user
password_check = pwd_context.verify(password,db_password)
if not password_check:
raise HTTPException(status_code=404,detail="Wrong Password")
token = create_token(db_username)
print(token)
response.set_cookie(key="token",value=f"{token}",httponly=True)
return {
"message" : "login successful"
}
except Exception as e:
conn.rollback()
raise HTTPException(status_code=500,detail="Internal Server error")
finally:
conn.close()