-
Notifications
You must be signed in to change notification settings - Fork 0
/
views.py
executable file
·243 lines (194 loc) · 8.29 KB
/
views.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
#!/usr/bin/python3
"""This module delivers authentication for a user"""
from datetime import date, datetime
from flask import (
render_template,
url_for,
render_template,
request,
redirect,
flash,
abort, send_from_directory
)
from flask_login import login_required, current_user
from functools import wraps
# from models.admin import Admin
from models.company import Company
from models.intern import Intern
import os
import random
from sqlalchemy import exc
import string
from typing import Callable
from web_app.views import app_views
from web_app.main_app import app, ALLOWED_EXTENSIONS
from werkzeug.utils import secure_filename
from werkzeug.exceptions import NotFound
# def permission_required(admin_permission: bool) -> Callable:
# """returns a decorator function for the route"""
# def decorator(func: Callable) -> Callable:
# """decorates a function to check admin access"""
# @wraps(func)
# def decorated_function(*args, **kwargs) -> Callable:
# """Decorated function"""
# if not current_user.is_admin(admin_permission):
# abort(403)
# return func(*args, **kwargs)
# return decorated_function
# return decorator
# def admin_required(func: Callable):
# """checks admin permission"""
# return permission_required(True)(func)
# @app_views.route("/admin", methods=['GET'])
# @login_required
# @admin_required
# def admin():
# """
# Admin route
# """
# return render_template("admin.html")
@app_views.route("/intern_profile/<intern_id>", methods=['GET'])
@login_required
def intern_profile(intern_id):
""" retrieve data for an intern profile """
from models import storage
if current_user.is_authenticated:
user = storage.get_user_by_email(current_user.email)
user_class = user.to_dict()['__class__']
return render_template("intern_profile.html", user_class=user_class)
@app_views.route("/all_companies", methods=['GET'])
def all_companies():
""" Get all the companies on the platform.
The template rendered depends on the class and if the user is
authenticated or not.
The template is rendered to allow only users with `Intern`
class to apply to companies.
`Company` class clients and users that are not authenticated can
also view companies but cannot apply.
The Company objects rendered for authenticated `interns` have their
`application_open` set to True
"""
from models import storage
try:
all_companies = storage.all(Company).values()
companies = sorted(all_companies, key=lambda k: k.name)
"""
Get the user's class if authenticated. This will be used
to redirect the user to the appropriate page
"""
if current_user.is_authenticated:
user = storage.get_user_by_email(current_user.email)
user_class = user.to_dict()['__class__']
if user_class == 'Intern':
return render_template("open_org.html",
companies=companies, user_class=user_class)
elif user_class == 'Company':
return render_template("all_companies.html",
companies=companies, user_class=user_class)
return render_template("all_companies.html", companies=companies)
except exc.SQLAlchemyError:
storage.rollback_session()
abort(400)
@app_views.route("/all_companies/open", methods=['GET'])
@login_required
def open_companies():
"""
route for all the companies whose application windows are open
"""
from models import storage
user = storage.get_user_by_email(current_user.email)
user_class = user.to_dict()['__class__']
if user_class == 'Intern':
return render_template("open_org.html",
user_class=user_class)
elif user_class == 'Company':
all_companies = storage.all(Company).values()
companies = sorted(all_companies, key=lambda k: k.name)
return render_template("all_companies.html",
companies=companies, user_class=user_class)
return render_template("open_org.html")
@app_views.route("/org_profile/<org_id>", methods=['GET', 'POST'])
@login_required
def company_profile(org_id):
""" Retrieve data for a company's profile """
from models import storage
try:
com_obj = storage.get(Company, org_id)
user_class = com_obj.to_dict()['__class__']
com_interns = sorted(com_obj.interns, key=lambda k: k.first_name)
return render_template("org_profile.html", user_class=user_class,
com_interns=com_interns)
except exc.SQLAlchemyError:
storage.rollback_session()
abort(400)
@app_views.route("/all_interns", methods=['GET'])
def all_interns():
""" Get all the companies on the platform """
from models import storage
try:
all_interns = storage.all(Intern).values()
interns = sorted(all_interns, key=lambda k: k.first_name)
if current_user.is_authenticated:
user = storage.get_user_by_email(current_user.email)
user_class = user.to_dict()['__class__']
return render_template("all_interns.html", interns=interns, user_class=user_class)
return render_template("all_interns.html", interns=interns)
except exc.SQLAlchemyError:
storage.rollback_session()
abort(400)
@app_views.route("/intern_profile/<intern_id>/", methods=['POST'])
@login_required
def upload_image(intern_id):
""" Route that handles the intern image upload """
from models import storage
try:
int_obj = storage.get(Intern, intern_id)
if request.method == 'POST':
# check if the request contains a file
if 'user_photo' not in request.files:
flash('No file in request', category='error')
return redirect(url_for('app_views.intern_profile', intern_id=current_user.id))
# check if the user selected a file
up_file = request.files.get('user_photo')
if up_file.filename == '':
flash('No file selected')
return redirect(url_for('app_views.intern_profile', intern_id=current_user.id))
if not allowed_filename(up_file.filename):
flash('Allowed files are jpg, jpeg, png', category="error")
return redirect(url_for('app_views.intern_profile', intern_id=current_user.id))
if up_file and allowed_filename(up_file.filename):
filename = secure_filename(up_file.filename)
# Generate a random string to preserve user's input
# get file extension
file_ext = os.path.splitext(filename)[1]
# generate random string file name
datetime_format = "%Y-%m-%dT%H:%M:%S"
curr_date = datetime.now().strftime(datetime_format)
gen_str = string.ascii_letters + '12345678910'
rand_str = ''.join([random.choice(gen_str)
for n in range(0, 30)])
new_filename = "{}_{}{}".format(rand_str, curr_date, file_ext)
# save the file with the new filename
file_path = os.path.join(
(app.config['UPLOAD_FOLDER']), new_filename)
up_file.save(file_path)
int_obj.image_path = new_filename
int_obj.save()
flash('Image uploaded successfully', category='success')
return redirect(url_for('app_views.intern_profile', intern_id=current_user.id))
except (exc.SQLAlchemyError, FileExistsError, FileNotFoundError):
storage.rollback_session()
abort(400)
@app_views.route("/upload/<filename>/", methods=['GET'])
@login_required
def display_image(filename):
""" Display image in user's profile """
try:
return send_from_directory(app.config["UPLOAD_FOLDER"], filename)
except NotFound:
flash('Upload Failed')
return redirect(url_for('app_views.intern_profile', intern_id=current_user.id))
def allowed_filename(filename: str) -> bool:
""" Checks if the filename is allowed """
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS