Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #832 : Adds JSON-API standards #847

Merged
merged 1 commit into from May 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 8 additions & 1 deletion backend/blueprint/api/controllers/fileUploader.py
Expand Up @@ -4,13 +4,13 @@
from api.helpers.uploads import saveToImage, saveToCSV, saveAsCSV
from api.models.file import File
from api.models.user import User
from api.schemas.file import FileSchema


router = Blueprint('fileUploader', __name__)


@router.route('/image', methods=['POST'])
@loginRequired
def uploadImage():
try:
image = request.json['data']
Expand Down Expand Up @@ -108,3 +108,10 @@ def upload_manual_data():
Response(200).generateMessage({
'message': 'Manual Data uploaded successfully',
'unique_id': csvName}))


@router.route('/get_file', methods=['GET'])
def get_file():
input_data = request.args
file = File().query.filter_by(filename=input_data.get('filename')).first()
return jsonify(FileSchema().dump(file).data)
9 changes: 9 additions & 0 deletions backend/blueprint/api/controllers/loginUser.py
Expand Up @@ -6,6 +6,7 @@
from api.utils.response import Response
from api.helpers.verifyPassword import verifyPassword
from api.models.user import User
from api.schemas.user import UserSchema


router = Blueprint('loginUser', __name__)
Expand Down Expand Up @@ -45,3 +46,11 @@ def login():
return jsonify(
Response(403).generateMessage(
'No name key received'))


@router.route('/get_user', methods=['GET'])
def index():
data = request.args
user = User.getUser(username=data.get('username'))
schema = UserSchema()
return jsonify(schema.dump(user).data)
30 changes: 10 additions & 20 deletions backend/blueprint/api/controllers/registerUser.py
@@ -1,21 +1,19 @@
from flask import Blueprint, jsonify, request
from firebase_admin import auth
from api.utils.response import Response
from api.models.user import User
from api.schemas.user import UserSchema


router = Blueprint('registerUser', __name__)


@router.route('/register', methods=['POST'])
def registerUser():
try:
data = request.get_json()
except Exception as e:
return jsonify(
Response(500).exceptWithMessage(
str(e),
'Unable to get json'))

def register_user():
schema = UserSchema()
input_data = request.get_json()
data, err = schema.load(input_data)
if err:
return err
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gabru-md This will return an error to the console, but what will the user see? Please make use Response class and return proper error to the user endpoint

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will iterate over this PR.
So incase you are worried about the error stuff, this is just a basic implementation.
Since it works and @yashLadha said it is important, therefore I have given a basic setup so that the frontend can be linked.

If you have any other questions I would suggest waiting for a day or two, so that I can work with @ParthS007 and @yashLadha.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vaibhavsingh97 #848 can you refer to the comments there, cheers 👍

user = auth.create_user(
email=data['email'],
email_verified=False,
Expand All @@ -29,14 +27,6 @@ def registerUser():
email=user.email,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why email is mentioned twice in auth.create_user?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, but what ?

Copy link
Member Author

@gabru-md gabru-md May 25, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a user for backend and a user for firebase.
I guess you should look more closely 😕

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gabru-md ignore this comment, I have seen something wrong 😅

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One of many

password=data['password'])

try:
newUser.save_to_db()
except Exception as e:
return jsonify(
Response(401).exceptWithMessage(
str(e),
'User already exists with the same Username'))
newUser.save_to_db()

return jsonify(
Response(200).generateMessage(
'User created successfully'))
return jsonify(schema.dump(newUser))
6 changes: 3 additions & 3 deletions backend/blueprint/api/models/file.py
@@ -1,21 +1,21 @@
from api.db import db
import uuid


class File(db.Model):
__tablename__ = 'File'

id = db.Column(db.String(100))
filename = db.Column(db.String(100), nullable=False, primary_key=True)
filetype = db.Column(db.String(100), nullable=False)
user_id = db.Column(db.String(100), db.ForeignKey('User.id', ondelete='CASCADE'))

def save_to_db(self):
self.id = str(uuid.uuid4())
db.session.add(self)
try:
db.session.commit()
except Exception as e:
db.session.rollback()
db.session.flush()
print(e)

def __repr__(self):
return '<File: {}>'.format(self.name)
4 changes: 2 additions & 2 deletions backend/blueprint/api/models/user.py
Expand Up @@ -6,8 +6,8 @@
class User(db.Model):
__tablename__ = 'User'

id = db.Column(db.String(100), primary_key=True)
username = db.Column(db.String(80))
id = db.Column(db.String(100))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why removed primary_key=True?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

user must be recognised by the username and not the id.
Rest is self explanatory.
😄

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gabru-md Agreed, but why id is not an primary key, so every id genrated against user must be unique. I guess, I am confused, so can you present some more information supporting the same

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess you are not reading the implementation of the code before creating comments.
I already stated that the answer is self explanatory, but it seems that you cannot understand so I will write here.
The id will be unique no matter what. The id being passed onto the user object is the uid generated by firebase, and which in itself is unique.
I guess you know about removing resundancy, sincr we already have a unique id taken care by firebase, then there is no need to mention it here.

I expect this much explanation is sufficient. 😄

username = db.Column(db.String(80), primary_key=True)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

one can add unique=True

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

both are different.
primary_key will be used here.
cheers!

password = db.Column(db.String(100))
email = db.Column(db.String(100))
files = db.relationship('File', backref='uploader')
Expand Down
2 changes: 2 additions & 0 deletions backend/blueprint/api/run.py
Expand Up @@ -13,8 +13,10 @@
oauthToken
)


app = create_app()


db.init_app(app)
migrate = Migrate(app, db)

Expand Down
Empty file.
21 changes: 21 additions & 0 deletions backend/blueprint/api/schemas/file.py
@@ -0,0 +1,21 @@
from marshmallow_jsonapi.flask import Schema
from marshmallow_jsonapi import fields


class FileSchema(Schema):
class Meta:
type_ = 'File'
self_view = 'fileUploader.get_file'
kwargs = {'id': '<id>'}

id = fields.Str(required=True, dump_only=True)
filename = fields.Str(required=True)
filetype = fields.Str(required=True)
user_id = fields.Relationship(
self_url='/api/upload/get_file',
self_url_kwargs={'file_id': '<id>'},
related_url='/user/register',
related_url_kwargs={'id': '<id>'},
include_resource_linkage=True,
type_='User'
)
15 changes: 15 additions & 0 deletions backend/blueprint/api/schemas/user.py
@@ -0,0 +1,15 @@
from marshmallow_jsonapi.flask import Schema
from marshmallow_jsonapi import fields


class UserSchema(Schema):
class Meta:
type_ = 'Users'
self_view = 'loginUser.login'
kwargs = {'id': '<id>'}

id = fields.Str(required=True, dump_only=True)
username = fields.Str(required=True)
email = fields.Str(required=True)
password = fields.Str(required=True, load_only=True)
name = fields.Str(required=True)
6 changes: 3 additions & 3 deletions backend/blueprint/api/utils/response.py
Expand Up @@ -22,12 +22,12 @@ def generateURL(self, url, message):

def sanitizeURL(self):
self.URL = self.URL.replace('backend/app/', urlConfig.BASE_URL)
return self.serialize()
return {'data': self.serialize()}

def generateResetURL(self, token):
self.token = token
self.URL = urlConfig.BASE_FRONTEND_URL + "reset/password/" + self.token
return self.serialize()
return {'data': self.serialize()}

def generateToken(self, token):
self.token = token
Expand All @@ -36,7 +36,7 @@ def generateToken(self, token):
def exceptWithMessage(self, exception, message):
self.message = message
self.exception = exception
return self.serialize()
return {'data': self.serialize()}

def serialize(self):
return self.__dict__