Ejemplo n.º 1
0
def send_email(username):
    if request.method == 'POST':
        mailaddr = apiDB.getEmail(username)
        print(username)
        print(mailaddr)
        mailkey = URLSafeTimedSerializer(
            'blowfish'
        )  #TODO move this to a secure position (encrypted perhaps)
        token = mailkey.dumps(username, salt='email-confirm')
        sendMail(
            'Verification Code', mailaddr,
            "<a href=http://127.0.0.1:3864/confirm_email/" + token +
            ">Follow this link for account activation</a>")
        apiLog.logInfo("Sent email verification to {}".format(mailaddr))
        return flask.jsonify(
            json.dumps({
                "Success": True,
                "Status": 'Sent verification code'
            })), 200
    else:
        apiLog.logError("Failed to send email verification")
        return flask.jsonify(
            json.dumps({
                "Success": False,
                "Status": 'Failed to send verification code'
            })), 400
Ejemplo n.º 2
0
def register(
        username,
        password,
        email="",
        role="Client"):  #for testing can be used for searching as it's dict
    Userjson = readJsonDict(userPath)
    if username in Userjson:
        return {"Success": False, "Error": "Username in use"}

    if email == "":
        return {"Success": False, "Error": "email missing"}

    hashedpassword = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt())
    Userjson[username] = {
        "password": hashedpassword.decode('UTF-8'),
        "role": role,
        "email": email,
        "emailVerify": False
    }
    writeJson(userPath, Userjson)
    apiLog.logInfo('Registered user, username: {} email: {} role: {}'.format(
        username, email, role))
    return {
        "Success": True,
        "username": username,
        "password": hashedpassword.decode('UTF-8'),
        "role": role,
        "email": email,
        "emailVerify": False
    }
Ejemplo n.º 3
0
def requestPermission(username, role):
    PermJson = readJsonDict(PermPath)
    requestRole = {"username": username, "role": role}
    PermJson[username] = role
    writeJson(PermPath, PermJson)
    apiLog.logInfo('Permission requested, username: {} role: {}'.format(
        username, role))
    return requestRole
Ejemplo n.º 4
0
def processData():
	response = checkJWT(request.headers["JWT"])
	username = response["username"] 
    #TODO check the jwt (DONE)
	if allowAccess(['Staff','Permission_Admin'],request) == True:
	    Data = apiDB.MenuUser()
	    apiLog.logInfo("{} accessed database".format(username))
        #TODO record log
	    return flask.jsonify(json.dumps(Data)),200
Ejemplo n.º 5
0
def grantPermission():
    if allowAccess(['Permission_Admin'], request) == False:
        apiLog.logWarn("{} attmepted to grant permission")
        return flask.jsonify({"Success": False, "Error": "No Permission"})
    result = checkJWT(request.headers["JWT"])
    username = result["username"]
    content = request.data.decode("UTF-8")
    #TODO check the username and the corresponding role to the dictionary then grant permission
    apiLog.logInfo("Permission granted by {}".format(username))
    return flask.jsonify(json.loads("{'Success':True}"))
Ejemplo n.º 6
0
def confirm_email(token):
    try:
        mailkey = URLSafeTimedSerializer(
            'blowfish'
        )  #TODO move this to a secure position (encrypted perhaps)
        username = mailkey.loads(token, salt='email-confirm')
        #TODO a request that changes emailVerify boolean to true and compare username to database
        apiLog.logInfo("Email verified for {}".format(username))
        return redirect('https://localhost:5000/login')
    except Exception:
        apiLog.logWarn("Email verification failed")
        return 'The token does not match'
Ejemplo n.º 7
0
def login():
    LoginUser = request.data.decode("UTF-8")
    try:
        #LoginUser = decryption(LoginUser,request.headers['id'])
        LoginUser = json.loads(LoginUser)
    except:
        return flask.jsonify(
            json.dumps({
                "Success": False,
                "Error": "Error Content"
            })), 400

    print(LoginUser)
    username = ""
    password = ""
    try:
        username = LoginUser["username"]
        password = LoginUser["password"]
    except:
        return flask.jsonify({
            "Success": False,
            "Error": "Error Content Unfound"
        }), 400

    try:
        #TODO check username and check password
        response = apiDB.login(username, password)
        if response["Success"] == False:
            return flask.jsonify(json.dumps(response)), 400
        #TODO if true to one time password(send email)
        emailaddr = apiDB.getEmail(username)
        #print({"Success":True, "Status":"One Time Password", "Username":username})
        mailkey = URLSafeTimedSerializer(
            'onetimeblow'
        )  #TODO move this to a secure position (encrypted perhaps)
        otp = mailkey.dumps(username, salt='oneblowfish')
        sendMail('One Time Passcode', emailaddr, "Please use this OTP: " + otp)
        apiLog.logInfo('Login {} {}'.format(username, True))
        return flask.jsonify(
            json.dumps({
                "Success": True,
                "Status": "One Time Password",
                "Username": username
            })), 200
    except Exception as e:
        print(e)
        apiLog.logWarn('Login {} {}'.format(username, False))
        return flask.jsonify(
            json.dumps({
                "Success": False,
                "Error": "Error Unknown"
            })), 400
Ejemplo n.º 8
0
def login(username, password):
    UserJson = readJsonDict(userPath)
    if username in UserJson:
        temp = UserJson[username]
        if bcrypt.checkpw(password.encode('UTF-8'),
                          temp["password"].encode('UTF-8')):
            apiLog.logInfo('Login {} {}'.format(username, True))
            return {"Success": True}
        else:
            apiLog.logWarn('Login {} {}'.format(username, False))
            return {"Success": False, "Error": "Password Incorrect"}
    else:
        apiLog.logWarn("Login unknown {}".format(False))
        return {"Success": False, "Error": "Username does not exist"}
Ejemplo n.º 9
0
def processData():
    response = checkJWT(request.headers["JWT"])
    username = response["username"]
    #TODO check the jwt (DONE)
    if allowAccess(['Staff', 'Permission_Admin'], request) == True:
        Data = apiDB.MenuUser()
        apiLog.logInfo("{} accessed database".format(username))
        #TODO record log
        return flask.jsonify(Data), 200
    elif allowAccess(['Client'], request) == True:
        Data = {}
        Data[username] = username
        return flask.jsonify(Data), 200
    else:
        apiLog.logError("{} raised {}".format(username, response["Error"]))
        return flask.jsonify(response), 400
Ejemplo n.º 10
0
def getData(patientusername):
    #TODO check jwt check role
    response = checkJWT(request.headers["JWT"])
    if response["Success"] == False:
        apiLog.logError(response["Error"])
        return flask.jsonify(response), 400

    username = response["username"]
    role = apiDB.getrole(username)
    if role == "Client" and patientusername != username:
        apiLog.logWarn("{} unauthorized access".format(username))
        return "unauthorized access", 400

    User = apiDB.getUser(patientusername)
    if User == False:
        return "No Such user", 400
    apiLog.logInfo("{} accessed {}'s data".format(username, patientusername))
    return flask.jsonify(User), 200
Ejemplo n.º 11
0
def requestPermission(role, usernameT):

    #TODO check jwt
    if allowAccess(['Staff', 'Permission_Admin', 'Client'],
                   request) == True:  #DO ADMIN HAVE TO REQUEST PERMISSION?
        response = checkJWT(request.headers["JWT"])
        username = response["username"]
        #TODO compare to the username
        #result = checkJWT(request.headers["JWT"])
        #if result["Success"] == True and result["username"]==currentusername:
        if username == usernameT:
            apiLog.logInfo(
                'Permission requested, username: {} role: {}'.format(
                    username, role))
            return flask.jsonify(apiDB.requestPermission(username, role))
        return flask.jsonify(
            json.loads("{'Success':False,'Error':Incorrect username}"))
    apiLog.logWarn("{} has Incorrect JWT".format(username))
    return 'JWT Incorrect'
Ejemplo n.º 12
0
def register():
    try:
        NewUser = decryption(request.data.decode("UTF-8"),
                             request.headers["id"])
        NewUser = json.loads(NewUser)
        username = NewUser['username']
        password = NewUser['password']
        email = NewUser['email']
        #TODO check username
        #TODO check password
        response = apiDB.register(username, password, email=email)
        if response["Success"] == False:
            return response["Error"], 400
        apiLog.logInfo(
            'Registered user, username: {} email: {} role: Client'.format(
                username, email))
        return flask.jsonify(json.dumps(response)), 200
    except Exception as e:
        print(e)
        return 'Error', 400
Ejemplo n.º 13
0
def getData(patientusername):
	response = checkJWT(request.headers["JWT"])
	username = response["username"]
    #TODO check jwt check role
	if allowAccess(['Staff','Permission_Admin','Client'],request) == True:
		if patientusername != username:
			apiLog.logWarn("{} unauthorized access".format(username))
			return flask.jsonify(json.dumps(response["Error"])),400
    #response = checkJWT(request.headers["JWT"])
    #if response["Success"] == False:
        #apiLog.logError(response["Error"])
        #return flask.jsonify(json.dumps(response)),400
    #username = response["username"]
    #role = apiDB.getrole(username)
    #if role == "Client" and patientusername != username:
        #apiLog.logWarn("{} unauthorized access".format(username))
        #return flask.jsonify(json.dumps(response["Error"])),400
		User = apiDB.getUser(patientusername)
		print(User)
		apiLog.logInfo("{} accessed {}'s data".format(username, patientusername))
		return flask.jsonify(json.dumps(User)),200
	else:
		apiLog.logError(response["Error"])
		return flask.jsonify(json.dumps(response)),400
Ejemplo n.º 14
0
def OneTimeCode(passcode):
    try:
        mailkey = URLSafeTimedSerializer(
            'onetimeblow'
        )  #TODO move this to a secure position (encrypted perhaps)
        username = mailkey.loads(passcode, salt='oneblowfish', max_age=180)
        print(
            username
        )  #TODO a request that changes emailVerify boolean to true and compare username to database
        apiDB.emailVerify(username)
        apiLog.logInfo("OTP verified for {}".format(username))
        return flask.jsonify(
            json.dumps({
                "Success": True,
                "Status": 'Passed OTP',
                "JWT": str(issueJWT(username).decode("UTF-8"))
            })), 200
    except Exception as e:
        print(e)
        apiLog.logError("Failed to verify OTP")
        return flask.jsonify(json.dumps({
            "Success": False,
            "Status": str(e)
        })), 400
Ejemplo n.º 15
0
def listPermission():
    if allowAccess(['Permission_Admin'], request) == True:
        apiLog.logInfo("Admin request to list all permissions")
        return flask.jsonify(apiDB.listPermission())
    apiLog.logWarn("{} attempted to list permissions".format(""))
    return 'Error'