コード例 #1
0
def login():
    # Clear any active session.
    session.clear()

    # Check if whm.db exists - redirect if not.
    if not os.path.exists(os.path.join(os.path.abspath(os.path.dirname(__file__)), "whm.db")):
        return render_template("init.html")

    # Attempt login.
    if request.method == "POST":

        # Ensure form completion.
        if not request.form.get("password") or not request.form.get("username"):
            return jsonify({
                'success': False,
                'details': "Missing username and/or password."
            })

        # Make sure input is safe for SQL.
        if not validate_sql(request.form.get("username")):
            return jsonify({
                'success': False,
                'details': "Unallowed characters enters."
            })

        # Pull user info from DB.
        selection = users.getUser("username", request.form.get("username"))

        # Validate credentials.
        if not selection['return'] or not pwd_context.verify(request.form.get("password"), selection['user'][2]):
            return jsonify({
                'success': False,
                'details': "Bad username and/or password"
            })

        # Set session variables.
        session["user_id"] = selection['user'][0]
        session["username"] = selection['user'][1]
        update_return = update_session_vars()   # vars that may be dynamic
        # Check if session vars updated successfully.
        if not update_return['success']:
            return jsonify({
                'return': False,
                'details': "User logged in but there was an issue loading session variables."
            })


        # Setup logging for this user.
        session["logger"] = Logger(session["username"], "WebApp");
        session["logger"].write(session["username"] + " logged in.")

        # Success
        return jsonify({
            'success': True,
            'details': "Session granted."
        })

    else:
        # GET request, return template.
        return render_template("login.html")
コード例 #2
0
ファイル: 99_puzzles.py プロジェクト: samr85/99puzzles
    def getUser(self, create=False):
        userName = self.get_secure_cookie(
            "user", max_age_days=36524)  # Must specify a max_age... 100 years
        if not userName:
            if create:
                userName = ("%06x" % (random.randint(1, 0xffffff))).encode()
                self.set_secure_cookie("user", userName, expires_days=100)
            else:
                return users.getNullUser()

        return users.getUser(userName)
コード例 #3
0
ファイル: app.py プロジェクト: ZacharyBys/rudating
def retrieveUser():
    id = request.args.get('id')

    result = getUser(int(id))

    if result == -1:
        return json.dumps({'success': False}), 400, {
            'ContentType': 'application/json'
        }
    else:
        return json.dumps(result), 200, {'ContentType': 'application/json'}
コード例 #4
0
ファイル: 99_puzzles.py プロジェクト: samr85/99puzzles
    def post(self):
        newName = self.get_body_argument("username")
        password = self.get_body_argument("password")
        confirmPassword = self.get_body_argument("confirmPassword")
        if password != confirmPassword:
            return self.renderPage(
                "password and confirmed password do not match!")

        userName = self.get_secure_cookie(
            "user", max_age_days=36524)  # Must specify a max_age... 100 years
        if not userName:
            userName = "******" % (random.randint(1, 0xffffff))
            self.set_secure_cookie("user", userName, expires_days=None)
        user = users.getUser(userName)
        ret = user.nameUser(newName, password)
        if ret:
            self.set_secure_cookie("user", newName, expires_days=None)
            return self.redirect("/")
        return self.renderPage("Username %s already exists" % (userName))
コード例 #5
0
ファイル: app.py プロジェクト: ZacharyBys/rudating
def activate():
    id = request.args.get('id')
    print('incoming id: {}'.format(id))
    result = activateUser(int(id), True)

    if result == -1:
        return json.dumps({'success': False}), 400, {
            'ContentType': 'application/json'
        }
    else:
        user = getUser(int(id))
        global activeUsers
        activeUsers.append(user)
        handleSearch()

        # if searchResult is not None:
        #     join_room(searchResult[2], searchResult[0], namespace=None)
        #     join_room(searchResult[2], searchResult[1], namespace=None)

        return json.dumps({'success': True}), 200, {
            'ContentType': 'application/json'
        }
コード例 #6
0
def query(data):
	try:
		asker, usern, passw, task, param = data.split(".")
		params = param.split(",")
		if asker == 'u' and users.authUser(usern,passw): pass
		elif asker == 'a' and admins.authAdmin(usern,passw): pass
		elif task != 'register_user' and task != 'forgot_pass_verify' and task != 'forgot_pass': return ['error', 'Authentication invalid']
	except:
		return ['error', 'improper API format']

	# P : 1
	if task == 'get_user_details':
		if asker == 'u':
			return users.secureData(users.getUser('username',usern)[0])
		elif asker == 'a':
			if 1 in admins.getPerm(usern):
				if len(params[0]) == 0:
					return admins.secureData(admins.getAdmin('username',usern)[0])
				try:
					return [users.secureData(i) for i in users.getUser(params[0],params[1])]
				except:
					return ['error', 'parameters invalid']
			else:
				return ['error', 'Permission denied']

	# P : None
	if task == 'get_all_hotels':
		return [hotel.secureData(i) for i in hotel.getAllHotels()]

	# P : None
	if task == 'get_hotel_by_id':
		return [hotel.secureData(i) for i in hotel.getHotel('id',params[0])]

	# P : None
	if task == 'forgot_pass' and asker == 'u':
		return [users.secQue(usern)]

	# P : None
	if task == 'forgot_pass_verify' and asker == 'u':
		return [users.verSecAns(usern, params[0])]

	# P : None
	if task == 'register_user':
		data = {}
		if len(params) < 8:
			return ['registration failed']
		data['username'] = params[0]
		data['password'] = params[1]
		data['fname'] = params[2]
		data['lname'] = params[3]
		data['gender'] = params[4]
		data['mobile'] = params[5]
		data['secque'] = params[6]
		data['secans'] = params[7]
		if users.addUser(data):
			return ['successful registration']
		else:
			return ['registration failed']

	# P : None
	if task == 'availability':
		if len(params) < 15:
			return ['error', 'parameters invalid']
		return [reserve.possibleReservation(params[0:3],params[3:9],params[9:15])]

	# P : None
	if task == 'make_reservation':
		data = {}
		if len(params) < 20:
			return ['reservation failed']
		if asker == 'u':
			data['by'] = ['u', users.getUser('username',usern)[0]['id']]
		else:
			data['by'] = ['a', admins.getAdmin('username',usern)[0]['id']]
		data['what'] = params[0:3]
		data['from'] = params[3:9]
		data['to'] = params[9:15]
		data['booking_time'] = datetime.datetime.now()
		data['confirmed'] = 'False'
		data['ended'] = 'False'
		data['comments'] = params[15]
		data['total_amount'] = params[16]
		data['quantity'] = params[17]
		data['reason'] = params[18]
		data['other'] = params[19]
		if reserve.addReservation(data):
			return ['successful reservation']
		else:
			return ['reservation failed']

	# P : 2
	if task == 'get_user_bookings':
		if asker == 'u':
			return reserve.getReservation("by", ['u', users.getUser('username',usern)[0]['id']])
		elif asker == 'a':
			if 2 in admins.getPerm(usern):
				if len(params[0]) == 0:
					return reserve.getReservation("by", ['a', admins.getAdmin('username',usern)[0]['id']])
				try:
					return reserve.getReservation("by", ['u', users.getUser(params[0],params[1])[0]['id']])
				except:
					return ['error', 'parameters invalid']
			else:
				return ['error', 'Permission denied']

	# P : None
	if task == 'get_allbookings_of' and asker == 'a':
		data = reserve.getAllReservations()
		if len(params[0]) == 0:
			return data
		elif len(params) == 1:
			return [i for i in data if i['what'][0] == params[0]]
		elif len(params) == 2:
			return [i for i in data if (i['what'][0] == params[0]) and (i['what'][1] == params[1])]
		elif len(params) == 3:
			return [i for i in data if (i['what'][0] == params[0]) and (i['what'][1] == params[1]) and (i['what'][2] == params[2])]
		return ['error', 'parameters invalid']

	# P : None
	if task == 'mark_reservation' and asker == 'a':
		if len(params) < 2:
			return ['error', 'parameters invalid']
		data = reserve.changeReservation(params[0],params[1])
		return [data]

	# P : None
	if task == 'get_all_users' and asker == 'a':
		data = [users.secureData(i) for i in users.getAllUsers()]
		return data

	return ['successful login']
コード例 #7
0
ファイル: app.py プロジェクト: harshit-budhraja/codechef-api
def User(handle):
    x = getUser(handle)
    return jsonify(result=x)
コード例 #8
0
ファイル: webApp.py プロジェクト: Xariec/FleetCMD
 def GET(self):
     return JSONEncoder().encode(users.getUser())
コード例 #9
0
def register():
    # Clear any active sesssion.
    session.clear()

    # Check if whm.db exists - redirect if not.
    if not os.path.exists(os.path.join(os.path.abspath(os.path.dirname(__file__)), "whm.db")):
        return render_template("init.html")

    # POST - Incoming user registration request.
    if request.method == "POST":
        # Load form data.
        user_request = [
            request.form.get("username"),
            request.form.get("password"),
            request.form.get("first"),
            request.form.get("last"),
            request.form.get("email"),
            request.form.get("phone")
        ]

        # Log event.
        logger.write("Registration attempt: " + str(user_request[0]) + " {pw} " + str(user_request[2:]))

        # Verify complete fields and safe sql.
        for i in range(len(user_request)):
            if not len(user_request[i]) > 0:
                return jsonify({
                    'accepted': False,
                    'details': "One or more fields are empty."
                })
            if not validate_sql(user_request[i]) and i != 1:
                return jsonify({
                    'accepted': False,
                    'details': "Unallowed characters enters."
                })

        # Check if username is in use.
        if users.getUser("username", user_request[0])["return"]:
            return jsonify({
                'accepted': False,
                'details': "Username is already taken. Please try another."
            })

        # Check if username has already been requested.
        if not len(to_sql("SELECT * FROM requests WHERE username = '******'", "r", "whm.db")['details']) == 0:
            return jsonify({
                'accepted': False,
                'details': "Username is already requested. Please try another."
            })

        # Validate password.
        user_request[1] = pwd_context.hash(user_request[1])
        if not pwd_context.verify(request.form.get("vpassword"), user_request[1]):
            return jsonify({
                'accepted': False,
                'details': "Passwords don't match."
            })

        # Attempt to add request to db.
        if not to_sql("INSERT INTO requests VALUES (NULL, " + str(user_request)[1:-1] + ");", "w", "whm.db")['success']:
            return jsonify({
                'accepted': False,
                'details': "Entries were validate, but adding the request to the database failed."
            })

        # All inputs are valid and write to database was successful.
        logger.write("Request submitted")
        return jsonify({
            'accepted': True,
            'details': "Request was submitted to the database."
        })

    else:
        # GET request, return template.
        return render_template("register.html")
コード例 #10
0
def settings():
    if request.method == "POST":
        if request.form.get('action') in ["update", "other_update"]:
            # Update user information. other_update specifies updating another users info and requires admin rights.
            if request.form.get('action') == "other_update":
                if not session['admin']:
                    # Non-admin tried to update another users' info. Log and deny access.
                    session['logger'].write("Non-admin tried: " + request.form.get('action'))
                    return jsonify({
                        'return': False,
                        'details': "Unauthorized Access"
                    })
                # Other user is being updated by admin - Remember subject user id.
                user_id = request.form.get('user_id')
            else:
                # User is updating their own info.
                # If a new password is provided, ensure current password was entered and is correct. Duel password entry is ensured on client side.
                if request.form.get('npassword'):
                    selection = users.getUser("user_id", session["user_id"])
                    if not selection['return'] or not pwd_context.verify(request.form.get("password"), selection['user'][2]):
                        return jsonify({
                            'return': False,
                            'details': "Incorrect current password entered."
                        })

                # Proceed with update request, remember subject (current) user id.
                user_id = session['user_id']

            # Store new password as a hash if provided, otherwise it hash will be stored as an empty string.
            if request.form.get('npassword'):
                newHash = pwd_context.hash(request.form.get('npassword'))
            else:
                newHash = ""

            # This holds the user id to update and everything that can be updated. Empty strings indicate fields that should remain unchanced.
            update_bundle = [
                user_id,
                newHash,
                request.form.get('first'),
                request.form.get('last'),
                request.form.get('email'),
                request.form.get('phone')
            ]

            # Attempt to update though users' update handler.
            result = users.updateUser(update_bundle)

            if result['return'] == True:
                # Update was successful - Log and return.
                update_return = update_session_vars()
                # Check if session vars updated successfully.
                if not update_return['success']:
                    return jsonify({
                        'return': False,
                        'details': "User information updated, but there was an issue reading the updated info."
                    })
                session['logger'].write("Update with info: " + str(update_bundle))
                return jsonify({
                    'return': True,
                    'details': "User information updated."
                })
            else:
                # Update was unsuccessful - Log and return edetails.
                session['logger'].write("Failed to update with info: " + str(update_bundle))
                return jsonify(result)

        # Settings actions below this point require admin rights. Ensure privilege before moving forward.
        if not session['admin']:
            session['logger'].write("Non-admin tried: " + request.form.get('action'))
            return jsonify({
                'return': False,
                'details': "Session by admin required"
            })

        # Returns a table of users or requested users.
        if request.form.get('action') == "get_table":
            # Validate requested table.
            if not request.form.get("table") in ["users", "requests"]:
                return jsonify({
                    'reported': False,
                    'details': "Invalide table"
                })
            # Get and return data.
            return jsonify({
                'reported': True,
                'lines': users.getUsers(group=request.form.get("table"))
            })

        # Returns the current log settings.
        if request.form.get('action') == "get_config":
            return jsonify(get_config('whm.cfg'))

        # Sets log settings
        if request.form.get('action') == "set_config":
            if request.form.get('section') == "log":
                # Load defaults from backup config if defaults are requested, or load settings from the form.
                if int(request.form.get('logs_default_flag')) == 1:
                    settings = get_config('whm.cfg.bak')
                    # Ensure backup config was loaded.
                    if not settings['return']:
                        session['logger'].write(settings['details'])
                        return jsonify(settings)
                else:
                    settings = {
                        'max_log_size': request.form.get('max_size'),
                        'max_log_age_unit': request.form.get('max_age_unit'),
                        'max_log_age_n': request.form.get('max_age_n'),
                        'user_str_len': request.form.get('usr_len'),
                        'source_str_len': request.form.get('src_len')
                    }

                # Ensure max_log_size is within range. Errors may occur outside of this range.
                if settings['max_log_size']:
                    try:
                        x = int(settings['max_log_size'])
                        if not 5000 <= x <= 1000000000:
                            raise Exception()
                    except:
                        return jsonify({
                            'return': False,
                            'details': "Invalid Maximum Log File Size"
                        })

                # Ensure valid age unit.
                if not settings['max_log_age_unit'] in ['minutes', 'hours', 'days', 'weeks']:
                    return jsonify({
                        'return': False,
                        'details': "Invalid Maximum Archive Age Unit"
                    })

                # Ensure age is a non-neg whole number.
                if settings['max_log_age_n']:
                    try:
                        x = int(settings['max_log_age_n'])
                        if not 0 <= x:
                            raise Exception()
                    except:
                        return jsonify({
                            'return': False,
                            'details': "Invalid Maximum Archive Age"
                        })

                # Ensure user_str_len is in acceptable range.
                if settings['user_str_len']:
                    try:
                        x = int(settings['user_str_len'])
                        if not 0 <= x <= 50:
                            raise Exception()
                    except:
                        return jsonify({
                            'return': False,
                            'details': "Invalid User Length"
                        })

                # Ensure source_str_len is in acceptable range.
                if settings['source_str_len']:
                    try:
                        x = int(settings['source_str_len'])
                        if not 0 <= x <= 50:
                            raise Exception()
                    except:
                        return jsonify({
                            'return': False,
                            'details': "Invalid Source Length"
                        })

                # Attempt to write each setting to config.
                try:
                    config = configparser.RawConfigParser()
                    config.read('whm.cfg')
                    for var in ['max_log_size', 'max_log_age_unit', 'max_log_age_n', 'user_str_len', 'source_str_len']:
                        if settings[var]:
                            config.set('logger', var, settings[var])
                    with open('whm.cfg', 'w') as configfile:
                        config.write(configfile)
                except:
                    return jsonify({
                        'return': False,
                        'details': "Failed to write config."
                    })

                # Log and return success.
                session["logger"].write("Log config changed")
                return jsonify({
                    'return': True,
                    'details': "Function ran with no errors."
                })

		    # Sets record settings
            if request.form.get('section') == "record":
                # Load defaults from backup config if defaults are requested, or load settings from the form.
                if int(request.form.get('record_default_flag')) == 1:
                    settings = get_config('whm.cfg.bak')
                    if not settings['return']:
                        # Ensure backup config was loaded.
                        session['logger'].write(settings['details'])
                        return jsonify(settings)
                else:
                    settings = {
                        'hours_age_max': request.form.get('record_hours'),
                        'days_age_max': request.form.get('record_days'),
                        'weeks_age_max': request.form.get('record_weeks')
                    }

                # Ensure all fields are whole numbers between 0 and 500.
                for field in ['hours_age_max', 'days_age_max', 'weeks_age_max']:
                    if settings[field]:
                        try:
                            x = int(settings[field])
                            if not 0 <= x <= 500:
                                raise Exception()
                        except:
                            return jsonify({
                                'return': False,
                                'details': "Values must be whole numbers between 0 and 500."
                            })

                # Attempt to write each setting to config.
                try:
                    config = configparser.RawConfigParser()
                    config.read('whm.cfg')
                    for var in ['hours_age_max', 'days_age_max', 'weeks_age_max']:
                        if settings[var]:
                            config.set('record', var, settings[var])
                    with open('whm.cfg', 'w') as configfile:
                        config.write(configfile)
                    # Load new config settings
                    load_record_conf()
                except:
                    return jsonify({
                        'return': False,
                        'details': "Failed to write config."
                    })

                # Log and return success.
                session["logger"].write("Log config changed")
                return jsonify({
                    'return': True,
                    'details': "Function ran with no errors."
                })

            if request.form.get('section') == "port":
                # Load default from backup config if defaults are requested, or load settings from the form.
                if int(request.form.get('port_default_flag')) == 1:
                    settings = get_config('whm.cfg.bak')
                    if not settings['return']:
                        # Ensure backup config was loaded.
                        session['logger'].write(settings['details'])
                        return jsonify(settings)
                else:
                    settings = {
                        'port_n': request.form.get('port_n')
                    }

                # Ensure port is a positive whole number.
                try:
                    x = int(settings['port_n'])
                    if not 1 <= x:
                        raise Exception()
                except:
                    return jsonify({
                        'return': False,
                        'details': "Port number must be a positive whole number."
                    })

                # Attempt to write port number.
                try:
                    config = configparser.RawConfigParser()
                    config.read('whm.cfg')
                    config.set('general', 'port_n', settings['port_n'])
                    with open('whm.cfg', 'w') as configfile:
                        config.write(configfile)
                except:
                    return jsonify({
                        'return': False,
                        'details': "Failed to write config."
                    })

                # Log and return success.
                session["logger"].write("Log config changed")
                return jsonify({
                    'return': True,
                    'details': "Function ran with no errors."
                })

        # User table actions - Requests can be accepted or declined, and current users can be deleted or have admin rights toggled.
        # Requests are handled by users.py and actions are logged.
        if request.form.get('action') == "accept":
            if not users.accept(request.form.get('request_id')):
                session['logger'].write("Failed to accept user with id: " + request.form.get('request_id'))
                return jsonify({
                    'return': False,
                    'details': "Failed to accept user."
                })

        # User action handling.
        if request.form.get('action') == "decline":
            users.delReq(request.form.get('request_id'))
            session['logger'].write("Deleted request with id: " + request.form.get('request_id'))
        if request.form.get('action') == "delete":
            users.delete(request.form.get('request_id'))
            session['logger'].write("Deleted user with id: " + request.form.get('request_id'))
        if request.form.get('action') == "toggle":
            users.toggleAdmin(request.form.get('request_id'))
            session['logger'].write("Toggles admin rights for user id: " + request.form.get('request_id'))

        # Return with no errors.
        return jsonify({
            'return': True,
            'details': "Success"
        })
    else:
        # GET request, return template.
        return render_template("settings.html")