Merge branch 'simple-authentication' into simple-authentication-front

This commit is contained in:
zurdi
2023-08-18 16:27:01 +02:00
6 changed files with 49 additions and 23 deletions

View File

@@ -1,4 +1,3 @@
import os
import secrets
import base64
import binascii
@@ -137,7 +136,7 @@ class UserUpdateForm:
self.disabled = disabled
@protected_route(router.patch, "/users/{user_id}", ["users.write"])
@protected_route(router.put, "/users/{user_id}", ["users.write"])
@requires(["users.write"])
def update_user(
request: Request, user_id: int, form_data: Annotated[UserUpdateForm, Depends()]
@@ -154,7 +153,7 @@ def update_user(
cleaned_data = {}
if form_data.username:
if form_data.username != user.username:
existing_user = dbh.get_user_by_username(form_data.username.lower())
if existing_user:
raise HTTPException(
@@ -181,7 +180,9 @@ def update_user(
dbh.update_user(user_id, cleaned_data)
# Log out the current user if username or password changed
if cleaned_data.get("username") or cleaned_data.get("hashed_password"):
if request.user.id == user_id and (
cleaned_data.get("username") or cleaned_data.get("hashed_password")
):
session_id = request.session.get("session_id")
if session_id:
cache.delete(f"romm:{session_id}")

View File

@@ -1,4 +1,3 @@
import os
import uvicorn
import alembic.config
import re
@@ -30,6 +29,14 @@ app.add_middleware(
allow_headers=["*"],
)
if ROMM_AUTH_ENABLED and "pytest" not in sys.modules:
# CSRF protection (except endpoints listed in exempt_urls)
app.add_middleware(
CustomCSRFMiddleware,
secret=ROMM_AUTH_SECRET_KEY,
exempt_urls=[re.compile(r"^/token.*"), re.compile(r"^/ws")],
)
# Handles both basic and oauth authentication
app.add_middleware(
AuthenticationMiddleware,
@@ -44,15 +51,6 @@ app.add_middleware(
https_only=False,
)
if "pytest" not in sys.modules and os.environ.get("ROMM_AUTH_ENABLED"):
# CSRF protection (except endpoints listed in exempt_urls)
app.add_middleware(
CustomCSRFMiddleware,
secret=ROMM_AUTH_SECRET_KEY,
exempt_urls=[re.compile(r"^/token.*"), re.compile(r"^/ws")],
)
app.include_router(oauth.router)
app.include_router(identity.router)
app.include_router(platform.router)

View File

@@ -56,15 +56,21 @@ async def get_current_active_user_from_session(conn: HTTPConnection):
if not username:
return None
# Key exists therefore user is authenticated
# Key exists therefore user is probably authenticated
user = dbh.get_user_by_username(username)
if user is None:
cache.delete(f"romm:{session_id}")
conn.session["session_id"] = None
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
status_code=status.HTTP_403_FORBIDDEN,
detail="User not found",
)
if user.disabled:
cache.delete(f"romm:{session_id}")
conn.session["session_id"] = None
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user"
)

View File

@@ -16,7 +16,15 @@ emitter.on("showCreateUserDialog", () => {
});
async function createUser() {
await createUserApi(user.value);
await createUserApi(user.value).catch(({ response, message }) => {
emitter.emit("snackbarShow", {
msg: `Unable to create user: ${
response?.data?.detail || response?.statusText || message
}`,
icon: "mdi-close-circle",
color: "red",
});
});
show.value = false;
emitter.emit("refreshView");
}
@@ -85,7 +93,11 @@ async function createUser() {
</v-row>
<v-row class="justify-center pa-2" no-gutters>
<v-btn @click="show = false" class="bg-terciary">Cancel</v-btn>
<v-btn class="text-rommGreen bg-terciary ml-5" @click="createUser()">
<v-btn
:disabled="!user.username || !user.password"
class="text-rommGreen bg-terciary ml-5"
@click="createUser()"
>
Create
</v-btn>
</v-row>

View File

@@ -1,6 +1,8 @@
<script setup>
import { ref, inject } from "vue";
import { updateUserApi } from "@/services/api";
const user = ref();
const show = ref(false);
@@ -11,9 +13,16 @@ emitter.on("showEditUserDialog", (userToEdit) => {
});
function editUser() {
// TODO: edit user endpoint
console.log("Updating user:");
console.log(user.value);
updateUserApi(user.value).catch(({ response, message }) => {
emitter.emit("snackbarShow", {
msg: `Unable to edit user: ${
response?.data?.detail || response?.statusText || message
}`,
icon: "mdi-close-circle",
color: "red",
});
});
show.value = false;
emitter.emit("refreshView");
}

View File

@@ -115,8 +115,8 @@ export async function createUserApi({ username, password, role }) {
return api.post("/users", {}, { params: { username, password, role } });
}
export async function updateUserApi(user) {
return api.put(`/users/${user.id}`, { user });
export async function updateUserApi({ id, username, password, role }) {
return api.put(`/users/${id}`, {}, { params: { username, password, role } });
}
export async function deleteUserApi(user) {