def qrcode():
    user = current_user
    code = gen_salt(48)
    msg = {
        "code": code,
        "user_id": user.get_user_id(),
        "username": user.name,
        "email": user.email,
    }
    session['code'] = code
    session.modified = True
    new_regist = RegistrationRequest(private_code=code,
                                     user_id=current_user.get_user_id(),
                                     start_at=datetime.now(),
                                     is_success=False)
    db.session.add(new_regist)
    db.session.commit()
    print('NEW REGIST: ', code)

    # render QR code
    content_json = json.dumps(msg)
    qr_content = base64.b64encode(content_json.encode('utf-8'))
    url = pyqrcode.create(qr_content)
    stream = io.BytesIO()
    url.svg(stream, scale=5)
    return stream.getvalue(), 200, {
        'Content-Type': 'image/svg+xml',
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache',
        'Expires': '0'
    }
Beispiel #2
0
def set_auth_server_attr(attr_name, attr_value):
    print("set_auth_server_attr")
    user_id = current_user.get_user_id()
    auth_attribute = AuthAttribute.query.filter_by(id=user_id).first()
    auth_server_attributes = auth_attribute.get_server_attributes()
    auth_server_attributes[attr_name] = attr_value
    print("auth_server_attributes: ", auth_server_attributes)
    auth_attribute.set_server_attributes(auth_server_attributes)
Beispiel #3
0
def fav_add(id):
    f = Favourites()
    f.user_id = current_user.get_user_id()
    f.post_id = id
    db_sess = db_session.create_session()
    db_sess.add(f)
    db_sess.commit()
    return redirect('/')
Beispiel #4
0
def set_auth_user_attr(attr_name, attr_value):
    print("(set_auth_user_attr)")
    user_id = current_user.get_user_id()
    auth_attribute = AuthAttribute.query.filter_by(id=user_id).first()
    auth_user_attributes = auth_attribute.get_user_attributes()
    auth_user_attributes[attr_name] = attr_value
    print("auth_user_attributes: ", auth_user_attributes)
    auth_attribute.set_user_attributes(auth_user_attributes)
    flask.session["info_authorize"] = 1
Beispiel #5
0
def get_auth_attributes():
    print("(get_auth_attributes)")
    user_id = current_user.get_user_id()
    auth_attribute = AuthAttribute.query.filter_by(id=user_id).first()
    auth_user_attributes = auth_attribute.get_user_attributes()
    auth_server_attributes = auth_attribute.get_server_attributes()
    print("[auth_user_attributes, auth_server_attributes]: ",
          [auth_user_attributes, auth_server_attributes])
    # return a list of two dictionaries
    return [auth_user_attributes, auth_server_attributes]
Beispiel #6
0
def favourite_posts():
    db_sess = db_session.create_session()
    if current_user.is_authenticated:
        favourites = db_sess.query(Favourites).filter(
            (Favourites.user_id == current_user.get_user_id()))
        s = list(set([i.post_id for i in favourites]))
        res = []
        for i in s:
            res.append(db_sess.query(News).filter(News.id == i).first())
    else:
        return redirect('/')
    return render_template("favourites.html", news=res, title='Избранное')
Beispiel #7
0
def policy():
    """Register a new policy using the py_abac format. 
    
    Args:
        All of the following arguments are required and passed in the request URL.
        td (JSON str): the information of the policy to be registered in JSON format
        location (str): the location where the thing description should be registered

    Returns:
        HTTP Response: if the register is completed, a simple success string with HTTP status code 200 is returned
            Otherwise a reason is returned in the response and HTTP status code is set to 400
    """

    # 1-2. check and parse input
    if not is_json_request(request, ["td", "location"]):
        return jsonify(ERROR_JSON), 400

    json = request.get_json()
    policy_json = json['td']
    location = json['location']
    # Does not allow customized uid, it should be auto generated by uuid
    if 'uid' in policy_json:
        return jsonify({'error': 'Cannot customize uid'})
    uid = str(uuid.uuid4())
    if not is_policy_request(
            policy_json,
        ["description", "effect", "rules", "targets", "priority"]):
        return jsonify(ERROR_POLICY), 400

    if not user.get_id():
        return jsonify(ERROR_NO_USER), 400
    policy_json['uid'] = uid
    if add_policy_to_storage(policy_json, location):
        new_policy = Policy(uid=uid,
                            location=location,
                            policy_json=str(policy_json),
                            user_id=int(
                                user.get_user_id()))  # local policy register
        auth_db.session.add(new_policy)
        auth_db.session.commit()
        return make_response("Created Policy", 200)

    return jsonify(ERROR_JSON), 400
Beispiel #8
0
def clear_auth_attributes():
    user_id = current_user.get_user_id()
    auth_attribute = AuthAttribute.query.filter_by(id=user_id).first()
    auth_attribute.set_user_attributes(auth_user_attr_default)
    auth_attribute.set_server_attributes(auth_server_attr_default)
Beispiel #9
0
 def get_attribute_value(self, ace, attribute_path, ctx):
     if not current_user:
         return None
     if ace == "subject" and attribute_path == "$.id":
         return current_user.get_user_id()
     return None
Beispiel #10
0
def selection(position):
    # TODO Check if they already Voted
    connection = db.data
    print(db.is_connected)
    if request.method == 'GET':
        position = position.lower()
        if position:
            candidates = get_cadidates_by_position(position)
            if candidates:
                # print(current_user.__dict__)
                # print(current_user.get_user_faculty())
                # print(candidates[0].group)
                if position == 'faculty officer':
                    # Filter out so only returns student's  faculty.
                    candidates = list(
                        filter(
                            lambda x: x.get_user_faculty() == current_user.
                            get_user_faculty(), candidates))

                    # print(faculty_candidates[0].__dict__)
                groups = {}
                # Putting the candidates in a group
                for candidate in candidates:
                    if candidate.group not in groups.keys():
                        groups[candidate.group] = [candidate]
                    else:
                        groups[candidate.group].append(candidate)

                candidates = {position: groups}

                return render_template("selection.html",
                                       candidates=candidates,
                                       endpoint=position)
            else:
                return "No Candidates for this %s position " % position
        else:
            return "position not provided"

    elif request.method == 'POST':
        if request.is_json:
            vote_selections = request.get_json()
            print(vote_selections)
            for group in vote_selections.copy().keys():
                # Checking that ranking meeets, at least one candidate ranked 1 and others optional
                print(vote_selections[group].values())
                all_selections = vote_selections[group]
                if '1' in vote_selections[group].values():
                    # Removing Default selection
                    for candidate in vote_selections[group].copy().keys():
                        if all_selections[candidate] == 'Choose a rank':
                            print('removing %s' % candidate)
                            vote_selections[group].pop(candidate)
                    if list_all_duplicates(vote_selections[group].values()):
                        return "ERROR- Candidates cannot have same preference  %s" % group, 403

                else:
                    return "At least one candidate needs to be ranked 1 for group %s" % group, 403
            global ALL_VOTES
            if not current_user.get_user_id() in ALL_VOTES.keys():
                ALL_VOTES[current_user.get_user_id()] = {
                    position: {
                        **vote_selections
                    }
                }
            else:
                ALL_VOTES[current_user.get_user_id()][position] = {
                    **vote_selections
                }
            return jsonify(ALL_VOTES[current_user.get_user_id()])

        else:
            return "Not valid content", 403