Added user endpoints with swagger documentation including authorization token and appid

This commit is contained in:
Peter Yefi 2023-01-16 15:31:02 -05:00
parent ac776c4e5d
commit 31867370d8
9 changed files with 3817 additions and 92 deletions

View File

@ -6,9 +6,7 @@ Project Collaborator name peteryefi@gmail.com
"""
import flask
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from flask_apispec.extension import FlaskApiSpec
import yaml
from flask_restful import Api
from hub_api.city_info import CityInfo, City
from hub_api.geometry import Geometry
@ -31,11 +29,33 @@ from hub_api.session import SessionStart, SessionEnd, KeepSessionAlive
from hub_api.uptime import Uptime
from hub_api.greenery import Greenery
from hub_api.user import User, UserLogin
from flasgger import LazyJSONEncoder, LazyString, Swagger
app = flask.Flask('gamification')
app.json_encoder = LazyJSONEncoder
api = Api(app)
with open("hub_api/docs/openapi-specs.yml", "r") as stream:
swagger_config = {
"headers": [],
"specs": [
{
"endpoint": 'apispec',
"route": '/apispec.json',
"rule_filter": lambda rule: True, # all in
"model_filter": lambda tag: True, # all in
}
],
"static_url_path": "/flasgger_static",
"specs_route": "/api-docs/",
"openapi": "3.0.0"
}
try:
Swagger(app, template=yaml.safe_load(stream), config=swagger_config)
except yaml.YAMLError as exc:
print(exc)
api.add_resource(Uptime, '/v1.4/uptime')
api.add_resource(Geometry, '/v1.4/geometry')
api.add_resource(GreeneryCatalogEntry, '/v1.4/greenery-catalog/entry')
@ -62,20 +82,3 @@ api.add_resource(KeepSessionAlive, '/v1.4/session/keep_alive')
api.add_resource(CityInfo, '/v1.4/city_info')
api.add_resource(City, '/v1.4/city')
api.add_resource(Greenery, '/v1.4/greenery')
# Add api documentation
app.config.update({
'APISPEC_SPEC': APISpec(
title='Gamification Service',
version='v1.4',
plugins=[MarshmallowPlugin()],
openapi_version='2.0.0'
),
'APISPEC_SWAGGER_URL': '/swagger/', # URI to access API Doc JSON
'APISPEC_SWAGGER_UI_URL': '/api-docs/' # URI to access UI of API Doc
})
docs = FlaskApiSpec(app)
docs.register(HeatPump)
docs.register(User)
docs.register(UserLogin)
docs.register(City)

File diff suppressed because it is too large Load Diff

View File

@ -11,7 +11,7 @@ from catalog_factories.usage_catalog_factory import UsageCatalogFactory
from imports.construction_factory import ConstructionFactory
from imports.geometry_factory import GeometryFactory
from imports.life_cycle_assessment_factory import LifeCycleAssessment
from imports.schedules_factory import SchedulesFactory
# from imports.schedules_factory import SchedulesFactory
from imports.usage_factory import UsageFactory
from imports.weather_factory import WeatherFactory
from flask import Response
@ -39,7 +39,7 @@ for building in city.buildings:
ConstructionFactory('nrel', city).enrich()
UsageFactory('comnet', city).enrich()
SchedulesFactory('comnet', city).enrich()
# SchedulesFactory('comnet', city).enrich()
LifeCycleAssessment('material', city).enrich()
LifeCycleAssessment('machine', city).enrich()
LifeCycleAssessment('fuel', city).enrich()

View File

@ -5,14 +5,18 @@ Copyright © 2022 Project Author name guillermo.gutierrezmorote@concordia.ca
"""
import json
from flask_apispec import use_kwargs, doc
from flask import Response, request
from flask import Response, request, g
from flask_restful import Resource
from hub_api.helpers.session_helper import refresh_session
from marshmallow import fields, Schema
from hub_api.helpers.auth import role_required
from persistence.models import UserRoles
from flask_apispec.views import MethodResource
from hub_logger import logger
from flasgger import swag_from
from imports.geometry_factory import GeometryFactory
from pathlib import Path
from imports.db_factory import DBFactory
import os
class AuthorizationHeader(Schema):
@ -85,14 +89,46 @@ class CityInfo(Resource):
return Response(json.dumps(response), headers=headers)
class City(MethodResource, Resource):
@doc(description='Persist a city', tags=['PersistCity'])
@role_required(UserRoles.Admin.value)
@use_kwargs(AuthorizationHeader, location='headers')
@use_kwargs(CitySchema)
def post(self, **kwargs):
class City(Resource):
def __init__(self):
pass
#@role_required([UserRoles.Admin.value])
@swag_from("docs/openapi-specs.yml", methods=['POST'])
def post(self):
allowed_ext = {'gml', '3dm', 'xml', 'obj', 'rhino'}
try:
return Response(response=json.dumps({'msg': 'Hello'}), status=201)
city_file = request.files['city_file']
ext = city_file.filename.rsplit('.', 1)[1].lower()
if ext in allowed_ext:
city_file_type = ext
if ext == 'gml':
city_file_type = 'citygml'
elif ext == '3dm':
city_file_type = 'rhino'
file_path = (Path(__file__).parent.parent / 'data/uploaded_city/{}'.format(city_file.filename)).resolve()
city_file.save(file_path)
city = GeometryFactory(city_file_type, file_path).city
db_factory = DBFactory(city=city, db_name='hub_prod', app_env='PROD',
dotenv_path="{}/.env".format(os.path.expanduser('~')))
saved_city = db_factory.persist_city(1)
if os.path.exists(file_path):
os.remove(file_path)
if type(saved_city) is not dict:
return Response(response=json.dumps({
'id': saved_city.id, 'name': saved_city.name, 'srs_name': saved_city.srs_name,
'time_zone': saved_city.time_zone, 'version': saved_city.city_version, 'country': saved_city.country_code,
'lat': saved_city.latitude, 'lon': saved_city.longitude, 'lower_corner': saved_city.lower_corner,
'upper_corner': saved_city.upper_corner, 'created': saved_city.created, 'updated': saved_city.updated,
'user': {'id': saved_city.user.id, 'name': saved_city.user.name, 'email': saved_city.user.email,
'role': saved_city.user.role.value}
}, default=str), status=201)
return Response(response=json.dumps(saved_city), status=200)
else:
return Response(response=json.dumps({'err_msg': 'Unknown city file type'}), status=400)
except Exception as err:
logger.error(err)
return Response(response=json.dumps({'err_msg': 'Sorry an error occurred while creating user'}), status=400)
return Response(response=json.dumps({'err_msg': 'Sorry an error occurred while creating city'}), status=400)

View File

@ -0,0 +1,340 @@
info:
title: Gamification Swagger - OpenAPI 3.0
description: NextGen Cities Institute Gamification API
termsOfService: http://swagger.io/terms/
contact:
email: peteryefi@gmail.com
version: 1.4
externalDocs:
description: Find out more about Swagger
url: http://swagger.io
paths:
/v1.4/city:
post:
tags:
- city
summary: Create a city
operationId: createCity
description: Create a new city with a file upoload
parameters:
- in: header
name: appId
schema:
type: string
required: true
description: the Id of the application access this API
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
city_file:
type: string
format: binary
required: true
responses:
'201':
description: City created successfully
content:
application/json:
schema:
$ref: '#/components/schemas/City'
'200':
description: City not created
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
'400':
description: Bad Request
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
'404':
description: City not found
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
'403':
description: Forbidden
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
'401':
description: Unauthorized
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
security:
- BearerAuth: []
/v1.4/user:
post:
tags:
- user
summary: Create user
description: This can only be done by the logged in admin.
operationId: createUser
parameters:
- in: header
name: appId
schema:
type: string
required: true
description: the Id of the application access this API
requestBody:
description: Created user object
content:
application/json:
schema:
$ref: '#/components/schemas/User'
application/xml:
schema:
$ref: '#/components/schemas/User'
responses:
'201':
description: User created successfully
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
description: Bad Request
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
'403':
description: Forbidden
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
'401':
description: Unauthorized
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
security:
- BearerAuth: [ ]
put:
tags:
- user
summary: Update user
description: This can only be done by the logged in admin.
operationId: updateUser
requestBody:
description: Update user object
content:
application/json:
schema:
$ref: '#/components/schemas/User'
application/xml:
schema:
$ref: '#/components/schemas/User'
responses:
'201':
description: User updated successfully
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
description: Bad Request
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
'403':
description: Forbidden
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
'401':
description: Unauthorized
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
security:
- BearerAuth: [ ]
/v1.4/user/login:
post:
tags:
- user
summary: Logs user into the system
description: ''
operationId: loginUser
parameters:
- in: header
name: appId
schema:
type: string
required: true
description: the Id of the application access this API
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/Login'
required: true
responses:
'200':
description: Login successful
content:
application/json:
schema:
$ref: '#/components/schemas/LoginRes'
'400':
description: Invalid username/password supplied
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
components:
schemas:
City:
type: object
properties:
id:
type: integer
format: int64
example: 10
name:
type: string
example: Montreal
srs_name:
type: string
example: EPSG:26918
country:
type: string
example: ca
lon:
type: float
example: 0.38292983
lat:
type: float
example: 0.92898883
time_zone:
type: string
example: utc
city_version:
type: integer
format: int64
example: 1
lower_corner:
type: array
items:
type: float
example: [610610.7547462888,5035770.347264212,566.5784301757819]
upper_corner:
type: array
items:
type: float
example: [610610.7547462888,5035770.347264212,566.5784301757819]
user:
type: object
$ref: '#/components/schemas/User'
created:
type: string
example: 2023-01-15 18:40:54.64877
updated:
type: string
example: 2023-01-15 18:40:54.64877
User:
type: object
properties:
id:
type: integer
format: int64
example: 10
name:
type: string
example: Peter Yefi
email:
type: string
example: peteryefi@gmail.com
password:
type: string
example: 'Hub@183838'
role:
type: string
enum:
- Admin
- Hub_Reader
Login:
type: object
properties:
email:
type: string
example: peteryefi@gmail.com
password:
type: string
example: 'Hub@183838'
LoginRes:
type: object
properties:
token:
type: string
example: eylskdkdjfkdj67uhbnmkhbn908uyhndh
user:
type: object
$ref: '#/components/schemas/User'
ApiResponse:
type: object
properties:
code:
type: integer
format: int32
message:
type: string
requestBodies:
User:
description: Pet object that needs to be added to the store
content:
application/json:
schema:
$ref: '#/components/schemas/User'
application/xml:
schema:
$ref: '#/components/schemas/User'
UserArray:
description: List of user object
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT

View File

@ -10,10 +10,11 @@ from flask_apispec import use_kwargs, doc
from flask_apispec.views import MethodResource
from flask_restful import Resource
from marshmallow import Schema, fields
from hub_api.helpers.auth import role_required
from hub_api.helpers.session_helper import refresh_session
from utils import HeatPumpSimulator
from utils import validate_hp_model
from persistence.models import UserRoles
class HeatPumpPostData(Schema):
@ -47,6 +48,7 @@ class HeatPump(MethodResource, Resource):
@doc(description='Heat pump simulation run', tags=['HeatPump'])
@use_kwargs(HeatPumpPostData)
@role_required([UserRoles.Admin.value, UserRoles.Hub_Reader.value])
def post(self, **kwargs):
session = refresh_session(request)
if session is None:

View File

@ -28,10 +28,13 @@ def validate_auth_token(token: str):
return instance.decode(token, verifying_key, do_time_check=True)
def role_required(role: str):
def role_required(roles: [str]):
def auth_module(user):
g.user = user
return user['role'] == role
for role in roles:
if role == user['role']:
return True
return False
"""
A wrapper to authorize specific roles for specific endpoints
@ -43,7 +46,7 @@ def role_required(role: str):
@wraps(f)
def wrapper(*args, **kwargs):
try:
token = request.headers['Authorization']
token = request.headers['Authorization'].split()[1]
user = validate_auth_token(token)
if user is None:

View File

@ -4,11 +4,8 @@ SPDX - License - Identifier: LGPL - 3.0 - or -later
Copyright © 2022 Project Author Peter Yefi peteryefi@gmail.com
"""
import json
from flask import Response
from flask_apispec import use_kwargs, doc
from flask_apispec.views import MethodResource
from flask import Response, request
from flask_restful import Resource
from marshmallow import Schema, fields
from imports.user_factory import UserFactory
from exports.user_factory import UserFactory as ExUserFactory
import os
@ -17,48 +14,17 @@ from hub_api.helpers.auth import generate_auth_token, role_required
from persistence.models import UserRoles
class AuthorizationHeader(Schema):
Authorization = fields.Str(required=True, description='Authorization token')
AppID = fields.Str(required=True, description='ID of app accessing API')
class LoginPostSchema(Schema):
"""
Defines post data for users
"""
password = fields.String(required=True, description='Password of user')
email = fields.String(required=True, description='Email of user')
class UserPostSchema(LoginPostSchema):
"""
Defines post data for users
"""
name = fields.String(required=True, description='Name of user')
role = fields.String(required=True, description='Allowed user roles', enum=['Admin', 'Hub_Reader'])
class UserPutSchema(UserPostSchema):
"""
Defines put data for users
"""
id = fields.Int(required=True, description='The Id of the user to be Updated')
class User(MethodResource, Resource):
class User(Resource):
def __init__(self):
self.user_factory = UserFactory(db_name='hub_prod', app_env='PROD',
dotenv_path="{}/.env".format(os.path.expanduser('~')))
@doc(description='Create users', tags=['CreateUser'])
@role_required(UserRoles.Admin.value)
@use_kwargs(AuthorizationHeader, location='headers')
@use_kwargs(UserPostSchema)
def post(self, **kwargs):
@role_required([UserRoles.Admin.value])
def post(self):
try:
user = self.user_factory.create_user(name=kwargs["name"], email=kwargs["email"], password=kwargs["password"],
role=kwargs["role"])
payload = request.get_json()
user = self.user_factory.create_user(name=payload["name"], email=payload["email"], password=payload["password"],
role=payload["role"])
if type(user) is dict:
return Response(response=json.dumps(user), status=400)
return Response(response=json.dumps({'user': {'id': user.id, 'name': user.name, 'email': user.email,
@ -67,14 +33,12 @@ class User(MethodResource, Resource):
logger.error(err)
return Response(response=json.dumps({'err_msg': 'Sorry an error occurred while creating user'}), status=400)
@doc(description='Get all users', tags=['UpdateUsers'])
@use_kwargs(UserPutSchema)
@role_required(UserRoles.Admin.value)
@use_kwargs(AuthorizationHeader, location='headers')
def put(self, **kwargs):
@role_required([UserRoles.Admin.value])
def put(self):
try:
res = self.user_factory.update_user(user_id=kwargs['id'], name=kwargs['name'], password=kwargs['password'],
role=kwargs['role'], email=kwargs['email'])
payload = request.get_json()
res = self.user_factory.update_user(user_id=payload['id'], name=payload['name'], password=payload['password'],
role=payload['role'], email=payload['email'])
if res:
return Response(response=json.dumps(res), status=400)
return Response(response=json.dumps({'success': 'user updated successfully'}), status=200)
@ -84,16 +48,15 @@ class User(MethodResource, Resource):
status=400)
class UserLogin(MethodResource, Resource):
class UserLogin(Resource):
def __init__(self):
self.user_factory = ExUserFactory(db_name='hub_prod', app_env='PROD',
dotenv_path="{}/.env".format(os.path.expanduser('~')))
@doc(description='Create users', tags=['LoginUser'])
@use_kwargs(LoginPostSchema)
def post(self, **kwargs):
def post(self):
try:
user = self.user_factory.login_user(email=kwargs["email"], password=kwargs["password"])
payload = request.get_json()
user = self.user_factory.login_user(email=payload["email"], password=payload["password"])
if type(user) is dict:
return Response(response=json.dumps(user), status=400)
user = user[0]
@ -107,7 +70,7 @@ class UserLogin(MethodResource, Resource):
}
}
user_dict['token'] = generate_auth_token(user_dict)
return Response(response=json.dumps(user_dict), status=201)
return Response(response=json.dumps(user_dict), status=200)
except Exception as err:
logger.error(err)
return Response(response=json.dumps({'err_msg': 'Sorry an error occurred while authenticating user'}), status=400)
return Response(response=json.dumps({'err_msg': 'An error occurred while authenticating user'}), status=400)

View File

@ -21,4 +21,5 @@ rhino3dm==7.7.0
scipy
PyYAML
pyecore==0.12.2
jwt==1.3.1
jwt==1.3.1
flagger==3.1.0