Пример #1
0
def signin():
    logger.debug('Welcome to SIGN IN page')

    # Parse the request arguments
    collection = get_collection_map('user')
    json_data = json.loads(request.data)
    user = json_data.get('username', None)
    password = json_data.get('password', None)

    # Check if the arguments supplied are correct. Also check the contents of the arguments
    if user is "" or password is "":
        logger.debug("Either User/Email or Password is None")
        logger.debug("User/Email: {0}, Password: {1}".format(user, password))
        return jsonify(message="Either User/Email or Password is NULL"), 400

    if user is None or password is None:
        logger.debug("Username or Password keyword is incorrect")
        logger.debug("Expected: username/password  Got: {0}".format(
            json_data.keys()))
        return jsonify(message="Expected: username/password  Got: {0}".format(
            json_data.keys())), 400

    # Query the DB for appropriate keyword and return accordingly
    db_obj = CollectionClass(mongo.db[collection]).find_one(
        filter={'$or': [{
            'username': user
        }, {
            'email': user
        }]})
    if db_obj is not None:
        decrypted_password = cipher_obj.decrypt(
            db_obj['password']).decode('utf-8')
        if json_data.get('password') == decrypted_password:
            logger.info('User Credentials Authentication Successful')
            return jsonify(
                message="User Credentials Authentication Successful"), 200
        else:
            logger.warning('Wrong Password')
            return jsonify(message="Invalid Username or Password"), 400
    else:
        logger.info('Invalid Username')
        return jsonify(message="Invalid Username or Password"), 400
Пример #2
0
def get_db_info(filename):
    with open(filename) as file_handle:
        data = json.load(file_handle)
    try:
        user = data["user"]
        password = data["password"]
        db = data["db"]
        key = data["cipherkey"]
        logger.debug(
            "Was able to successfully parse the file and "
            "extract the username, password, db-name and key from {0}".format(
                filename))

    except:
        logger.error(
            "Could not find username, password, db-name and key in the file. "
            "Please check the {0} again".format(filename))
        user = None
        password = None
        db = None
        key = None

    return user, password, db, key
Пример #3
0
def signup():
    logger.debug('Welcome to SIGN UP page')

    # Parse the request arguments
    collection = get_collection_map('user')
    json_data = json.loads(request.data)
    username = json_data.get('username', None)
    email_id = json_data.get('email', None)
    password = json_data.get('password', None)
    json_data["password"] = cipher_obj.encrypt(bytes(password, 'utf-8'))

    # Check if the arguments supplied are correct. Also check the contents of the arguments
    if username is "" or password is "" or email_id is "":
        logger.debug("Either Username or Email-ID or Password is NULL")
        logger.debug("Username: {0}, Email-ID: {1}, Password: {2}".format(
            username, email_id, password))
        return jsonify(
            message="Either Username or Email-ID or Password is NULL"), 400

    if username is None or password is None or email_id is None:
        logger.debug("Username or Email-ID or Password keyword is incorrect")
        logger.debug("Expected: username/email/password  Got: {0}".format(
            json_data.keys()))
        return jsonify(message="Expected: username/email/password  Got: {0}".
                       format(json_data.keys())), 400

    if (len(json_data.keys()) != 3):
        logger.debug("Expected: username/email/password  Got: {0}".format(
            json_data.keys()))
        return jsonify(
            message=
            "Incorrect number of keys. Expected: username/email/password  Got: {0}"
            .format(json_data.keys())), 400

    # Query the DB for appropriate keyword and return accordingly
    try:
        CollectionClass(mongo.db[collection]).insert([json_data])
        logger.info("Successfully added {0} in the DB".format(username))
        return jsonify(message="{0} added successfully".format(username)), 200
    except pymongo.errors.DuplicateKeyError as e:
        logger.exception('{0}'.format(e))
        return jsonify(
            message="Username already taken, please choose another one"), 400
    except Exception as e:
        logger.exception('{0}'.format(e))
        return jsonify(message="Server Exception. Try again in some time"), 500
Пример #4
0
def create_index():
    collection_with_index = "test_with_index"
    log.debug("Trying To create index for {0}".format(collection_with_index))
    print (mongo.db[collection_with_index].create_index([("username", 1)], unique=True))
    print (mongo.db[collection_with_index].create_index([("email", 1)]))
Пример #5
0
def get_articles():
    """
    /articles?username=kmanek&limit=2
        Get all articles owned by kmanek where limit is 2 (This is for the first page)
        
    /articles?username=kmanek&id=5b664e9bd09275c1286c86a1&limit=2
        Get all articles owned by kmanek where id > 5b664e9bd09275c1286c86a1 and limit is 2 (this is for all pages except first)
        
    /articles?limit=2
        Get all articles from all owners where limit is 2 (This is for the first page)
            
    /articles?id=5b664e9bd09275c1286c86a1&limit=2
        Get all articles from all owners where id > 5b664e9bd09275c1286c86a1 and limit is 2 (this is for all pages except first)
        
    /articles
        This is not yet defined and will throw user does not exist error
     
    """
    logger.debug('Welcome to get all articles page')

    # Parse the request arguments
    article_collection = get_collection_map('article')
    user_collection = get_collection_map('user')

    # parse username, default is None
    username = request.args.get('username', default=None)

    # default value of limit is 10 is not specified
    limit = int(request.args.get('limit', default="10"))

    # default value of last_id will be 0 for the first page
    last_id_rcvd = request.args.get('last_id',
                                    default="000000000000000000000000")

    logger.debug("Received GET request for the foll parameters {0}".format(
        request.args))

    # If username is provided and exist then return all articles owned by that username.
    # If username is provided and does not exist then return with error.
    if username:
        if user_exit(collection_name=user_collection, user=username):
            search_filter = {
                'article_owner_id': username,
                "_id": {
                    "$gt": ObjectId(last_id_rcvd)
                }
            }
        else:
            return jsonify(message='Username \'{0}\' does not exist.'.format(
                username)), 400

    # If username is not provided then return all articles.
    else:
        search_filter = {"_id": {"$gt": ObjectId(last_id_rcvd)}}


    article_obj = CollectionClass(mongo.db[article_collection]). \
                find(filter=search_filter, limit=limit, sort=[("_id",pymongo.DESCENDING)])

    # Convert pymongo cursor to list, so that it can be converted to JSON later on
    article_data = list(article_obj)

    try:
        object_id_str = dumps(article_data[0]["_id"])
        object_id_json = json.loads(object_id_str)
        last_id_sent = object_id_json["$oid"]
    # this will trigger when there are no more articles to be shown, hence make last_id_sent = -1
    except IndexError as e:
        logger.exception(e)
        last_id_sent = -1

    # TODO: Ask Gareth if he wants 204 status code with no content or send empty JSON with 200 status code

    return jsonify(message=dumps(article_obj), last_id=last_id_sent), 200
Пример #6
0
import json

sys.path.append(os.path.join(os.path.dirname(__file__), ".."))

from app.main import logger, app, mongo
from app.views.users import user_mod
from app.views.articles import articles_mod

from flask_cors import cross_origin

app.register_blueprint(user_mod)
app.register_blueprint(articles_mod)

try:
    logger.debug(
        "Trying to test if DB can be connected or not by displaying all the collection names: {0}"
        .format(mongo.db.collection_names()))
except Exception as e:
    logger.exception("Could not connect to MongoDB Exiting... {0}".format(e))
    sys.exit(1)

manager = Manager(app)


@app.route('/getAll', methods=['GET'])
@cross_origin()
def find_data():

    # print dir(mongo.db)
    collection = mongo.db.list_collection_names()[0]
    collection = 'demo-articles'
Пример #7
0
def seed_ntpc():
    logger.debug("Seed NTPC sample data")
    data_file = os.path.join(os.getcwd(), "seed", "NTCLighting.csv")
    if not os.path.isfile(data_file):
        logger.debug(f"CSV file not existed: {data_file}")
        return

    clean_data()

    # add basic data
    cust = sdCustomer(name=__cust_name,
                      display_name=__cust_display,
                      comment=__cust_comment)
    user = sdUser(cust=cust,
                  name="admin",
                  display_name="Admin (NTPC)",
                  comment="NTPC Administrator",
                  password="******")
    model_led = sdDeviceModel(name=__model_led[0], display_name=__model_led[1])
    model_ctrl = sdDeviceModel(name=__model_ctrl[0],
                               display_name=__model_ctrl[1])
    db.session.add(cust)
    db.session.add(user)
    db.session.add(model_led)
    db.session.add(model_ctrl)
    db.session.commit()

    # add devices
    device_groups = {}
    with open(data_file, encoding='utf-8', newline='') as csv_file:
        rows = csv.reader(csv_file)
        index = 0
        row_count = 0
        for row in rows:
            index += 1
            if index == 1:
                # ignore header
                continue
            # convert twd97 to wgs84
            try:
                twd_x, twd_y = float(row[4]), float(row[5])
                (wgs_y, wgs_x) = twd97.towgs84(twd_x, twd_y)
            except Exception:
                logger.debug(f"twd or wgs error: {row}")
                continue
            # check if coordination out of range
            if wgs_x < 120 or wgs_x > 122 or wgs_y < 24 or wgs_y > 26:
                logger.debug(
                    f"wgs_x or wgs_y out of range: 120 <= x < 122 or 24 <= x < 26"
                )
                continue
            # add device
            row_count = row_count + 1
            # get or new device group
            group_name = row[0]
            device_group = device_groups.get(group_name)
            if not device_group:
                device_group = sdDeviceGroup(cust=cust,
                                             name=group_name,
                                             display_name=f"新北市{group_name}")
                device_groups[group_name] = device_group
            # new device
            device = sdDevice(
                cust=cust,
                name=f"{row_count}",
                display_name=f"{row[0]}_{row_count}",
                comment=f"New no is {row[1]}, Old no is {row[2]}",
                address=f"新北市{row[3]}",
                device_group=device_group,
                wgs_x=wgs_x,
                wgs_y=wgs_y)
            # assign controller and led
            device.controller = sdController(model=model_ctrl,
                                             cust=cust,
                                             serial_no=str(uuid.uuid4()))
            device.led = sdLed(model=model_led,
                               cust=cust,
                               serial_no=str(uuid.uuid4()))
            # add objects
            db.session.add(device)
            if (row_count % 10000) == 0:
                db.session.commit()
                logger.debug(f"Commit {row_count}")
        db.session.commit()
        logger.debug(f"Total device committed {row_count}")