Esempio n. 1
0
def delete_note(note):
    sessionid = request.cookies.get("app_session")
    log.debug(sessionid)
    if sessionid == None:
        log.debug("session id is lost")
        return redirect(url_for('login'))
    current_user = db.hget("sessions_app", sessionid)
    if current_user == None:
        log.debug("session id is bad")
        return redirect(url_for('login'))
    note_owner = db.hget(note, "owner")
    if current_user != note_owner:
        return {'msg': "Lapy precz to nie twoje!"}
    mynotes = json.loads(db.hget(current_user, "notes"))
    mynotes['notes'].remove(note)
    db.hset(current_user, "notes", json.dumps(mynotes))
    users = json.loads(db.hget(note, "users"))
    for user in users['users']:
        notesforuser = json.loads(db.hget(user, "notesforme"))
        notesforuser['notes'].remove(note)
        db.hset(user, "notesforme", json.dumps(notesforuser))
    keys = db.hkeys(note)
    for key in keys:
        db.hdel(note, key)
    db.hdel("public::notes", note)
    return redirect(url_for('notes'))
Esempio n. 2
0
def login():
    if request.method == POST:
        form = request.form
        username = form["username"]
        password = form.get("password").encode("utf-8")
        res = db.hexists(username, "data")
        if res == 0:
            return render_template("login.html"), 404
        salt = db.hget(username, "passwd_salt").encode("utf-8")
        for i in range(10):
            hashed_passwd = bcrypt.hashpw(password, salt)
            password = hashed_passwd
        password = str(hashed_passwd)
        cor_password = db.hget(username, "passwd_hash")
        if password == cor_password:
            response = make_response(redirect(url_for('home')))
            sessionid = uuid.uuid4().hex
            response.set_cookie("app_session",
                                sessionid,
                                secure=True,
                                httponly=True,
                                samesite="Strict")
            db.hset("sessions_app", sessionid, username)
            log.debug("session is set ")
            threading.Thread(target=removeUserSession, args=(
                sessionid,
                600,
            )).start()
            time.sleep(0.2)
            return response, 200
        else:
            return render_template("login.html"), 403
    else:
        return render_template("login.html"), 200
Esempio n. 3
0
def resetpasswd():
    if request.method == POST:
        form = request.form
        username = form["username"]
        res = db.hexists(username, "data")
        if res == 0:
            return {'msg': "Taki uzytkownik nie istnieje"}
        phone = form["phone"]

        user_data = db.hget(username, "data")
        user_data = json.loads(user_data)
        cor_phone = user_data["phone"]
        log.debug(cor_phone)
        log.debug(phone)

        if phone != cor_phone:
            return {'msg': "Nieudalo sie zresetowac hasla!"}
        answer = form.get("answer").encode("utf-8")
        salt = db.hget(username, "answer_salt").encode("utf-8")
        for i in range(10):
            hashed_answer = bcrypt.hashpw(answer, salt)
            answer = hashed_answer
        answer = str(hashed_answer)
        cor_answer = db.hget(username, "answer_hash")
        log.debug(cor_answer)
        log.debug(answer)
        if answer == cor_answer:
            # password hash & save
            generated_passwd = generatePasswd(16)
            password = generated_passwd
            salt = bcrypt.gensalt(12)
            for i in range(10):
                hashed_passwd = bcrypt.hashpw(password, salt)
                password = hashed_passwd
            salt = str(salt)
            password = str(hashed_passwd)
            db.hset(username, "passwd_hash", password)
            db.hset(username, "passwd_salt", salt)
            return {
                'msg':
                "Pomyslnie zresetowano haslo! Zaloguj sie i niezwlocznie zmien haslo na wlasne!",
                'new_password': generated_passwd
            }
        else:
            return {'msg': "Nieudalo sie zresetowac hasla!"}
    else:
        return redirect(url_for("reset"))
Esempio n. 4
0
def changepasswd():
    sessionid = request.cookies.get("app_session")
    log.debug(sessionid)
    if sessionid == None:
        log.debug("session id is lost")
        return redirect(url_for('login'))
    current_user = db.hget("sessions_app", sessionid)
    if current_user == None:
        log.debug("session id is bad")
        return redirect(url_for('login'))
    if request.method == POST:
        form = request.form
        username = current_user
        password = form.get("oldpassword").encode("utf-8")
        salt = db.hget(username, "passwd_salt").encode("utf-8")
        for i in range(10):
            hashed_passwd = bcrypt.hashpw(password, salt)
            password = hashed_passwd
        password = str(hashed_passwd)
        cor_password = db.hget(username, "passwd_hash")
        if password == cor_password:
            isValid, msg = validate_password(form)
            if not isValid:
                return {'msg': msg}, 400
            # password hash & save
            password = form.get("password").encode("utf-8")
            salt = bcrypt.gensalt(12)
            for i in range(10):
                hashed_passwd = bcrypt.hashpw(password, salt)
                password = hashed_passwd
            salt = str(salt)
            password = str(hashed_passwd)
            db.hset(current_user, "passwd_hash", password)
            db.hset(current_user, "passwd_salt", salt)
            return {'msg': "Pomyslnie zmieniono haslo!"}, 200
        else:
            return {'msg': "Nie udalo sie zmienic hasla!"}, 200
    else:
        {'msg': "To nie nie powinno pokazac!"}, 200
Esempio n. 5
0
def changeprofile():
    sessionid = request.cookies.get("app_session")
    log.debug(sessionid)
    if sessionid == None:
        log.debug("session id is lost")
        return redirect(url_for('login'))
    current_user = db.hget("sessions_app", sessionid)
    if current_user == None:
        log.debug("session id is bad")
        return redirect(url_for('login'))
    form = request.form
    isValid, msg = validate_updateuserform(form)
    if not isValid:
        return {'msg': msg}, 400

    fname = form.get("firstName")
    lname = form.get("lastName")
    phone = form.get("phone")
    street = form.get("street")
    number = form.get("streetNumber")
    postalCode = form.get("postalCode")
    city = form.get("city")
    country = form.get("country")

    user_data = db.hget(current_user, "data")
    user_data = json.loads(user_data)

    user_data['fname'] = fname
    user_data['lname'] = lname
    user_data['phone'] = phone
    user_data['address']['street'] = street
    user_data['address']['number'] = number
    user_data['address']['postalCode'] = postalCode
    user_data['address']['city'] = city
    user_data['address']['country'] = country

    db.hset(current_user, "data", json.dumps(user_data))

    return redirect(url_for("profile")), 200
Esempio n. 6
0
    def prioritized_sweeping(self, planning_steps: int = 0, n_episodes: int = 50, alpha: float = 0.1,
                             gamma: float = 0.95,
                             epsilon: float = 0.1, theta: float = 0.00001, verbose: bool = False, seed: int = None,
                             ):
        if seed:
            random.seed(seed)
            np.random.seed(seed)

        q_shape = [len(self.actions)] + list(self.grid.shape)
        q_values = np.random.rand(*q_shape)
        model = defaultdict(tuple)
        p_queue = heapdict()
        predecessors = defaultdict(set)  # to track all the states leading into a given state

        if verbose:
            self.grid = self.grid.astype(int)
            grid = self.grid.copy()

        total_steps_per_episode = list()
        for _ in tqdm(range(n_episodes)):
            total_steps = 0
            time.sleep(3)

            state = self.start_state
            while state != self.goal:

                # training board
                db.hset('Prioritized Sweeping', 'Q-Values', pickle.dumps(q_values))
                db.hset('Prioritized Sweeping', 'Grid', pickle.dumps(grid))
                db.hset('Prioritized Sweeping', 'Priority', pickle.dumps(p_queue))

                a = randargmax(q_values[:, state[0], state[1]])
                a = self.epsilon_greedy(a, epsilon)
                state_next, reward = self.state_transition(state, self.actions[a])

                # if verbose:
                # print(grid.T)
                # print('current state:', state)
                # print('next action:', a)
                # print('next action:', state_next)

                model[state, a] = reward, state_next
                # remember state-action pairs and associated rewards that led to the next state
                predecessors[state_next].add((state, a, reward))

                q_index = a, state[0], state[1]
                q_index_next = randargmax(q_values[:, state_next[0], state_next[1]]), state_next[0], state_next[1]
                priority = abs(reward + gamma * q_values[q_index_next] - q_values[q_index])
                if priority > theta:
                    # note that python's native heapq works for min elements only
                    p_queue[state, a] = min(p_queue.get((state, a), 0), priority * -1)

                for n in range(planning_steps):
                    if not p_queue:
                        break

                    s, a = p_queue.popitem()[0]
                    reward, s_next = model[s, a]

                    q_index = a, s[0], s[1]
                    q_index_next = randargmax(q_values[:, s_next[0], s_next[1]]), s_next[0], s_next[1]
                    q_values[q_index] += alpha * (reward + gamma * q_values[q_index_next] - q_values[q_index])

                    # compute priorities of predecessors of the sample state
                    q_index = randargmax(q_values[:, s[0], s[1]]), s[0], s[1]
                    for state_prev, a_prev, reward_prev in predecessors[s]:
                        q_index_prev = a_prev, state_prev[0], state_prev[1]
                        priority = abs(reward_prev + gamma * q_values[q_index] - q_values[q_index_prev])
                        if priority > theta:
                            p_queue[state_prev, a_prev] = min(p_queue.get((state_prev, a_prev), 0), priority * -1)
                    total_steps += 1

                if verbose:
                    grid[state] = 0
                    grid[state_next] = 10

                state = state_next

            total_steps_per_episode.append(total_steps)
        return total_steps_per_episode
Esempio n. 7
0
def notes():
    sessionid = request.cookies.get("app_session")
    log.debug(sessionid)
    if sessionid == None:
        log.debug("session id is lost")
        return redirect(url_for('login'))
    current_user = db.hget("sessions_app", sessionid)
    if current_user == None:
        log.debug("session id is bad")
        return redirect(url_for('login'))
    if request.method == POST:
        form = request.form
        noteid = uuid.uuid4().hex
        title = form.get("title")
        text = form.get("text")
        usersff = form.get("users")
        users = []
        if usersff != "" and usersff != None:
            usersff = usersff.split(";")
            for user in usersff:
                user = user.replace(" ", "")
                res = db.hexists(user, "data")
                if res == 0:
                    return {'msg': "Uzytkownik %s nie istnieje" % user}
            for user in usersff:
                user = user.replace(" ", "")
                users.append(user)
                notesforhim = db.hget(user, "notesforme")
                notesforhim = json.loads(notesforhim)
                notesforhim['notes'].append(noteid)
                db.hset(user, "notesforme", json.dumps(notesforhim))
        public = form["public"]
        if public == "True":
            public = "True"
        else:
            public = "False"
        #create new note (TITLE, TEXT OWNER, PUBLIC, USERS)
        db.hset(noteid, "title", title)

        db.hset(noteid, "text", text)

        db.hset(noteid, "owner", current_user)

        db.hset(noteid, "public", public)

        db.hset(noteid, "users", json.dumps({'users': users}))

        if public == "True":
            db.hset("public::notes", noteid, "True")
        yournotes = db.hget(current_user, "notes")
        yournotes = json.loads(yournotes)
        yournotes["notes"].append(noteid)
        db.hset(current_user, "notes", json.dumps(yournotes))
        notes = []
        if len(yournotes["notes"]) > 0:
            for note in yournotes["notes"]:
                note = {
                    'id': note,
                    'title': db.hget(note, "title"),
                    'text': db.hget(note, "text")
                }
                notes.append(note)
        public_notes = []
        publicnotesid = db.hkeys("public::notes")
        for nid in publicnotesid:
            note = {
                'id': nid,
                'title': db.hget(nid, "title"),
                'text': db.hget(nid, "text")
            }
            public_notes.append(note)
        notes_for_me = []
        notesforme = db.hget(current_user, "notesforme")
        notesforme = json.loads(notesforme)
        for nid in notesforme['notes']:
            note = {
                'id': nid,
                'title': db.hget(nid, "title"),
                'text': db.hget(nid, "text")
            }
            notes_for_me.append(note)
        return render_template("notes.html",
                               notes=notes,
                               public_notes=public_notes,
                               notes_for_me=notes_for_me)
    else:
        yournotes = db.hget(current_user, "notes")
        yournotes = json.loads(yournotes)
        notes = []
        if len(yournotes["notes"]) > 0:
            for note in yournotes["notes"]:
                note = {
                    'id': note,
                    'title': db.hget(note, "title"),
                    'text': db.hget(note, "text")
                }
                notes.append(note)
        public_notes = []
        publicnotesid = db.hkeys("public::notes")
        for nid in publicnotesid:
            note = {
                'id': nid,
                'title': db.hget(nid, "title"),
                'text': db.hget(nid, "text")
            }
            public_notes.append(note)
        notes_for_me = []
        notesforme = db.hget(current_user, "notesforme")
        notesforme = json.loads(notesforme)
        for nid in notesforme['notes']:
            note = {
                'id': nid,
                'title': db.hget(nid, "title"),
                'text': db.hget(nid, "text")
            }
            notes_for_me.append(note)
        return render_template("notes.html",
                               notes=notes,
                               public_notes=public_notes,
                               notes_for_me=notes_for_me)
Esempio n. 8
0
def registration():
    if request.method == GET:
        return render_template("registration.html")
    else:
        form = request.form
        # data validation
        isValid, msg = validate_userform(form)
        if not isValid:
            return {'msg': msg}, 400
        isValid, msg = validate_password(form)
        if not isValid:
            return {'msg': msg}, 400
        isValid, msg = validate_question(form)
        if not isValid:
            return {'msg': msg}, 400
        # user data save
        user = to_user(form)
        notes = json.dumps({'notes': []})
        user_data = json.dumps(user.user_to_dict())
        db.hset(user.login, "data", user_data)
        db.hset(user.login, "notes", notes)
        db.hset(user.login, "notesforme", notes)
        # password hash & save
        password = form.get("password").encode("utf-8")
        salt = bcrypt.gensalt(12)
        for i in range(10):
            hashed_passwd = bcrypt.hashpw(password, salt)
            password = hashed_passwd
        salt = str(salt)
        password = str(hashed_passwd)
        db.hset(user.login, "passwd_hash", password)
        db.hset(user.login, "passwd_salt", salt)
        # answer hash & save
        question = form.get("question")
        answer = form.get("answer").encode("utf-8")
        salt = bcrypt.gensalt(12)
        for i in range(10):
            hashed_answer = bcrypt.hashpw(answer, salt)
            answer = hashed_answer
        salt = str(salt)
        answer = str(hashed_answer)
        db.hset(user.login, "question", question)
        db.hset(user.login, "answer_hash", answer)
        db.hset(user.login, "answer_salt", salt)
        return redirect(url_for('home')), 200