コード例 #1
0
def fetch_file(current_user):
    if request.method == 'GET':
        logger.info(
            "---------------------- Fetch file api ----------------------")
        try:
            connection = get_db()
            cursor = connection.cursor()
            cursor.execute("select user_id from users where public_id=%s",
                           (current_user[0], ))
            user_id = cursor.fetchone()

            q = request.args.get('q')  # params q as data limit send by user
            if q:
                cursor.execute(
                    "select file_id, file_path, file_name from files_data where user_id=%s order by file_id desc limit %s",
                    (user_id, int(q)))
            else:
                cursor.execute(
                    "select file_id, file_path, file_name from files_data where user_id=%s order by file_id desc",
                    (user_id, ))
            rows = cursor.fetchall()

            resp = jsonify({'files': rows})
            resp.status_code = 201
            return resp
            close_db()
        except Exception as e:
            print(e)
            resp = jsonify({'message': 'Server Error'})
            resp.status_code = 500
            return resp
コード例 #2
0
ファイル: api.py プロジェクト: udkumar/Latest
def login():
    data = request.get_json()
    if not data or not data['user_id'] or not data['password']:
        return make_response(
            'Could not verify', 401,
            {'WWW-Authenticate': 'Basic relm="Login Required!"'})

    connection = get_db()
    cursor = connection.cursor()
    cursor.execute(
        "select u.public_id, u.password, r.role_name from users as u, roles as r where u.user_id=%s and u.role_id=r.role_id",
        (data['user_id'], ))
    user = cursor.fetchone()
    if not user:
        return make_response(
            'Could not verify', 401,
            {'WWW-Authenticate': 'Basic relm="Login Required!"'})

    if check_password_hash(user[1], data['password']):
        token = jwt.encode(
            {
                'public_id': user[0],
                'exp':
                datetime.datetime.utcnow() + datetime.timedelta(minutes=60)
            }, app.config['SECRET_KEY'])
        return jsonify({'token': token.decode('UTF-8'), 'role': user[2]}), 200

    return make_response('Could not verify', 401,
                         {'WWW-Authenticate': 'Basic relm="Login Required!"'})
コード例 #3
0
def new_registration(code):
    connection = get_db()
    cursor = connection.cursor()
    cursor.execute(
        "SELECT email FROM users WHERE verification_code = %s AND email_verified = False",
        (code, ))
    if cursor.fetchone():
        cursor.execute(
            "UPDATE users SET email_verified = True WHERE verification_code = %s",
            (code, ))
    cursor.close()
    connection.commit()
    logger.info("User verified!")
    return jsonify({"message": "Account verified"}), 201
コード例 #4
0
def registration():
    # pdb.set_trace()
    logger.info(
        "---------------------- User registration api ----------------------")
    data = request.get_json(True)
    print(request)
    hashed_password = generate_password_hash(data['password'],
                                             method='pbkdf2:sha256')

    connection = get_db()
    cursor = connection.cursor()
    cursor.execute("select email from users where email=%s", (data['email'], ))

    existing_user = cursor.fetchone()
    if existing_user:
        logger.info("An email address already exists.")
        return jsonify({"message": "An email address already exists."}), 409
    else:
        verification_code = str(uuid.uuid4()).replace("-", "")
        cursor.execute(
            "INSERT INTO users (email, public_id, password, user_name, verification_code) VALUES (%s,%s,%s,%s,%s);",
            (data['email'], str(uuid.uuid4()), hashed_password,
             data['user_name'], verification_code))
        connection.commit()

        print("\nSending email verification .....\n")
        logger.info("Sending email verification")
        headers = {"api-key": '3nXcT1fANr7UYwD5'}
        url = "https://api.sendinblue.com/v2.0/email"
        msg = '''Hello %s,<br/><br/>Thanks for your interest to use the BCS File Conveter web service! <br/>\
		<br/>You need to confirm your email address by opening this link: <a href="http://%s/v1/verifications/%s" >click me</a> \
		<br/><br/>Thanks,<br/>BCS File Conveter web service''' % (
            data['user_name'], be_api_url, verification_code)
        payload = {
            "to": {
                data['email']: ""
            },
            "from": ["*****@*****.**"],
            "subject": "BCS FILE CONVETER - Please verify your email address",
            "html": msg,
        }
        logger.info(msg)
        print(msg)
        resp = requests.post(url, data=json.dumps(payload), headers=headers)
        logger.info("User created!")
        return jsonify({
            "message":
            "Account created, Please check email and confirm your account!"
        }), 201
コード例 #5
0
ファイル: api.py プロジェクト: udkumar/Latest
def fetch_file(current_user):
    if request.method == 'GET':
        connection = get_db()
        cursor = connection.cursor()
        cursor.execute("select u_id from users where public_id=%s",
                       (current_user[0], ))
        user_id = cursor.fetchone()
        role_name = current_user[1]

        cursor.execute("SELECT Videos", (user_id, ))
        rows = cursor.fetchall()

        resp = jsonify({'sources': rows, 'languages': languages})
        resp.status_code = 201
        return resp
        close_db()
コード例 #6
0
 def decorator(*args, **kwargs):
     token = None
     if 'x-access-token' in request.headers:
         token = request.headers['x-access-token']
     logger.info('Token: %s', token)
     if not token:
         return jsonify({"message": "Token is missing!"}), 401
     try:
         data = jwt.decode(token, app.config['SECRET_KEY'])
         connection = get_db()
         cursor = connection.cursor()
         cursor.execute("select public_id from users where public_id=%s",
                        (data['public_id'], ))
         current_user = cursor.fetchone()
     except:
         traceback.print_exc()
         return jsonify({"message": "Token is invalid!"}), 401
     return f(current_user, *args, **kwargs)
コード例 #7
0
def request_reset_password():
    data = request.get_json(True)
    email = data['email']
    logger.info("%s initiated password reset..", email)
    connection = get_db()
    cursor = connection.cursor()
    cursor.execute("SELECT email, email_verified from users WHERE email = %s",
                   (email, ))
    rst = cursor.fetchone()
    if not rst:
        return jsonify({"message": "Email has not yet been registered"}), 401
    else:
        status = rst[1]
        if not True:
            return '{"message":"Your account/email is not verified!"}'

        headers = {"api-key": '3nXcT1fANr7UYwD5'}
        url = "https://api.sendinblue.com/v2.0/email"

        verification_code = randint(100001, 999999)

        msg = '''Hello,<br/><br/>Your request for resetting the password has been recieved. <br/>
		Your temporary password is %s. Use this to create a new password at <a href="%s/resetpassword">link</a> . 

		<br/><br/>Thanks,<br/>BCS File Conveter Web Service''' % \
              (verification_code, be_api_url)
        payload = {
            "to": {
                email: ""
            },
            "from": ["*****@*****.**", "Bridge Engine"],
            "subject": "BCS FILE CONVETER - Password reset verification mail",
            "html": msg,
        }
        logger.info(msg)
        cursor.execute("UPDATE users SET verification_code= %s WHERE email = %s", \
                       (verification_code, email))
        cursor.close()
        connection.commit()
        resp = requests.post(url, data=json.dumps(payload), headers=headers)
        return jsonify({
            "message":
            "Link to reset password has been sent to the registered mail ID"
        }), 201
コード例 #8
0
ファイル: api.py プロジェクト: udkumar/Latest
def upload_file(current_user):
    if request.method == 'POST':
        # logger.info("---------------------- File upload api ----------------------")
        # try:
        pdb.set_trace()

        videoFileName = ""

        subject = request.form.get('subject')
        chapter = request.form.get('chapter')
        video_url = request.form.get('video_url')
        # video_status = request.form.get('video_status')
        class_standard = request.form.get('class_standard')

        videoFilePath = ""
        videoFileType = ""
        if 'selectFile' in request.files:
            file = request.files['selectFile']
            videoFileType = file.filename.split("/")[-1].split(".")[-1]
            combineDir = UPLOAD_FOLDER + '/' + sourceLang + '/'
            source_directory = str(combineDir)
            os.makedirs(os.path.join(source_directory), exist_ok=True)

        connection = get_db()
        cursor = connection.cursor()

        cursor.execute("select u_id from users where public_id=%s",
                       (current_user[0], ))
        userId = cursor.fetchone()
        role_name = current_user[1]

        print("\nuserId:", userId)
        print("\nrole name:", role_name)
        cursor.execute(
            "INSERT INTO videos (file_path, file_type, class_standard, subject, chapter, video_url, u_id) VALUES (%s,%s,%s,%s,%s,%s,%s);",
            (videoFilePath, videoFileType, class_standard, subject, chapter,
             video_url, userId))

        connection.commit()

        resp = jsonify({'message': 'File successfully uploaded'})
        resp.status_code = 201
        return resp
        close_db()
コード例 #9
0
def login():
    logger.info("---------------------- Login api ----------------------")
    data = request.get_json(True)
    logger.info('Email : %s', data['email'])
    if not data or not data['email'] or not data['password']:
        logger.info('Could not verify : data not available')
        return make_response(
            'Could not verify', 401,
            {'WWW-Authenticate': 'Basic relm="Login Required!"'})

    connection = get_db()
    cursor = connection.cursor()
    cursor.execute(
        "select public_id, password, email_verified from users where email=%s",
        (data['email'], ))
    user = cursor.fetchone()
    if not user:
        return make_response(
            'Could not verify', 401,
            {'WWW-Authenticate': 'Basic relm="Login Required!"'})

    if user[2] != True:
        return jsonify({'message': 'Please verify your email!'}), 401

    if check_password_hash(user[1], data['password']):
        token = jwt.encode(
            {
                'public_id': user[0],
                'exp':
                datetime.datetime.utcnow() + datetime.timedelta(hours=24)
            }, app.config['SECRET_KEY'])

        return jsonify({
            'token': token.decode('UTF-8'),
            'verified': user[2]
        }), 200
    else:
        return jsonify({'message': 'Password or email is incorrect!'}), 401

    return make_response('Could not verify', 401,
                         {'WWW-Authenticate': 'Basic relm="Login Required!"'})
コード例 #10
0
def reset_password():
    data = request.get_json(True)

    temp_password = data['temporaryPassword']
    password = data['password']
    connection = get_db()
    cursor = connection.cursor()
    cursor.execute(
        "SELECT email FROM users WHERE verification_code = %s \
		AND email_verified = True", (temp_password, ))
    rst = cursor.fetchone()
    if not rst:
        return jsonify({
            "success": False,
            "message": "Invalid temporary password."
        }), 401
    else:
        email = rst[0]
        hashed_password = generate_password_hash(password,
                                                 method='pbkdf2:sha256')

        cursor.execute(
            "UPDATE users SET verification_code = %s, password = %s \
			WHERE email = %s", (temp_password, hashed_password, email))
        cursor.close()
        connection.commit()
        logger.info("temp password = %s and password = %s given by  %s",
                    temp_password, password, email)

        logger.info("%s changed password successfully ", email)
        return jsonify({
            "success":
            True,
            "message":
            "Password has been reset. Login with the new password."
        }), 201
コード例 #11
0
def convert_file(file_extension, targetType, source_file_path, fileId, userId):

    if file_extension == "usfm" and targetType == "csv":
        target_file_csv = usfm_to_csv(source_file_path)
        # print(target_file)

        target_file_path_1, file_name = os.path.split(target_file_csv)
        connection = get_db()
        cursor = connection.cursor()

        cursor.execute(
            "UPDATE files_data SET target_file_name = %s, file_converted = %s WHERE file_id = %s AND user_id = %s",
            (file_name, True, fileId, userId))
        connection.commit()
        resp = jsonify({'message': 'File successfully converted'})
        resp.status_code = 201
        return resp
        close_db()

    elif file_extension == "CSV" and targetType == "usfm":
        target_file_usfm = csv_to_usfm(source_file_path)
        # print(target_file)

        target_file_path_2, file_name = os.path.split(target_file_usfm)

        cursor.execute(
            "UPDATE files_data SET target_file_name = %s, file_converted = %s WHERE file_id = %s AND user_id = %s",
            (file_name, True, fileId, userId))
        connection.commit()
        resp = jsonify({'message': 'File successfully converted'})
        resp.status_code = 201
        return resp
        # close_db()

    elif file_extension == "html" and targetType == "csv":
        target_file_html_csv = html_to_csv(source_file_path)
        # print(target_file)

        target_file_path_3, file_name = os.path.split(target_file_html_csv)

        cursor.execute(
            "UPDATE files_data SET target_file_name = %s, file_converted = %s WHERE file_id = %s AND user_id = %s",
            (file_name, True, fileId, userId))
        connection.commit()
        resp = jsonify({'message': 'File successfully converted'})
        resp.status_code = 201
        return resp

    elif file_extension == "md" and targetType == "csv":
        target_file_md_csv = md_to_csv(source_file_path)
        # print(target_file)

        target_file_path_4, file_name = os.path.split(target_file_md_csv)
        cursor.execute(
            "UPDATE files_data SET target_file_name = %s, file_converted = %s WHERE file_id = %s AND user_id = %s",
            (file_name, True, fileId, userId))
        connection.commit()
        resp = jsonify({'message': 'File successfully converted'})
        resp.status_code = 201
        return resp

    elif file_extension == "xlsx" and targetType == "txt":
        target_file_xlsx_txt = xlsx_to_txt(source_file_path)
        # print(target_file)

        target_file_path_5, file_name = os.path.split(target_file_xlsx_txt)
        # cursor.execute("UPDATE files_data SET target_file_name = %s, file_converted = %s WHERE file_id = %s AND user_id = %s",(file_name, True, fileId, userId))
        # connection.commit()
        # resp = jsonify({'message': 'File successfully converted'})
        # resp.status_code = 201
        # return resp
        # close_db()
        resp = jsonify({'message': 'File successfully converted'})
        resp.status_code = 201
        return resp
        close_db()

    else:
        resp = jsonify({'message': 'Method is not allowed'})
        resp.status_code = 201
        return resp
コード例 #12
0
def upload_file(current_user):
    if request.method == 'POST':
        logger.info(
            "---------------------- File upload api ----------------------")
        try:
            if 'file' not in request.files:
                resp = jsonify({'message': 'No file part in the request'})
                resp.status_code = 400
                logger.info("No file part in the request")
                return resp
            file = request.files['file']
            if file.filename == '':
                resp = jsonify({'message': 'No file selected for uploading'})
                resp.status_code = 400
                logger.info("No file selected for uploading")
                return resp
            if file and allowed_file(file.filename):
                sourceFileName = secure_filename(file.filename)
                targetType = request.form.get('targetType')
                print(targetType)

                logger.info("Source file : %s", sourceFileName)

                fileType = file.filename.split("/")[-1].split(".")[-1]

                combineDir = UPLOAD_FOLDER + '/' + current_user[0] + '/'
                source_directory = str(combineDir)
                os.makedirs(os.path.join(source_directory), exist_ok=True)

                connection = get_db()
                cursor = connection.cursor()

                cursor.execute("select user_id from users where public_id=%s",
                               (current_user[0], ))
                userId = cursor.fetchone()
                print(userId)

                file.save(os.path.join(source_directory, sourceFileName))
                logger.info("File saved in directory : %s", source_directory)

                sourceFilePath = source_directory

                cursor.execute(
                    "INSERT INTO files_data (file_path, file_name, target_type, user_id) VALUES (%s,%s,%s,%s);",
                    (sourceFilePath, sourceFileName, targetType, userId))
                connection.commit()
                logger.info("Saved source file content in db")

                cursor.execute(
                    "select file_id, file_path from files_data WHERE user_id=%s ORDER BY file_id DESC LIMIT 1",
                    (userId))
                uploaded_file = cursor.fetchone()
                print(uploaded_file)

                fileId = uploaded_file[0]
                print(fileId)

                cursor.execute(
                    "select file_id, file_path, file_name from files_data where user_id=%s and file_id=%s",
                    (userId, fileId))
                selected_file = cursor.fetchone()
                print(selected_file)
                selected_file_name = selected_file[2]
                print(selected_file_name)
                file_extension = selected_file_name.split(".")[-1]
                print(file_extension)
                source_file_path = selected_file[1] + selected_file[2]
                convert_file(file_extension, targetType, source_file_path,
                             fileId, userId)

                # convert_file(fileID,targetType,userID)
                resp = jsonify({
                    'message': 'File converted successfully',
                    'root_path': uploaded_file,
                    'file_name': sourceFileName
                })
                resp.status_code = 201
                return resp
                # close_db()

        except Exception as e:
            print(e)
            logger.info("Exception source: %s", e)
            resp = jsonify({'message': 'Server Error'})
            resp.status_code = 500
            return resp
コード例 #13
0
def upload_file2(current_user):
    if request.method == 'POST':
        logger.info(
            "---------------------- File upload api ----------------------")
        try:
            if 'file' not in request.files:
                resp = jsonify({'message': 'No file part in the request'})
                resp.status_code = 400
                logger.info("No file part in the request")
                return resp
            file = request.files['file']
            if file.filename == '':
                resp = jsonify({'message': 'No file selected for uploading'})
                resp.status_code = 400
                logger.info("No file selected for uploading")
                return resp
            if file and allowed_file(file.filename):
                sourceFileName = secure_filename(file.filename)
                targetType = request.form.get('targetType')

                logger.info("Source file : %s", sourceFileName)

                fileType = file.filename.split("/")[-1].split(".")[-1]

                combineDir = UPLOAD_FOLDER + '/' + current_user[0] + '/'
                source_directory = str(combineDir)
                os.makedirs(os.path.join(source_directory), exist_ok=True)

                connection = get_db()
                cursor = connection.cursor()

                cursor.execute("select user_id from users where public_id=%s",
                               (current_user[0], ))
                userId = cursor.fetchone()

                file.save(os.path.join(source_directory, sourceFileName))
                logger.info("File saved in directory : %s", source_directory)

                sourceFilePath = source_directory

                cursor.execute(
                    "INSERT INTO files_data (file_path, file_name, target_type, user_id) VALUES (%s,%s,%s,%s);",
                    (sourceFilePath, sourceFileName, targetType, userId))
                connection.commit()
                logger.info("Saved source file content in db")

                path = sourceFilePath + sourceFileName

                if fileType == "usfm" and targetType == "csv":
                    target_file_csv = usfm_to_csv(path)
                    # print(target_file)

                    target_file_path_1, file_name = os.path.split(
                        target_file_csv)

                    cursor.execute(
                        "UPDATE files_data SET target_file_name = %s, file_converted = %s WHERE file_id = %s AND user_id = %s",
                        (file_name, True, fileId, userId))
                    connection.commit()
                    resp = jsonify({'message': 'File successfully converted'})
                    resp.status_code = 201
                    return resp
                    close_db()

                elif fileType == "csv" and targetType == "usfm":
                    target_file_usfm = csv_to_usfm(path)
                    # print(target_file)

                    target_file_path_2, file_name = os.path.split(
                        target_file_usfm)

                    cursor.execute(
                        "UPDATE files_data SET target_file_name = %s, file_converted = %s WHERE file_id = %s AND user_id = %s",
                        (file_name, True, fileId, userId))
                    connection.commit()
                    resp = jsonify({'message': 'File successfully converted'})
                    resp.status_code = 201
                    return resp
                    # close_db()

                elif fileType == "html" and targetType == "csv":
                    target_file_html_csv = html_to_csv(path)
                    # print(target_file)

                    target_file_path_3, file_name = os.path.split(
                        target_file_html_csv)

                    cursor.execute(
                        "UPDATE files_data SET target_file_name = %s, file_converted = %s WHERE file_id = %s AND user_id = %s",
                        (file_name, True, fileId, userId))
                    connection.commit()
                    resp = jsonify({'message': 'File successfully converted'})
                    resp.status_code = 201
                    return resp

                elif fileType == "md" and targetType == "csv":
                    target_file_md_csv = md_to_csv(path)
                    # print(target_file)

                    target_file_path_4, file_name = os.path.split(
                        target_file_md_csv)
                    cursor.execute(
                        "UPDATE files_data SET target_file_name = %s, file_converted = %s WHERE file_id = %s AND user_id = %s",
                        (file_name, True, fileId, userId))
                    connection.commit()
                    resp = jsonify({'message': 'File successfully converted'})
                    resp.status_code = 201
                    return resp

                elif fileType == "xlsx" and targetType == "txt":
                    target_file_xlsx_txt = xlsx_to_txt(path)
                    # print(target_file)

                    target_file_path_5, file_name = os.path.split(
                        target_file_xlsx_txt)
                    # cursor.execute("UPDATE files_data SET target_file_name = %s, file_converted = %s WHERE file_id = %s AND user_id = %s",(file_name, True, fileId, userId))
                    # connection.commit()
                    # resp = jsonify({'message': 'File successfully converted'})
                    # resp.status_code = 201
                    # return resp
                    # close_db()
                    resp = jsonify({'message': 'File successfully converted'})
                    resp.status_code = 201
                    return resp
                    close_db()

                else:
                    resp = jsonify({'message': 'Method is not allowed'})
                    resp.status_code = 201
                    return resp

            # resp = jsonify({'message': 'File successfully converted', 'root_path':uploaded_file, 'file_name': sourceFileName})
            resp = jsonify({'message': 'File successfully converted'})
            resp.status_code = 201
            return resp
            close_db()

        except Exception as e:
            print(e)
            logger.info("Exception source: %s", e)
            resp = jsonify({'message': 'Server Error'})
            resp.status_code = 500
            return resp
コード例 #14
0
def convert_file(current_user):
    if request.method == 'POST':
        logger.info(
            "---------------------- File converter api ----------------------")
        connection = get_db()
        cursor = connection.cursor()

        cursor.execute("select user_id from users where public_id=%s",
                       (current_user[0], ))
        userId = cursor.fetchone()

        fileId = request.form.get('file_id')
        targetType = request.form.get('target_type')
        print(targetType)

        cursor.execute(
            "select file_id, file_path, file_name from files_data where user_id=%s and file_id=%s",
            (userId, fileId))
        selected_file = cursor.fetchone()
        print(selected_file)
        selected_file_name = selected_file[2]
        print(selected_file_name)
        file_extension = selected_file_name.split(".")[-1]
        print(file_extension)

        source_file_path = selected_file[1] + selected_file[2]

        if file_extension == "usfm" and targetType == "csv":
            target_file_csv = usfm_to_csv(source_file_path)
            # print(target_file)

            target_file_path_1, file_name = os.path.split(target_file_csv)

            cursor.execute(
                "UPDATE files_data SET target_file_name = %s, file_converted = %s WHERE file_id = %s AND user_id = %s",
                (file_name, True, fileId, userId))
            connection.commit()
            resp = jsonify({'message': 'File successfully converted'})
            resp.status_code = 201
            return resp
            close_db()

        elif file_extension == "csv" and targetType == "usfm":
            target_file_usfm = csv_to_usfm(source_file_path)
            # print(target_file)

            target_file_path_2, file_name = os.path.split(target_file_usfm)

            cursor.execute(
                "UPDATE files_data SET target_file_name = %s, file_converted = %s WHERE file_id = %s AND user_id = %s",
                (file_name, True, fileId, userId))
            connection.commit()
            resp = jsonify({'message': 'File successfully converted'})
            resp.status_code = 201
            return resp
            # close_db()

        elif file_extension == "html" and targetType == "csv":
            target_file_html_csv = html_to_csv(source_file_path)
            # print(target_file)

            target_file_path_3, file_name = os.path.split(target_file_html_csv)

            cursor.execute(
                "UPDATE files_data SET target_file_name = %s, file_converted = %s WHERE file_id = %s AND user_id = %s",
                (file_name, True, fileId, userId))
            connection.commit()
            resp = jsonify({'message': 'File successfully converted'})
            resp.status_code = 201
            return resp

        elif file_extension == "md" and targetType == "csv":
            target_file_md_csv = md_to_csv(source_file_path)
            # print(target_file)

            target_file_path_4, file_name = os.path.split(target_file_md_csv)
            cursor.execute(
                "UPDATE files_data SET target_file_name = %s, file_converted = %s WHERE file_id = %s AND user_id = %s",
                (file_name, True, fileId, userId))
            connection.commit()
            resp = jsonify({'message': 'File successfully converted'})
            resp.status_code = 201
            return resp

        elif file_extension == "xlsx" and targetType == "txt":
            target_file_xlsx_txt = xlsx_to_txt(source_file_path)
            # print(target_file)

            target_file_path_5, file_name = os.path.split(target_file_xlsx_txt)
            cursor.execute(
                "UPDATE files_data SET target_file_name = %s, file_converted = %s WHERE file_id = %s AND user_id = %s",
                (file_name, True, fileId, userId))
            connection.commit()
            # resp = jsonify({'message': 'File successfully converted'})
            # resp.status_code = 201
            # return resp
            # close_db()
            resp = jsonify({'message': 'File successfully converted'})
            resp.status_code = 201
            return resp
            close_db()

        else:
            resp = jsonify({'message': 'Method is not allowed'})
            resp.status_code = 201
            return resp
コード例 #15
0
ファイル: api.py プロジェクト: udkumar/Latest
def registration():
    headers = request.headers
    req_from_faculty = headers.get("X-Faculty")
    if req_from_faculty == "userAsFaculty":
        data = request.get_json()
        print(data)
        connection = get_db()
        cursor = connection.cursor()

        cursor.execute("select email from users where email=%s",
                       (data['email'], ))

        existing_user = cursor.fetchone()
        if existing_user:
            return jsonify({"message": "A email address already exists."}), 409
        else:
            data['role_id'] = "2"

            auto_user_id = random.randrange(100000, 999999)
            auto_user_id = str(auto_user_id)
            print("user_id", auto_user_id)
            auto_password = random.randrange(100000, 999999)
            string_pass = str(auto_password)
            print("pass: "******"INSERT INTO users (public_id, user_id, email, alternet_email, password, first_name, last_name, mobile_number, city, class_std, subject, edu_board, role_id) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);",
                (str(uuid.uuid4()), auto_user_id, data['email'],
                 data['alternet_email'], hashed_password, data['firstName'],
                 data['lastName'], data['mobile'], data['city'],
                 data['class_std'], data['subject'], data['edu_board'],
                 data['role_id']))

            connection.commit()
            print("Faculty added...")
        return jsonify({"message": "Faculty created!"}), 201
    else:
        data = request.get_json()

        connection = get_db()
        cursor = connection.cursor()
        cursor.execute("select email from users where email=%s",
                       (data['email'], ))

        existing_user = cursor.fetchone()
        if existing_user:
            return jsonify({"message": "A email address already exists."}), 409
        else:
            data['role_id'] = "1"

            auto_user_id = random.randrange(100000, 999999)
            auto_user_id = str(auto_user_id)
            print("user_id", auto_user_id)

            auto_password = random.randrange(100000, 999999)
            string_pass = str(auto_password)
            print("pass: "******"INSERT INTO users (public_id, user_id, email, alternet_email, password, first_name, last_name, mobile_number, city, class_std, subject, edu_board, role_id) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);",
                (str(uuid.uuid4()), auto_user_id, data['email'],
                 data['alternet_email'], hashed_password, data['firstName'],
                 data['lastName'], data['mobile'], data['city'],
                 data['class_std'], data['subject'], data['edu_board'],
                 data['role_id']))

            connection.commit()

            # Send email as credential
            msg = Message(subject='MAIIC Login details...',
                          recipients=[student_email])
            msg.html = "Hello <strong>{}</strong>, <p>Your login details are: <br>Student ID = {}, Password = {}</p><br>Click here to login: <a href='http://maiiceducation.com/'>http://maiiceducation.com/</a>".format(
                first_name, auto_user_id, string_pass)
            mail.send(msg)
            print("user added...")
        return jsonify({"message": "Student created!"}), 201