Exemple #1
0
	def get(self, moduleID = None):
		if (moduleID is None):
			full = request.args.get('full', False)
			if (full):
				cursor = LibraryModule._get_collection().find(sort = [('name', 1)])
			else:
				cursor = LibraryModule._get_collection().find({}, {'name': True, 'description': True}, sort = [('name', 1)])
			return makeJsonResponse(list(cursor))
		else:
			module = LibraryModule._get_collection().find_one({'_id': moduleID})
			if (module is None):
				raise APIException("No module exists with ID {}".format(moduleID))
			return makeJsonResponse(module)
Exemple #2
0
	def post(self):
		"""
		Create a new quantity
		"""
		quantity = Quantity()
		quantity.save()
		return makeJsonResponse({'_id': quantity.id}, 'Quantity created')
Exemple #3
0
	def put(self, quantityID):
		quantityData = parseJsonResponse(request.data)
		del quantityData['_id']
		quantity = Quantity.objects.get(id = quantityID)
		quantity.modify(**quantityData)
		quantity.save()
		return makeJsonResponse(None, 'Quantity saved')
Exemple #4
0
	def changePassword(self):
		requestData = parseJsonResponse(request.data)
		username = requestData['username']
		oldPassword = requestData['oldPassword']
		newPassword = requestData['newPassword']
		
		try:
			user = User.objects.get(username = username)
		except DoesNotExist:
			raise NotFoundError("User not found")
		
		permission = UserAdminPermission(user)
		if not permission.can():
			raise APIException('You have no permission to change the user password')
		
		passwordValid = bcrypt.check_password_hash(user.password, oldPassword)
		if (not passwordValid):
			raise APIException('Invalid old password')
		
		if (len(newPassword) < 6):
			raise APIException('Your new password has to be at least 6 characters long')
		
		user.modify(password = unicode(bcrypt.generate_password_hash(newPassword)))
		
		return makeJsonResponse(None, 'Password changed')
Exemple #5
0
	def delete(self, modelID, username):
		model = Models.Model.objects.get(id = modelID)
		self.checkPermissions(model)
		user = Users.User.objects.get(username = username)
		accessEntry = ModelUserAccess.objects.get(model = model, user = user)
		accessEntry.delete()
		return makeJsonResponse(None, 'Success')
Exemple #6
0
	def get(self, quantityID = None):
		"""
		Returns a model or a list of models
		"""
		if (quantityID is None):
			full = request.args.get('full', False)
			if (full):
				cursor = Quantity._get_collection().find(sort = [('name', 1)])
			else:
				cursor = Quantity._get_collection().find({}, {'name': True}, sort = [('name', 1)])
			return makeJsonResponse(list(cursor))
		else:
			quantity = Quantity._get_collection().find_one({'_id': quantityID})
			if (quantity is None):
				raise APIException("No quantity exists with ID {}".format(quantityID))
			return makeJsonResponse(quantity)
Exemple #7
0
	def get(self, modelID = None):
		model = Models.Model.objects.get(id = modelID)
		self.checkPermissions(model)
		acl = ModelUserAccess.objects(model = model)
		accessList = []
		for accessEntry in acl:
			accessList.append({'username': accessEntry.user.username, 'access': dict(ModelUserAccess.ACCESS)[accessEntry.access]})
		return makeJsonResponse(accessList)
Exemple #8
0
 def delete(self, modelID):
     """ Delete a model"""
     model = Model.objects.get(id=modelID)
     permission = MP.ModelFullPermission(model)
     if permission.can():
         model.delete()
         return makeJsonResponse(None, "Model deleted")
     else:
         raise UnauthorizedError("You have no permissions to delete this model")
Exemple #9
0
	def post(self, moduleID = None):
		with AdminPermission.require():
			if (moduleID == None):
				newModule = LibraryModule()
				newModule.save()
				return makeJsonResponse({'_id': newModule.id})
			else:
				params = request.args
				action = params.get('action')			
				raise APIException("Unknown POST action {}".format(action))
Exemple #10
0
 def loadModel(self, modelID):
     # Get a single model
     try:
         model = Model.objects.get(id=modelID)
     except DoesNotExist:
         raise APIException("No model exists with ID {}".format(modelID))
     permission = MP.ModelViewPermission(model)
     if not permission.can():
         raise UnauthorizedError("You have no permissions to view this model")
     model = model.to_mongo()
     return makeJsonResponse(model)
Exemple #11
0
	def logout(self):
		logout_user()
		# Remove session keys set by Flask-Principal
		for key in ('identity.name', 'identity.auth_type'):
			session.pop(key, None)					
		# Tell Flask-Principal the user is anonymous
		identity_changed.send(current_app._get_current_object(),
					  identity = AnonymousIdentity())
		response = makeJsonResponse({'msg': 'You have sucessfully logged out'})
		response.set_cookie('user.username', '')
		response.set_cookie('user.roles', '')
		return response
Exemple #12
0
	def post(self, modelID, username):
		model = Models.Model.objects.get(id = modelID)
		self.checkPermissions(model)
		user = Users.User.objects.get(username = username)
		access = request.args['access']
		access = ModelUserAccess.ACCESS_DCT[access]
		try:
			accessEntry = ModelUserAccess.objects.get(model = model, user = user)
			accessEntry.modify(access = access)
		except DoesNotExist:
			accessEntry = ModelUserAccess(model = model, user = user, access = access)
			accessEntry.save()
		return makeJsonResponse(None, 'Success')
Exemple #13
0
 def copy(self, modelID, user):
     # Duplicate existing model
     model = Model.objects.get(id=modelID)
     permission = MP.ModelViewPermission(model)
     if permission.can():
         model.id = None
         model.name = "Copy of " + model.name
         model.created = datetime.datetime.utcnow()
         model.owner = user
         model.save()
         return makeJsonResponse({"_id": model.id})
     else:
         raise UnauthorizedError("You have no permissions to copy this model")
Exemple #14
0
	def find(self):
		""""Finds a user"""		
		identifier = request.args.get('identifier')
		try:
			if (identifier is not None):
				if ('@' in identifier):
					user = User.objects.get(email = identifier)
				else:
					user = User.objects.get(username = identifier)
			else:
				raise APIException("Parameter 'identifier' must be given")
		except DoesNotExist:
			raise NotFoundError("User not found")
		result = dict(username = user.username)
		return makeJsonResponse(result)
Exemple #15
0
	def login(self):
		userData = parseJsonResponse(request.data)
		if current_user.is_authenticated():
			return makeJsonResponse({'msg': 'You are already logged in'})
		else:
			try:
				user = User.objects.get(email = userData['id'])
			except DoesNotExist:
				raise APIException('User does not exist')
			if (not user.active):
				raise APIException('User has not been activated or has been deactivated. Please contact the administrator!')
			if (not user.confirmed):
				raise APIException('Your registration has not been confirmed. Please visit the link found in yout email!')
			passwordValid = bcrypt.check_password_hash(user.password, userData['password'])
			if (passwordValid):
				login_user(user)
				identity_changed.send(current_app._get_current_object(),
							  identity = Identity(user.get_id()))
				response = makeJsonResponse({'msg': 'You have sucessfully logged in'})
				response.set_cookie('user.username', user.username)
				response.set_cookie('user.roles', '-'.join([role.name for role in user.roles]))
				return response
			else:
				raise APIException('Incorrect password')
Exemple #16
0
 def put(self, modelID):
     """Updates a model definition"""
     model = Model.objects.get(id=modelID)
     permission = MP.ModelEditPermission(model)
     if permission.can():
         modelData = parseJsonResponse(request.data)
         model.modify(
             name=modelData["name"],
             description=modelData["description"],
             board=Board(**modelData["board"]),
             background=modelData.get("background"),
             publicAccess=modelData.get("publicAccess"),
         )
         model.save()
         return makeJsonResponse(None, "Model saved")
     else:
         raise UnauthorizedError("You have no permissions to save changes to this model")
Exemple #17
0
 def listModels(self):
     responseFields = {"name": True, "description": True, "created": True, "owner": True}
     userCollection = User._get_collection()
     models = None
     if current_user.is_authenticated():
         user = current_user._get_current_object()
         # modelUserRelation = [own, shared, public, all]
         modelUserRelation = request.args.get("modelUserRelation", "own")
         if modelUserRelation == "own":
             searchFilter = {"owner": user.id}
         elif modelUserRelation == "shared":
             models = []
             sharedModelAccess = MP.ModelUserAccess.objects(
                 user=user, access__gte=MP.ModelUserAccess.ACCESS_DCT["list"]
             )
             for modelAccess in sharedModelAccess:
                 model = modelAccess.model
                 models.append(
                     {
                         "_id": model.id,
                         "name": model.name,
                         "description": model.description,
                         "created": model.created,
                         "owner": model.owner.username,
                         "access": modelAccess.access,
                     }
                 )
         elif modelUserRelation == "public":
             searchFilter = {"publicAccess": {"$gte": Model.PUBLIC_ACCESS_DCT["list"]}}
             responseFields["publicAccess"] = True
         elif modelUserRelation == "all":
             if AdminPermission.can():
                 searchFilter = {}
             else:
                 raise UnauthorizedError("Only administrators can list all models in the database")
         else:
             raise APIException("Invalid value for modelUserRelation, must be one of [own, shared, public, all]")
     else:
         searchFilter = {"publicAccess": {"$gte": Model.PUBLIC_ACCESS_DCT["list"]}}
         responseFields["publicAccess"] = True
     if models is None:
         models = list(Model._get_collection().find(searchFilter, responseFields, sort=[("name", 1)]))
         for model in models:
             model["owner"] = userCollection.find_one({"_id": model["owner"]})["username"]
     return makeJsonResponse(models)
Exemple #18
0
	def create(self):
		# If no users exist, init the user DB
		if (User.objects.count() == 0):
			self.initUsersDB();
		userData = parseJsonResponse(request.data)
		if (len(userData[u'password']) < 6):
			raise APIException('Your password has to be at least 6 characters long')
		if (User.objects(username = userData['username']).count() > 0):
			raise APIException('User with this username already exists')
		if (User.objects(email = userData['email']).count() > 0):
			raise APIException('User with this email already exists')
		roleUser = Role.objects.get(name='user')
		user = User(
			username = userData['username'],
			email = userData['email'],
			firstName = userData['firstName'],
			lastName = userData['lastName'],
			country = userData['country'],
			organization = userData.get('organization', ''),
			password = unicode(bcrypt.generate_password_hash(userData[u'password'])),
			roles = [roleUser]
		)
		# If no users exist, init the user DB
		if (User.objects.count() == 0):
			user.roles.append(Role.objects.get(name='admin'))
		try:
			user.save()
			# Send email to the user
			msg = Message("Welcome to STEM", recipients = [user.email])
			msg.body = """\
Please click on the link to activate your profile
http://stem.sysmoltd.com/stem/api/Users/confirm?username={}&activationCode={}""".format(user.username, str(user.id))
			mail.send(msg)
			# Send email to admin
			msg = Message("New user registration", recipients = ["*****@*****.**"])
			msg.body = "username: {}\n email: {}\n".format(user.username, user.email)
			mail.send(msg)
		except NotUniqueError:
			raise APIException('Registration failed. Please contact the administrator [email protected]')
		return makeJsonResponse({
			'msg': 'Successfully created user {}'.format(user.username)
		})
Exemple #19
0
	def delete(self, quantityID):
		Quantity.objects.get(id = quantityID).delete()
		return makeJsonResponse(None, 'Quantity deleted')
Exemple #20
0
 def create(self, user):
     """"Create new model"""
     model = Model(owner=user)
     model.save()
     return makeJsonResponse({"_id": model.id})
Exemple #21
0
 def compute(self):
     modelData = parseJsonResponse(request.data)
     ex = ModelCalculator(modelData)
     ex.compute()
     return makeJsonResponse(modelData, "Model computed")