コード例 #1
0
ファイル: organizations.py プロジェクト: gitter-badger/karmen
def list_organizations():
    user = get_current_user()
    item_list = []
    for org in organization_roles.get_by_user_uuid(user["uuid"]):
        item_list.append({
            "uuid": org["uuid"],
            "name": org["name"],
            "role": org["role"],
        })
    return jsonify({"items": item_list}), 200
コード例 #2
0
ファイル: users_me.py プロジェクト: gitter-badger/karmen
def activate_user():
    data = request.json
    if not data:
        return abort(make_response(jsonify(message="Missing payload"), 400))
    email = data.get("email", "").lstrip().rstrip().lower()
    activation_key = data.get("activation_key", None)
    password = data.get("password", None)
    password_confirmation = data.get("password_confirmation", None)

    if not email or not is_email(email):
        return abort(
            make_response(jsonify(message="Missing or bad email"), 400))
    if not password:
        return abort(make_response(jsonify(message="Missing password"), 400))
    if not activation_key:
        return abort(
            make_response(jsonify(message="Missing activation_key"), 400))
    if password != password_confirmation:
        return abort(
            make_response(jsonify(message="Passwords do not match"), 400))

    existing = users.get_by_email(email)
    if not existing:
        return abort(make_response(jsonify(message="Cannot activate"), 400))
    if existing["activated"] is not None:
        return abort(make_response(jsonify(message="Already activated"), 409))

    if (hashlib.sha256(str(activation_key).encode("utf-8")).hexdigest() !=
            existing["activation_key_hash"]):
        return abort(make_response(jsonify(message="Cannot activate"), 400))
    if existing["activation_key_expires"] < datetime.now().astimezone():
        return abort(
            make_response(jsonify(message="Activation key expired"), 400))

    memberships = organization_roles.get_by_user_uuid(existing["uuid"])
    if len(memberships) == 0:
        orguuid = guid.uuid4()
        organizations.add_organization(uuid=orguuid,
                                       name="Default organization")
        organization_roles.set_organization_role(orguuid, existing["uuid"],
                                                 "admin")

    pwd_hash = bcrypt.hashpw(password.encode("utf8"), bcrypt.gensalt())
    users.update_user(
        uuid=existing["uuid"],
        activated=datetime.now().astimezone(),
        providers=["local"],
        providers_data={},
    )
    local_users.add_local_user(
        user_uuid=existing["uuid"],
        pwd_hash=pwd_hash.decode("utf8"),
        force_pwd_change=False,
    )
    return "", 204
コード例 #3
0
ファイル: tests_admin.py プロジェクト: fragaria/karmen
def create_test_user():
    email = request.json.get("email")
    password = request.json.get("password")
    new_user = models.users_me.create_tests_user(email=email,
                                                 password=password)
    new_user["detail"] = dict(users.get_by_uuid(new_user["user_uuid"]))
    # These 2 are datetimes objects from Postgres and can't be
    # serialized to JSON without extra work, so they crash the server here.
    # As we don't need them, it's easier to pop them.
    new_user["detail"].pop("activated")
    new_user["detail"].pop("activation_key_expires")
    app.logger.debug(organization_roles.get_by_user_uuid(
        new_user["user_uuid"]))
    new_user["organizations"] = [
        dict(x)
        for x in organization_roles.get_by_user_uuid(new_user["user_uuid"])
    ]

    return make_response(json.dumps(new_user),
                         201 if new_user["activated"] else 400)
コード例 #4
0
ファイル: test_users_me.py プロジェクト: fragaria/karmen
 def test_activate_user_with_default_org(self):
     with app.test_client() as c:
         self.assertTrue(
             len(organization_roles.get_by_user_uuid(self.user_uuid)) == 0)
         response = c.post(
             "/users/me/activate",
             json={
                 "email": self.email,
                 "activation_key": self.activation_key,
                 "password": "******",
                 "password_confirmation": "aaa",
             },
         )
         self.assertEqual(response.status_code, 204)
         user = users.get_by_uuid(self.user_uuid)
         self.assertTrue(user is not None)
         self.assertTrue(user["activated"] is not None)
         local_user = local_users.get_local_user(self.user_uuid)
         self.assertTrue(local_user is not None)
         self.assertTrue(
             len(organization_roles.get_by_user_uuid(self.user_uuid)) == 1)
コード例 #5
0
    def test_list(self):
        with app.test_client() as c:
            c.set_cookie("localhost", "access_token_cookie", TOKEN_USER2)
            response = c.get(
                "/organizations",
                headers={"x-csrf-token": TOKEN_USER2_CSRF},
            )
            self.assertEqual(response.status_code, 200)
            self.assertTrue("items" in response.json)
            self.assertTrue(
                len(response.json["items"]) <= len(
                    organization_roles.get_by_user_uuid(UUID_USER2)))

            c.set_cookie("localhost", "access_token_cookie", TOKEN_USER)
            response = c.get(
                "/organizations",
                headers={"x-csrf-token": TOKEN_USER_CSRF},
            )
            self.assertEqual(response.status_code, 200)
            self.assertTrue("items" in response.json)
            self.assertTrue(
                len(response.json["items"]) <= len(
                    organization_roles.get_by_user_uuid(UUID_USER)))
コード例 #6
0
def activate_user(email, activation_key, password, password_confirmation):
    try:
        validate_email(email, check_deliverability=False)
    except EmailNotValidError as e:
        return {"activated": False, "message": f"Email not valid: {e}"}
    if not password:
        return {"activated": False, "message": "Missing password"}
    if not activation_key:
        return {"activated": False, "message": "Missing activation_key"}
    if password != password_confirmation:
        return {"activated": False, "message": "Passwords do not match"}

    existing = users.get_by_email(email)
    if not existing:
        return {"activated": False, "message": "Cannot activate"}
    if existing["activated"] is not None:
        return {
            "activated": False,
            "already_activated": True,
            "message": "Already activated",
        }

    if (hashlib.sha256(str(activation_key).encode("utf-8")).hexdigest() !=
            existing["activation_key_hash"]):
        return {"activated": False, "message": "Cannot activate"}
    if existing["activation_key_expires"] < datetime.now().astimezone():
        return {"activated": False, "message": "Activation key expired"}

    memberships = organization_roles.get_by_user_uuid(existing["uuid"])
    if len(memberships) == 0:
        orguuid = guid.uuid4()
        organizations.add_organization(uuid=orguuid,
                                       name="Default organization")
        organization_roles.set_organization_role(orguuid, existing["uuid"],
                                                 "admin")

    pwd_hash = bcrypt.hashpw(password.encode("utf8"), bcrypt.gensalt())
    users.update_user(
        uuid=existing["uuid"],
        activated=datetime.now().astimezone(),
        providers=["local"],
        providers_data={},
    )
    local_users.add_local_user(
        user_uuid=existing["uuid"],
        pwd_hash=pwd_hash.decode("utf8"),
        force_pwd_change=False,
    )
    return {"activated": True, "user_uuid": existing["uuid"]}
コード例 #7
0
ファイル: users_me.py プロジェクト: gitter-badger/karmen
def get_user_identity(userdata, token_freshness):
    membership = {}
    for org in organization_roles.get_by_user_uuid(userdata.get("uuid")):
        membership[org.get("uuid")] = {
            "uuid": org.get("uuid"),
            "name": org.get("name"),
            "role": org.get("role"),
        }
    return {
        "identity": userdata.get("uuid"),
        "system_role": userdata.get("system_role", "user"),
        "username": userdata.get("username"),
        "email": userdata.get("email"),
        "force_pwd_change": userdata.get("force_pwd_change", False),
        "fresh": token_freshness,
        "expires_on": datetime.now() + ACCESS_TOKEN_EXPIRES_AFTER,
        "organizations": membership,
    }