Merge branch 'API_Dev'

This commit is contained in:
Sagi Dayan 2015-06-28 21:14:44 +03:00
commit 83627788bd
11 changed files with 804 additions and 277 deletions

View file

@ -30,6 +30,7 @@ from SE_API.CampusRoutes import campus_routes
from SE_API.CourseRoutes import course_routes from SE_API.CourseRoutes import course_routes
from SE_API.ProjectRoutes import project_routes from SE_API.ProjectRoutes import project_routes
from SE_API.TaskRoutes import task_routes from SE_API.TaskRoutes import task_routes
from SE_API.MessageRoutes import message_routes
@ -51,6 +52,7 @@ app.register_blueprint(campus_routes)
app.register_blueprint(course_routes) app.register_blueprint(course_routes)
app.register_blueprint(project_routes) app.register_blueprint(project_routes)
app.register_blueprint(task_routes) app.register_blueprint(task_routes)
app.register_blueprint(message_routes)
auto = Autodoc(app) auto = Autodoc(app)

View file

@ -76,9 +76,10 @@ def create_campus(token):
print e print e
user = get_user_by_token(token) user = get_user_by_token(token)
arr = []
arr.append(str(user.key().id()))
try: try:
campus = Campus(title=payload['title'], email_ending=payload['email_ending'], master_user_id=user.key().id(), avatar_url=payload['avatar_url']) campus = Campus(title=payload['title'], email_ending=payload['email_ending'], master_user_id=user.key().id(), avatar_url=payload['avatar_url'], membersId=arr)
except Exception: except Exception:
return bad_request() return bad_request()
@ -94,6 +95,53 @@ def create_campus(token):
# PUT # PUT
#---------------------------------------------------------- #----------------------------------------------------------
@campus_routes.route('/api/campuses/joinCampus/<string:token>/<string:campusId>', methods=["PUT"])
@auto.doc()
def joinCampus(token, campusId):
"""
<span class="card-title">This call will add the user (by token) to a specific campus</span>
<br>
<b>Route Parameters</b><br>
- seToken: 'seToken'<br>
- campusId: 123456789
<br>
<br>
<b>Payload</b><br>
- None <br>
<br>
<b>Response</b>
<br>
202 - Accepted
<br>
400 - Bad Request
<br>
403 - Invalid token or not a lecturer
"""
user = get_user_by_token(token)
if user is None:
return bad_request("Wrong user Token")
campus = Campus.get_by_id(int(campusId))
if campus is None:
return bad_request("No such course")
if user.key().id() in campus.membersId:
return no_content("User is already member in Project")
campus.membersId.append(str(user.key().id()))
user.courses_id_list.append(str(campus.key().id()))
db.put(campus)
db.put(user)
db.save
return Response(response=campus.to_JSON(),
status=202,
mimetype="application/json")
#---------------------------------------------------------- #----------------------------------------------------------
# GET # GET
#---------------------------------------------------------- #----------------------------------------------------------

View file

@ -49,7 +49,7 @@ def create_course(token):
- JSON Object, Example: <br> - JSON Object, Example: <br>
{<br> {<br>
'courseName': 'Advance Math',<br> 'courseName': 'Advance Math',<br>
'campusName': 'JCE',<br> 'campusId': 1234567890,<br>
'startDate': {'year': 2015, 'month' : 4, 'day' : 3},<br> 'startDate': {'year': 2015, 'month' : 4, 'day' : 3},<br>
'endDate': {'year': 2016, 'month' : 5, 'day' : 14}<br> 'endDate': {'year': 2016, 'month' : 5, 'day' : 14}<br>
}<br> }<br>
@ -83,11 +83,12 @@ def create_course(token):
if end_date <= start_date: if end_date <= start_date:
return bad_request("end date cant be before (or same day) start date") return bad_request("end date cant be before (or same day) start date")
course = Course(courseName=payload['courseName'], campusName=payload['campusName'], master_id=user.key().id(), course = Course(courseName=payload['courseName'], campusId=payload['campusId'], master_id=user.key().id(),
startDate=start_date, endDate=end_date) startDate=start_date, endDate=end_date)
#check if name already exists #check if name already exists
try: try:
query = Course.all() query = Course.all()
query.filter('campusId = ', payload['campusId'])
query.filter("courseName = ", payload['courseName']) query.filter("courseName = ", payload['courseName'])
for c in query.run(limit=1): for c in query.run(limit=1):
return forbidden("Course with same name already exists") return forbidden("Course with same name already exists")
@ -113,64 +114,6 @@ def create_course(token):
mimetype="application/json") mimetype="application/json")
@course_routes.route('/api/courses/createMessage/<string:token>', methods=['POST'])
@auto.doc()
def createMessage(token):
"""
<span class="card-title">This call will create a new Message in the DB</span>
<br>
<b>Route Parameters</b><br>
- seToken: 'seToken'
<br>
<br>
<b>Payload</b><br>
- JSON Object, Example: <br>
{<br>
'courseName': 'Advance Math',<br>
'message': 'The lecture today is canceled'<br>
}<br>
<br>
<br>
<b>Response</b>
<br>
201 - Created
<br>
400 - Bad Request
<br>
403 - Invalid token or not a lecturer
"""
if not request.data:
return bad_request("no data")
if not is_lecturer(token): #todo: change to lecturer id
return forbidden("Invalid token or not a lecturer!")
user = get_user_by_token(token)
#try to parse payload
try:
payload = json.loads(request.data)
except Exception as e:
return bad_request("here")
try:
msg = Message(groupId=payload['groupId'], message=payload['message'], msgDate=datetime.datetime.now(), master_id=user.key().id())
except Exception as e:
print e
return bad_request("there")
try:
msg['isProject'] = payload['isProject']
except Exception as e:
pass
db.save(msg)
db.save
return created()
#---------------------------------------------------------- #----------------------------------------------------------
# PUT # PUT
#---------------------------------------------------------- #----------------------------------------------------------
@ -226,14 +169,14 @@ def joinCourse(token, courseId):
#---------------------------------------------------------- #----------------------------------------------------------
@course_routes.route('/api/courses/getCourseByCampusName/<string:name>', methods=["GET"]) @course_routes.route('/api/courses/getCoursesByCampus/<string:campusId>', methods=["GET"])
@auto.doc() @auto.doc()
def getCourseByCampusName(name): def getCourseByCampus(campusId):
""" """
<span class="card-title">>This Call will return an array of all courses in a given campus</span> <span class="card-title">>This Call will return an array of all courses in a given campus</span>
<br> <br>
<b>Route Parameters</b><br> <b>Route Parameters</b><br>
- name: 'campus name' - campusId: 1234567890
<br> <br>
<br> <br>
<b>Payload</b><br> <b>Payload</b><br>
@ -246,7 +189,7 @@ def getCourseByCampusName(name):
<code> <code>
{<br> {<br>
'courseName': 'Advance Math',<br> 'courseName': 'Advance Math',<br>
'campusName': 'JCE',<br> 'campusId': 1234567890,<br>
'startDate': '2015-14-3'<br> 'startDate': '2015-14-3'<br>
'endDate': '2015-29-6'<br> 'endDate': '2015-29-6'<br>
'taskFlag': 'False'<br> 'taskFlag': 'False'<br>
@ -258,7 +201,7 @@ def getCourseByCampusName(name):
""" """
arr = [] arr = []
query = Course.all() query = Course.all()
query.filter("campusName=", name) query.filter("campusId = ", int(campusId))
for c in query.run(): for c in query.run():
arr.append(dict(json.loads(c.to_JSON()))) arr.append(dict(json.loads(c.to_JSON())))
@ -319,7 +262,7 @@ def getCampusesByUser(token,campusId):
arr = [] arr = []
for i in user.courses_id_list: for i in user.courses_id_list:
course = Course.get_by_id(int(i)) course = Course.get_by_id(int(i))
if course.courseName == campus.title: if course.campusId == campus.key().id():
arr.append(dict(json.loads(course.to_JSON()))) arr.append(dict(json.loads(course.to_JSON())))
if len(arr) != 0: if len(arr) != 0:
@ -332,61 +275,6 @@ def getCampusesByUser(token,campusId):
mimetype="application/json") mimetype="application/json")
@course_routes.route('/api/courses/getMessagesByCourseName/<string:name>', methods=["GET"])
@auto.doc()
def getMessagesByCourseName(name):
"""
<span class="card-title">>This Call will return an array of all courses in a given campus</span>
<br>
<b>Route Parameters</b><br>
- name: 'campus name'
<br>
<br>
<b>Payload</b><br>
- NONE
<br>
<br>
<b>Response</b>
<br>
200 - JSON Example:<br>
<code>
{<br>
'courseName': 'Advance Math',<br>
'campusName': 'JCE',<br>
'startDate': '2015-14-3'<br>
'endDate': '2015-29-6'<br>
'taskFlag': false,<br>
'id' : 1234567890<br>
}
</code>
<br>
"""
arr = []
query = Message.all()
query.filter("courseName = ", name)
for m in query.run():
msgDic = dict(json.loads(m.to_JSON()))
#add a key 'forSortDate' for sorting dates
msgTime = datetime.datetime(msgDic['date']['year'], msgDic['date']['month'], msgDic['date']['day'], msgDic['date']['hour'], msgDic['date']['minute'])
msgDic['forSortDate'] = msgTime
arr.append(msgDic)
arr = sorted(arr, key=itemgetter('forSortDate'), reverse=False)
for i in arr:
del i['forSortDate']
print arr
if len(arr) != 0:
return Response(response=json.dumps(arr),
status=200,
mimetype="application/json")
else:
return Response(response=[],
status=200,
mimetype="application/json")
#---------------------------------------------------------- #----------------------------------------------------------
# PUT # PUT
#---------------------------------------------------------- #----------------------------------------------------------
@ -448,64 +336,64 @@ def deleteCourse(token,courseid):
return forbidden("lecturer is not owner of course") return forbidden("lecturer is not owner of course")
@course_routes.route('/api/courses/deleteCoursesByCampus/<string:token>/<string:campusName>', methods=['DELETE']) # @course_routes.route('/api/courses/deleteCoursesByCampus/<string:token>/<string:campusid>', methods=['DELETE'])
@auto.doc() # @auto.doc()
def deleteCoursesByCampus(token,campusName): # def deleteCoursesByCampus(token,campusName):
""" # """
<span class="card-title">This Call will delete a specific campus's courses</span> # <span class="card-title">This Call will delete a specific campus's courses</span>
<br> # <br>
<b>Route Parameters</b><br> # <b>Route Parameters</b><br>
- seToken: 'seToken' # - seToken: 'seToken'
- title: 'campusName' # - title: 'campusName'
<br> # <br>
<br> # <br>
<b>Payload</b><br> # <b>Payload</b><br>
- NONE <br> # - NONE <br>
<br> # <br>
<br> # <br>
<b>Response</b> # <b>Response</b>
<br> # <br>
202 - Deleted campus # 202 - Deleted campus
<br> # <br>
204 - No Matching Campus Found # 204 - No Matching Campus Found
<br> # <br>
....<br> # ....<br>
{<br> # {<br>
...<br> # ...<br>
}req<br> # }req<br>
#
]<br> # ]<br>
400 - Bad Request # 400 - Bad Request
<br> # <br>
403 - Invalid token or not a lecturer!<br> # 403 - Invalid token or not a lecturer!<br>
""" # """
#
if not is_lecturer(token): #todo: change to lecturer id # if not is_lecturer(token): #todo: change to lecturer id
return forbidden("Invalid token or not a lecturer!") # return forbidden("Invalid token or not a lecturer!")
#
#
user = get_user_by_token(token) # user = get_user_by_token(token)
campus = get_campus_by_campusName(campusName) # campus = get_campus_by_campusName(campusName)
if campus is None: # if campus is None:
return bad_request("Not a campus!") # return bad_request("Not a campus!")
#
#check user is owner of campus # #check user is owner of campus
if campus.master_user_id != user.key().id(): # if campus.master_user_id != user.key().id():
return forbidden("lecturer is not owner of campus!") # return forbidden("lecturer is not owner of campus!")
#
query = Course.all() # query = Course.all()
#
try: # try:
query.filter('campusName =', campusName) # query.filter('campusName =', campusName)
except Exception as e: # except Exception as e:
print e # print e
return bad_request("invalid course title attribute") # return bad_request("invalid course title attribute")
#
for c in query.run(): # for c in query.run():
db.delete(c) # db.delete(c)
db.save # db.save
#
return no_content() # return no_content()

246
SE_API/MessageRoutes.py Normal file
View file

@ -0,0 +1,246 @@
__author__ = 'Aran'
from flask import Blueprint
import json
from GithubAPI.GithubAPI import GitHubAPI_Keys
from google.appengine.ext import db
import requests
import datetime
from operator import itemgetter
from flask import Flask, request, render_template, redirect, abort, Response
from flask.ext.github import GitHub
from flask.ext.cors import CORS, cross_origin
from flask.ext.autodoc import Autodoc
# DB Models
from models.Course import Course
from models.Project import Project
from models.Message import Message
#Validation Utils Libs
from SE_API.Validation_Utils import *
from SE_API.Respones_Utils import *
message_routes = Blueprint("message_routes", __name__)
auto = Autodoc()
#----------------------------------------------------------
# POST
#----------------------------------------------------------
@message_routes.route('/api/messages/create/<string:token>', methods=['POST'])
@auto.doc()
def createMessage(token):
"""
<span class="card-title">This call will create a new Message in the DB</span>
<br>
<b>Route Parameters</b><br>
- seToken: 'seToken'
<br>
<br>
<b>Payload</b><br>
- JSON Object, Example: <br>
{<br>
'groupId' : 123456789,<br>
'message' : 'Class is canceled',<br>
'date' : {<br>
'year': 2015,<br>
'month': 3,<br>
'day': 14,<br>
'hour': 16,<br>
'minute': 53<br>
},<br>
'isProject' : true<br>
}<br>
<br>
<br>
<b>Response</b>
<br>
201 - Created
<br>
400 - Bad Request
<br>
403 - Invalid token or not a lecturer
"""
if not request.data:
return bad_request("no data")
if not is_lecturer(token): #todo: change to lecturer id
return forbidden("Invalid token or not a lecturer!")
user = get_user_by_token(token)
#try to parse payload
try:
payload = json.loads(request.data)
except Exception as e:
return bad_request("here")
try:
msg = Message(groupId=payload['groupId'], message=payload['message'], msgDate=datetime.datetime.now(), master_id=user.key().id())
except Exception as e:
print e
return bad_request("there")
try:
msg['isProject'] = payload['isProject']
except Exception as e:
pass
db.put(msg)
db.save
return created()
#----------------------------------------------------------
# PUT
#----------------------------------------------------------
#----------------------------------------------------------
# GET
#----------------------------------------------------------
@message_routes.route('/api/messages/getMessagesByGroup/<string:token>/<string:groupId>', methods=["GET"])
@auto.doc()
def getMessagesByGroup(token, groupId):
"""
<span class="card-title">>This Call will return an array of all messages (sorted by date),<br>
for a given group (course or project)</span>
<br>
<b>Route Parameters</b><br>
- SeToken: token <br>
- groupId: 1234567890
<br>
<br>
<b>Payload</b><br>
- NONE
<br>
<br>
<b>Response</b>
<br>
200 - JSON Example:<br>
<code>
{<br>
'groupId' : 1234567890,<br>
'message' : 'hello all',<br>
'date' : {<br>
'year': 2015,<br>
'month': 5,<br>
'day': 5,<br>
'hour': 5,<br>
'minute': 5<br>
},<br>
'id' : 1234567890,<br>
'master_id' : 1234567890,<br>
'isProject' : false<br>
}<br>
</code>
<br>
"""
if get_user_by_token(token) is None:
return bad_request("No such User")
arr = []
query = Message.all()
query.filter("groupId = ", int(groupId))
for m in query.run():
msgDic = dict(json.loads(m.to_JSON()))
#add a key 'forSortDate' for sorting dates
msgTime = datetime.datetime(msgDic['date']['year'], msgDic['date']['month'], msgDic['date']['day'], msgDic['date']['hour'], msgDic['date']['minute'])
msgDic['forSortDate'] = msgTime
arr.append(msgDic)
print arr
arr = sorted(arr, key=itemgetter('forSortDate'), reverse=True)
for i in arr:
del i['forSortDate']
print arr
if len(arr) != 0:
return Response(response=json.dumps(arr),
status=200,
mimetype="application/json")
else:
return Response(response=[],
status=200,
mimetype="application/json")
#----------------------------------------------------------
# DELETE
#----------------------------------------------------------
@message_routes.route('/api/messages/deleteMessage/<string:token>/<string:msgId>', methods=["DELETE"])
@auto.doc()
def deleteMessage(token, msgId):
"""
<span class="card-title">>This Call will delete a message by owner token</span>
<br>
<b>Route Parameters</b><br>
- SeToken: token
- msgId: 1234567890
<br>
<br>
<b>Payload</b><br>
- NONE
<br>
<br>
<b>Response</b>
<br>
200 - JSON Example:<br>
<code>
{<br>
'groupId' : 1234567890,<br>
'message' : 'hello all',<br>
'date' : {<br>
'year': 2015,<br>
'month': 5,<br>
'day': 5,<br>
'hour': 5,<br>
'minute': 5<br>
},<br>
'id' : 1234567890,<br>
'master_id' : 1234567890,<br>
'isProject' : false<br>
}<br>
</code>
<br>
"""
user = get_user_by_token(token)
if user is None:
return bad_request("No such User")
msg = Message.get_by_id(int(msgId))
if msg is None:
return bad_request("No such Message")
if msg.master_id != user.key().id():
return forbidden("User is not the Creator of the message")
db.delete(msg)
db.save
return no_content()
#----------------------------------------------------------
# DOCUMENTATION
#----------------------------------------------------------
@message_routes.route('/api/messages/help')
def documentation():
return auto.html()

View file

@ -42,7 +42,7 @@ def create_project(token):
- JSON Object, Example: <br> - JSON Object, Example: <br>
{<br> {<br>
'projectName': 'Advance Math',<br> 'projectName': 'Advance Math',<br>
'courseName': 'JCE',<br> 'courseId': 1234567890,<br>
'logo_url': 'http://location.domain.com/image.jpg',<br> 'logo_url': 'http://location.domain.com/image.jpg',<br>
'gitRepository': 'http://location.git.com/somthing'<br> 'gitRepository': 'http://location.git.com/somthing'<br>
}<br> }<br>
@ -62,18 +62,14 @@ def create_project(token):
payload = json.loads(request.data) payload = json.loads(request.data)
except Exception as e: except Exception as e:
return bad_request("invalid JSON format") return bad_request("invalid JSON format")
#if not is_lecturer(token): #todo: change to lecturer id
# return forbidden("Invalid token or not a lecturer!")
user = get_user_by_token(token) user = get_user_by_token(token)
if user is None: if user is None:
return bad_request("Wrong user Token") return bad_request("Wrong user Token")
#todo: check legality
try: try:
project = Project(projectName=payload['projectName'], courseName=payload['courseName'], master_id=user.key().id(), gitRepository=payload['gitRepository'], membersId=[token]) project = Project(projectName=payload['projectName'], courseId=payload['courseId'], master_id=user.key().id(), gitRepository=payload['gitRepository'], membersId=[token])
except Exception as e: except Exception as e:
print e print e
return bad_request() return bad_request()
@ -142,14 +138,14 @@ def joinProject(token, projectId):
# GET # GET
#---------------------------------------------------------- #----------------------------------------------------------
@project_routes.route('/api/projects/getProjectsByCourseName/<string:name>', methods=["GET"]) @project_routes.route('/api/projects/getProjectsByCourse/<string:courseId>', methods=["GET"])
@auto.doc() @auto.doc()
def getProjectsByCourseName(name): def getProjectsByCourse(courseId):
""" """
<span class="card-title">>This Call will return an array of all projects in a given course</span> <span class="card-title">>This Call will return an array of all projects in a given course</span>
<br> <br>
<b>Route Parameters</b><br> <b>Route Parameters</b><br>
- name: 'course name' - courseId: 1234567890
<br> <br>
<br> <br>
<b>Payload</b><br> <b>Payload</b><br>
@ -162,7 +158,7 @@ def getProjectsByCourseName(name):
<code> <code>
{<br> {<br>
'projectName': 'Advance Math',<br> 'projectName': 'Advance Math',<br>
'courseName': 'JCE',<br> 'courseId': 123456789,<br>
'grade': 98,<br> 'grade': 98,<br>
'logo_url': 'http://location.domain.com/image.jpg',<br> 'logo_url': 'http://location.domain.com/image.jpg',<br>
'gitRepository': 'http://location.git.com/somthing',<br> 'gitRepository': 'http://location.git.com/somthing',<br>
@ -175,7 +171,7 @@ def getProjectsByCourseName(name):
arr = [] arr = []
query = Project.all() query = Project.all()
query.filter("courseName = ", name) query.filter("courseId = ", int(courseId))
for p in query.run(): for p in query.run():
arr.append(dict(json.loads(p.to_JSON()))) arr.append(dict(json.loads(p.to_JSON())))

View file

@ -17,6 +17,7 @@ from flask.ext.autodoc import Autodoc
# DB Models # DB Models
from models.User import User from models.User import User
from models.Course import Course from models.Course import Course
from models.Project import Project
#Validation Utils Libs #Validation Utils Libs
from SE_API.Validation_Utils import * from SE_API.Validation_Utils import *
@ -270,6 +271,7 @@ def getUserByToken(token):
return no_content("No User Found") return no_content("No User Found")
@user_routes.route('/api/users/getUserById/', defaults={'token': None, 'id': None}) @user_routes.route('/api/users/getUserById/', defaults={'token': None, 'id': None})
@user_routes.route('/api/users/getUserById/<string:token>/<string:id>', methods=["GET"]) @user_routes.route('/api/users/getUserById/<string:token>/<string:id>', methods=["GET"])
@auto.doc() @auto.doc()
@ -333,18 +335,201 @@ def getUserById(token, id):
@user_routes.route('/api/users/getUsersByCampus/<string:token>/<string:campusId>', methods=["GET"])
@auto.doc()
def getUsersByCampus(token, campusId):
"""
<span class="card-title">>This Call will return all users in Campus</span>
<br>
<b>Route Parameters</b><br>
- seToken: 'seToken'<br>
- campusId: 123456789
<br>
<br>
<b>Payload</b><br>
- NONE
<br>
<br>
<b>Response</b>
<br>
200 - JSON Example:<br>
<code>
{<br>
'username': 'DarkLord',<br>
'name': 'Darth Vader',<br>
'email': 'darkLord@death.planet,<br>
'isLecturer': 'True',<br>
'seToken': 'xxxxxx-xxxxx-xxxxx-xxxxxx',<br>
'avatar_url': 'http://location.git.com/somthing'<br>
'isFirstLogin': False,<br>
'campuses_id_list': [75894378,5893482,894032],<br>
'courses_id_list': [4324,432432,4324324]<br>
}
</code>
<br>
403 - No User Found
"""
if token is None:
return no_content("Token Is Empty, No User Found")
user = get_user_by_token(token)
if user is None:
return bad_request("Bad User Token")
campus = Campus.get_by_id(int(campusId))
if campus is None:
return bad_request("No such Campus")
arr = []
for u in enumerate(campus.membersId):
u = json.loads(User.get_by_id(int(u)).to_JSON())
arr.append(dict(u))
if len(arr) != 0:
return Response(response=json.dumps(arr),
status=200,
mimetype="application/json")
else:
return Response(response=[],
status=200,
mimetype="application/json")
@user_routes.route('/api/users/getUsersByCourse/<string:token>/<string:courseId>', methods=["GET"])
@auto.doc()
def getUsersByCourse(token, courseId):
"""
<span class="card-title">>This Call will return all users in Course</span>
<br>
<b>Route Parameters</b><br>
- seToken: 'seToken'<br>
- courseId: 123456789
<br>
<br>
<b>Payload</b><br>
- NONE
<br>
<br>
<b>Response</b>
<br>
200 - JSON Example:<br>
<code>
{<br>
'username': 'DarkLord',<br>
'name': 'Darth Vader',<br>
'email': 'darkLord@death.planet,<br>
'isLecturer': 'True',<br>
'seToken': 'xxxxxx-xxxxx-xxxxx-xxxxxx',<br>
'avatar_url': 'http://location.git.com/somthing'<br>
'isFirstLogin': False,<br>
'campuses_id_list': [1243567,7583584904],<br>
'courses_id_list': [543543,54353453,543543534]<br>
}
</code>
<br>
403 - No User Found
"""
if token is None:
return no_content("Token Is Empty, No User Found")
user = get_user_by_token(token)
if user is None:
return bad_request("Bad User Token")
course = Course.get_by_id(int(courseId))
if course is None:
return bad_request("No such Course")
arr = []
for u in enumerate(course.membersId):
u = json.loads(User.get_by_id(int(u)).to_JSON())
arr.append(dict(u))
if len(arr) != 0:
return Response(response=json.dumps(arr),
status=200,
mimetype="application/json")
else:
return Response(response=[],
status=200,
mimetype="application/json")
@user_routes.route('/api/users/getUsersByProject/<string:token>/<string:projectId>', methods=["GET"])
@auto.doc()
def getUsersByCampus(token, projectId):
"""
<span class="card-title">>This Call will return all users in Project</span>
<br>
<b>Route Parameters</b><br>
- seToken: 'seToken'<br>
- projectId: 123456789
<br>
<br>
<b>Payload</b><br>
- NONE
<br>
<br>
<b>Response</b>
<br>
200 - JSON Example:<br>
<code>
{<br>
'username': 'DarkLord',<br>
'name': 'Darth Vader',<br>
'email': 'darkLord@death.planet,<br>
'isLecturer': 'True',<br>
'seToken': 'xxxxxx-xxxxx-xxxxx-xxxxxx',<br>
'avatar_url': 'http://location.git.com/somthing'<br>
'isFirstLogin': False,<br>
'campuses_id_list': [43243532532,5325325325,532532342],<br>
'courses_id_list': [53523,43432423,432432432432]<br>
}
</code>
<br>
403 - No User Found
"""
if token is None:
return no_content("Token Is Empty, No User Found")
user = get_user_by_token(token)
if user is None:
return bad_request("Bad User Token")
project = Project.get_by_id(int(projectId))
if project is None:
return bad_request("No such Project")
arr = []
for u in enumerate(project.membersId):
u = json.loads(User.get_by_id(int(u)).to_JSON())
arr.append(dict(u))
if len(arr) != 0:
return Response(response=json.dumps(arr),
status=200,
mimetype="application/json")
else:
return Response(response=[],
status=200,
mimetype="application/json")
#---------------------------------------------------------- #----------------------------------------------------------
# DELETE # DELETE
#---------------------------------------------------------- #----------------------------------------------------------
@user_routes.route('/api/users/removeUserFromCampus/<string:token>/<string:campusId>', methods=["PUT"]) @user_routes.route('/api/users/removeUserFromCampus/<string:token>/<string:userId>/<string:campusId>', methods=["PUT"])
@auto.doc() @auto.doc()
def removeUserFromCampus(token, campusId): def removeUserFromCampus(token, userId, campusId):
""" """
<span class="card-title">>This Call will remove a Campus from a user Campus list</span> <span class="card-title">>This Call will remove a user from a campus</span>
<br> <br>
<b>Route Parameters</b><br> <b>Route Parameters</b><br>
- seToken: 'seToken' - seToken: 'seToken'<br>
- userId: 0987654321,<br>
- 'campusId': 1234567890<br> - 'campusId': 1234567890<br>
<br> <br>
<br> <br>
@ -360,18 +545,13 @@ def removeUserFromCampus(token, campusId):
400 - Bad Request 400 - Bad Request
""" """
if not request.data: requestingUser = get_user_by_token(token)
return bad_request() if requestingUser is None:
return bad_request("Bad User Token")
try: userToRemove = User.get_by_id(int(userId))
payload = json.loads(request.data) if userToRemove is None:
except Exception as e: return bad_request("No such user to remove")
return bad_request()
if not is_lecturer(token): #todo: change to lecturer id
return forbidden("Invalid token or not a lecturer!")
user = get_user_by_token(token)
#check Campus Exists #check Campus Exists
campus = Campus.get_by_id(int(campusId)) campus = Campus.get_by_id(int(campusId))
@ -379,18 +559,20 @@ def removeUserFromCampus(token, campusId):
return bad_request("No such Campus!") return bad_request("No such Campus!")
#check if user is owner of Campus #check if user is owner of Campus
if user.key().id() != campus.master_user_id: if requestingUser.key().id() != campus.master_user_id:
return forbidden("Lecturer is not owner of course") # check if user want to delete itself
if requestingUser.key().id() != userToRemove.key().id():
return forbidden("No permission to delete user")
try: try:
user.campuses_id_list.remove(campusId) userToRemove.campuses_id_list.remove(campusId)
except Exception as e: except Exception as e:
print e
return bad_request("user is not listed to this campus") return bad_request("user is not listed to this campus")
db.put(user)
db.put(userToRemove)
db.save db.save
return Response(response=user.to_JSON(), return Response(response=userToRemove.to_JSON(),
status=200, status=200,
mimetype="application/json") # Real response! mimetype="application/json") # Real response!
@ -398,64 +580,128 @@ def removeUserFromCampus(token, campusId):
# @user_routes.route('/api/users/removeUserFromCourse/<string:token>/<string:courseId>', methods=["PUT"])
# @auto.doc() @user_routes.route('/api/users/removeUserFromCourse/<string:token>/<string:userId>/<string:courseId>', methods=["PUT"])
# def removeUserFromCourse(token, courseId): @auto.doc()
# """ def removeUserFromCourse(token, userId, courseId):
# <span class="card-title">>This Call will remove a Course from a user Campus list</span> """
# <br> <span class="card-title">>This Call will remove a user from a course</span>
# <b>Route Parameters</b><br> <br>
# - seToken: 'seToken' <b>Route Parameters</b><br>
# - 'courseId': 1234567890<br> - seToken: 'seToken'<br>
# <br> - userId: 0987654321,<br>
# <br> - 'courseId': 1234567890<br>
# <b>Payload</b><br> <br>
# - NONE <br>
# {<br> <b>Payload</b><br>
# }<br> - NONE
# <br> {<br>
# <b>Response</b> }<br>
# <br> <br>
# 200 - User updated <b>Response</b>
# <br> <br>
# 400 - Bad Request 200 - User updated
# """ <br>
# 400 - Bad Request
# if not request.data: """
# return bad_request()
# requestingUser = get_user_by_token(token)
# try: if requestingUser is None:
# payload = json.loads(request.data) return bad_request("Bad User Token")
# except Exception as e:
# return bad_request() userToRemove = User.get_by_id(int(userId))
# if userToRemove is None:
# user = get_user_by_token(token) return bad_request("No such user to remove")
# if user is None:
# return bad_request("No such user!") #check Course Exists
# course = Course.get_by_id(int(courseId))
# if course is None:
# #check Course Exists return bad_request("No such Course!")
# course = Course.get_by_id(int(courseId))
# if course is None: #check if user is owner of Course
# return bad_request("No such Course!") if requestingUser.key().id() != course.master_id:
# # check if user want to delete itself
# #check if user is owner of Campus if requestingUser.key().id() != userToRemove.key().id():
# if user.key().id() != course.master_id: return forbidden("No permission to delete user")
# return forbidden("Lecturer is not owner of course")
# try:
# try: userToRemove.courses_id_list.remove(courseId)
# user.campuses_id_list.remove(campusId) course.membersId.remove(userToRemove.key().id())
# except Exception as e: except Exception as e:
# print e return bad_request("user is not listed to this course")
# return bad_request("user is not listed to this campus")
#
# db.put(user)
# db.save db.put(userToRemove)
# return Response(response=user.to_JSON(), db.put(course)
# status=200, db.save
# mimetype="application/json") # Real response! return Response(response=userToRemove.to_JSON(),
# status=200,
# mimetype="application/json") # Real response!
@user_routes.route('/api/users/removeUserFromProject/<string:token>/<string:userId>/<string:projectId>', methods=["PUT"])
@auto.doc()
def removeUserFromProject(token, userId, projectId):
"""
<span class="card-title">>This Call will remove a user from a project</span>
<br>
<b>Route Parameters</b><br>
- seToken: 'seToken'<br>
- userId: 0987654321,<br>
- 'projectId': 1234567890<br>
<br>
<br>
<b>Payload</b><br>
- NONE
{<br>
}<br>
<br>
<b>Response</b>
<br>
200 - User updated
<br>
400 - Bad Request
"""
requestingUser = get_user_by_token(token)
if requestingUser is None:
return bad_request("Bad User Token")
userToRemove = User.get_by_id(int(userId))
if userToRemove is None:
return bad_request("No such user to remove")
#check project Exists
project = Project.get_by_id(int(projectId))
if project is None:
return bad_request("No such Project!")
#check if user is owner of project
if requestingUser.key().id() != project.master_id:
# check if user want to delete itself
if requestingUser.key().id() != userToRemove.key().id():
return forbidden("No permission to delete user")
try:
userToRemove.projects_id_list.remove(projectId)
project.membersId.remove(userToRemove.key().id())
except Exception as e:
return bad_request("user is not listed to this project")
db.put(userToRemove)
db.put(project)
db.save
return Response(response=userToRemove.to_JSON(),
status=200,
mimetype="application/json") # Real response!

View file

@ -0,0 +1,97 @@
__author__ = 'etye'
import unittest
import requests
import json
from Testing.config import __CONFIG__
class UserTestPlan(unittest.TestCase):
@classmethod
def setUpClass(cls):
debug = __CONFIG__['DEBUG']
if debug:
url = __CONFIG__['PATHS']['DEBUG']
else:
url = __CONFIG__['PATHS']['PRODUCTION']
cls.url_ = url
request = requests.get(url+'api/qa/init')
if 200 <= request.status_code <= 299:
print 'Initialized'
def test_courseCreate_lecturer(self):
#url = "http://localhost:8080/api/courses/create/_QA_TOKEN_TEST_LECTURER"
url=self.__class__.url_+'api/courses/create/'+__CONFIG__['TOKENS']['LECTURER']
data = {
'courseName': 'matan',
'campusName': 'https://yt3.ggpht.com/--ZkWxybWGOM/AAAAAAAAAAI/AAAAAAAAAAA/_nAICC_kzzI/s88-c-k-no/photo.jpg',
'projects': '@gay.lord.ultima.multi.omega',
'startDate': {'year': 2015, 'month' : 4, 'day' : 3},
'endDate': {'year': 2016,'month' : 6,'day' : 6}
}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)
self.assertEquals(r.status_code, 201)
def test_courseCreate_lecturerExsistingCourse(self):
#url = "http://localhost:8080/api/courses/create/_QA_TOKEN_TEST_LECTURER"
url=self.__class__.url_+'api/courses/create/'+__CONFIG__['TOKENS']['LECTURER']
data = {
'courseName': 'matan',
'campusName': 'https://yt3.ggpht.com/--ZkWxybWGOM/AAAAAAAAAAI/AAAAAAAAAAA/_nAICC_kzzI/s88-c-k-no/photo.jpg',
'projects': '@gay.lord.ultima.multi.omega',
'startDate': {'year': 2015, 'month' : 4, 'day' : 3},
'endDate': {'year': 2016,'month' : 6,'day' : 6}
}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)
self.assertEquals(r.status_code, 403)
def test_courseCreate_student(self):
#url = "http://localhost:8080/api/courses/create/_QA_TOKEN_TEST_LECTURER"
url=self.__class__.url_+'api/courses/create/'+__CONFIG__['TOKENS']['STUDENT']
data = {
'courseName': 'matan',
'campusName': 'https://yt3.ggpht.com/--ZkWxybWGOM/AAAAAAAAAAI/AAAAAAAAAAA/_nAICC_kzzI/s88-c-k-no/photo.jpg',
'projects': '@gay.lord.ultima.multi.omega',
'startDate': {'year': 2015, 'month' : 4, 'day' : 3},
'endDate': {'year': 2016,'month' : 6,'day' : 6}
}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)
self.assertEquals(r.status_code, 403)
def test_courseCreate_invalidToken(self):
#url = "http://localhost:8080/api/courses/create/_QA_TOKEN_TEST_LECTURER"
url=self.__class__.url_+'api/courses/create/invalidToken'
data = {
'courseName': 'matan',
'campusName': 'https://yt3.ggpht.com/--ZkWxybWGOM/AAAAAAAAAAI/AAAAAAAAAAA/_nAICC_kzzI/s88-c-k-no/photo.jpg',
'projects': '@gay.lord.ultima.multi.omega',
'startDate': {'year': 2015, 'month' : 4, 'day' : 3},
'endDate': {'year': 2016,'month' : 6,'day' : 6}
}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)
self.assertEquals(r.status_code, 403)
def test_courseCreate_hebrewToken(self):
#url = "http://localhost:8080/api/courses/create/_QA_TOKEN_TEST_LECTURER"
url=self.__class__.url_+'api/courses/create/????'
data = {
'courseName': 'matan',
'campusName': 'https://yt3.ggpht.com/--ZkWxybWGOM/AAAAAAAAAAI/AAAAAAAAAAA/_nAICC_kzzI/s88-c-k-no/photo.jpg',
'projects': '@gay.lord.ultima.multi.omega',
'startDate': {'year': 2015, 'month' : 4, 'day' : 3},
'endDate': {'year': 2016,'month' : 6,'day' : 6}
}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)
self.assertEquals(r.status_code, 404)
#/api/courses/getCourseByCampusName/<string:name>
def test_getCourseByCampusName_EXSISTING_CAMPUS(self):
url=self.__class__.url_+'api/courses/getCourseByCampusName/'+__CONFIG__['CAMPUS_NAME']['JCE']
r = requests.get(url)
self.assertEquals(r.status_code, 200)
if __name__ == '__main__':
unittest.main()

View file

@ -9,12 +9,15 @@ class Campus(db.Model):
avatar_url = db.StringProperty(required=True) avatar_url = db.StringProperty(required=True)
email_ending = db.StringProperty(required=True) email_ending = db.StringProperty(required=True)
master_user_id = db.IntegerProperty(required=True) master_user_id = db.IntegerProperty(required=True)
membersId = db.StringListProperty(required=True, default=[])
def to_JSON(self): def to_JSON(self):
data = {'title': self.title, data = {'title': self.title,
'email_ending': self.email_ending, 'email_ending': self.email_ending,
'master_user_id': self.master_user_id, 'master_user_id': self.master_user_id,
'avatar_url': self.avatar_url, 'avatar_url': self.avatar_url,
'membersId': self.membersId,
'id' : self.key().id() 'id' : self.key().id()
} }
return json.dumps(data) return json.dumps(data)

View file

@ -5,7 +5,7 @@ from google.appengine.ext import db
class Course(db.Model): class Course(db.Model):
courseName = db.StringProperty(required=True) courseName = db.StringProperty(required=True)
campusName = db.StringProperty(required=True) campusId = db.IntegerProperty(required=True)
master_id = db.IntegerProperty(required=True) master_id = db.IntegerProperty(required=True)
# projects = db.StringListProperty(required=True,default=[]) # projects = db.StringListProperty(required=True,default=[])
startDate = db.DateProperty(required=True) startDate = db.DateProperty(required=True)
@ -14,7 +14,7 @@ class Course(db.Model):
def to_JSON(self): def to_JSON(self):
data = {'courseName' : self.courseName, data = {'courseName' : self.courseName,
'campusName' : self.campusName, 'campusId' : self.campusId,
'master_id' : self.master_id, 'master_id' : self.master_id,
# 'projects' : self.projects, # 'projects' : self.projects,
'startDate' : { 'startDate' : {

View file

@ -5,7 +5,7 @@ from google.appengine.ext import db
class Project(db.Model): class Project(db.Model):
projectName = db.StringProperty(required=True) projectName = db.StringProperty(required=True)
courseName = db.StringProperty(required=True) courseId = db.IntegerProperty(required=True)
master_id = db.IntegerProperty(required=True) master_id = db.IntegerProperty(required=True)
grade = db.IntegerProperty(required=True, default=0) grade = db.IntegerProperty(required=True, default=0)
logo_url = db.StringProperty(required=False) logo_url = db.StringProperty(required=False)
@ -14,7 +14,7 @@ class Project(db.Model):
def to_JSON(self): def to_JSON(self):
data = {'projectName' : self.projectName, data = {'projectName' : self.projectName,
'courseName' : self.courseName, 'courseId' : self.courseId,
'master_id' : self.master_id, 'master_id' : self.master_id,
'grade' : self.grade, 'grade' : self.grade,
'logo_url' : self.logo_url, 'logo_url' : self.logo_url,

View file

@ -62,6 +62,7 @@
<li class="collection-item dismissable"><div>Courses Related API<a href="/api/courses/help" class="secondary-content"><i class="mdi-content-send"></i></a></div></li> <li class="collection-item dismissable"><div>Courses Related API<a href="/api/courses/help" class="secondary-content"><i class="mdi-content-send"></i></a></div></li>
<li class="collection-item dismissable"><div>Projects Related API<a href="/api/projects/help" class="secondary-content"><i class="mdi-content-send"></i></a></div></li> <li class="collection-item dismissable"><div>Projects Related API<a href="/api/projects/help" class="secondary-content"><i class="mdi-content-send"></i></a></div></li>
<li class="collection-item dismissable"><div>Tasks Related API<a href="/api/tasks/help" class="secondary-content"><i class="mdi-content-send"></i></a></div></li> <li class="collection-item dismissable"><div>Tasks Related API<a href="/api/tasks/help" class="secondary-content"><i class="mdi-content-send"></i></a></div></li>
<li class="collection-item dismissable"><div>Messages Related API<a href="/api/messages/help" class="secondary-content"><i class="mdi-content-send"></i></a></div></li>
<li class="collection-item dismissable"><div>Validation Related API<a href="#!" class="secondary-content"><i class="mdi-content-send"></i></a></div></li> <li class="collection-item dismissable"><div>Validation Related API<a href="#!" class="secondary-content"><i class="mdi-content-send"></i></a></div></li>
<li class="collection-item dismissable"><div>Miscellaneous Methods<a href="/api/help/misc" class="secondary-content"><i class="mdi-content-send"></i></a></div></li> <li class="collection-item dismissable"><div>Miscellaneous Methods<a href="/api/help/misc" class="secondary-content"><i class="mdi-content-send"></i></a></div></li>
</ul> </ul>