from flask import current_app from .db import MongoDB class User(object): def __init__(self, app=None): self.app = app def all(self): db = MongoDB(self.app) mongo = db.connection() return list(mongo.db.users.find({})) def register(self, username): db = MongoDB(self.app) mongo = db.connection() error = {} if not username: error = {'msg': 'Username is required.', 'code': 400} elif len(list(mongo.db.users.find({"username": username}))) > 0: error = { 'msg': 'User {} is already registered.'.format(username), 'code': 409 } if not error: mongo.db.users.insert({"username": username}) return {'msg': 'User {} added.'.format(username), 'code': 201} return error def remove(self, username): db = MongoDB(self.app) mongo = db.connection() error = {} if not username: error = {'msg': 'Username is required', 'code': 400} elif len(list(mongo.db.users.find({"username": username}))) == 0: error = { 'msg': "User {} not exist. So it's good.".format(username), 'code': 404 } if not error: mongo.db.users.remove({"username": username}) return {'msg': 'User {} deleted.'.format(username), 'code': 200} return error