feat: add password reset for usermanager (#2688)
* feat: add password reset for usermanager - add a reset_key to account table - add ?reset_key= GET arguments to index.html and show reset form if provided - superuser can generate and copy reset url with key to share future ideas: - could add send forgot password email if user fill out email address * feat: simplify reset key * test: use reset key * test: add more tests * test: reset passwords do not match * test: `reset_password_auth_threshold_expired` --------- Co-authored-by: Vlad Stan <stan.v.vlad@gmail.com>
This commit is contained in:
+3
-3
@@ -219,8 +219,8 @@ async def update_user_password(data: UpdateUserPassword, last_login_time: int) -
|
||||
|
||||
assert 0 <= time() - last_login_time <= settings.auth_credetials_update_threshold, (
|
||||
"You can only update your credentials in the first"
|
||||
f" {settings.auth_credetials_update_threshold} seconds after login."
|
||||
" Please login again!"
|
||||
f" {settings.auth_credetials_update_threshold} seconds."
|
||||
" Please login again or ask a new reset key!"
|
||||
)
|
||||
assert data.password == data.password_repeat, "Passwords do not match."
|
||||
|
||||
@@ -240,7 +240,7 @@ async def update_user_password(data: UpdateUserPassword, last_login_time: int) -
|
||||
)
|
||||
|
||||
user = await get_user(data.user_id)
|
||||
assert user, "Updated account couldn't be retrieved"
|
||||
assert user, "Updated account couldn't be retrieved."
|
||||
return user
|
||||
|
||||
|
||||
|
||||
@@ -194,6 +194,12 @@ class UpdateUserPubkey(BaseModel):
|
||||
pubkey: str = Query(default=..., max_length=64)
|
||||
|
||||
|
||||
class ResetUserPassword(BaseModel):
|
||||
reset_key: str
|
||||
password: str = Query(default=..., min_length=8, max_length=50)
|
||||
password_repeat: str = Query(default=..., min_length=8, max_length=50)
|
||||
|
||||
|
||||
class UpdateSuperuserPassword(BaseModel):
|
||||
username: str = Query(default=..., min_length=2, max_length=20)
|
||||
password: str = Query(default=..., min_length=8, max_length=50)
|
||||
|
||||
@@ -184,6 +184,47 @@
|
||||
</div>
|
||||
</q-form>
|
||||
</q-card-section>
|
||||
<q-card-section
|
||||
v-if="authAction === 'reset' && authMethod === 'username-password'"
|
||||
>
|
||||
<b> <span v-text="$t('reset_password')"></span> </b><br /><br />
|
||||
<q-form @submit="reset" class="q-gutter-md">
|
||||
<q-input
|
||||
filled
|
||||
dense
|
||||
required
|
||||
:disable="true"
|
||||
v-model="reset_key"
|
||||
:label="$t('reset_key') + ' *'"
|
||||
></q-input>
|
||||
<q-input
|
||||
filled
|
||||
dense
|
||||
v-model="password"
|
||||
:label="$t('password') + ' *'"
|
||||
type="password"
|
||||
:rules="[(val) => !val || val.length >= 8 || $t('invalid_password')]"
|
||||
></q-input>
|
||||
<q-input
|
||||
filled
|
||||
dense
|
||||
v-model="passwordRepeat"
|
||||
:label="$t('password_repeat') + ' *'"
|
||||
type="password"
|
||||
:rules="[(val) => !val || val.length >= 8 || $t('invalid_password')]"
|
||||
></q-input>
|
||||
<div>
|
||||
<q-btn
|
||||
unelevated
|
||||
color="primary"
|
||||
:disable="!password || !passwordRepeat|| !reset_key || (password !== passwordRepeat)"
|
||||
type="submit"
|
||||
class="full-width"
|
||||
:label="$t('reset_password')"
|
||||
></q-btn>
|
||||
</div>
|
||||
</q-form>
|
||||
</q-card-section>
|
||||
{%endif%} {% if LNBITS_NEW_ACCOUNTS_ALLOWED %}
|
||||
<q-card-section
|
||||
v-if="authAction === 'register' && authMethod === 'user-id-only'"
|
||||
|
||||
@@ -84,6 +84,15 @@ include "users/_createWalletDialog.html" %}
|
||||
>
|
||||
<q-tooltip>Super User</q-tooltip>
|
||||
</q-btn>
|
||||
<q-btn
|
||||
round
|
||||
icon="refresh"
|
||||
size="sm"
|
||||
color="secondary"
|
||||
@click="resetPassword(props.row.id)"
|
||||
>
|
||||
<q-tooltip>Generate and copy password reset url</q-tooltip>
|
||||
</q-btn>
|
||||
<q-btn
|
||||
round
|
||||
icon="delete"
|
||||
|
||||
@@ -44,6 +44,7 @@ from ..models import (
|
||||
CreateUser,
|
||||
LoginUsernamePassword,
|
||||
LoginUsr,
|
||||
ResetUserPassword,
|
||||
UpdateSuperuserPassword,
|
||||
UpdateUser,
|
||||
UpdateUserPassword,
|
||||
@@ -259,7 +260,50 @@ async def update_pubkey(
|
||||
except Exception as exc:
|
||||
logger.debug(exc)
|
||||
raise HTTPException(
|
||||
HTTP_500_INTERNAL_SERVER_ERROR, "Cannot update user password."
|
||||
HTTP_500_INTERNAL_SERVER_ERROR, "Cannot update user pubkey."
|
||||
) from exc
|
||||
|
||||
|
||||
@auth_router.put("/reset")
|
||||
async def reset_password(data: ResetUserPassword) -> JSONResponse:
|
||||
if not settings.is_auth_method_allowed(AuthMethods.username_and_password):
|
||||
raise HTTPException(
|
||||
HTTP_401_UNAUTHORIZED, "Auth by 'Username and Password' not allowed."
|
||||
)
|
||||
|
||||
try:
|
||||
assert data.reset_key[:10] == "reset_key_", "This is not a reset key."
|
||||
|
||||
reset_data_json = decrypt_internal_message(
|
||||
base64.b64decode(data.reset_key[10:]).decode()
|
||||
)
|
||||
assert reset_data_json, "Cannot process reset key."
|
||||
|
||||
action, user_id, request_time = json.loads(reset_data_json)
|
||||
assert action == "reset", "Expected reset action."
|
||||
assert user_id is not None, "Missing user ID."
|
||||
assert request_time is not None, "Missing reset time."
|
||||
|
||||
user = await get_account(user_id)
|
||||
assert user, "User not found."
|
||||
|
||||
update_pwd = UpdateUserPassword(
|
||||
user_id=user.id,
|
||||
username=user.username or "",
|
||||
password=data.password,
|
||||
password_repeat=data.password_repeat,
|
||||
)
|
||||
user = await update_user_password(update_pwd, request_time)
|
||||
|
||||
return _auth_success_response(
|
||||
username=user.username, user_id=user_id, email=user.email
|
||||
)
|
||||
except AssertionError as exc:
|
||||
raise HTTPException(HTTP_403_FORBIDDEN, str(exc)) from exc
|
||||
except Exception as exc:
|
||||
logger.warning(exc)
|
||||
raise HTTPException(
|
||||
HTTP_500_INTERNAL_SERVER_ERROR, "Cannot reset user password."
|
||||
) from exc
|
||||
|
||||
|
||||
@@ -309,7 +353,7 @@ async def first_install(data: UpdateSuperuserPassword) -> JSONResponse:
|
||||
except Exception as exc:
|
||||
logger.debug(exc)
|
||||
raise HTTPException(
|
||||
HTTP_500_INTERNAL_SERVER_ERROR, "Cannot update user password."
|
||||
HTTP_500_INTERNAL_SERVER_ERROR, "Cannot init user password."
|
||||
) from exc
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import base64
|
||||
import json
|
||||
import time
|
||||
from http import HTTPStatus
|
||||
from typing import List
|
||||
|
||||
@@ -23,7 +26,7 @@ from lnbits.core.models import (
|
||||
from lnbits.core.services import update_wallet_balance
|
||||
from lnbits.db import Filters, Page
|
||||
from lnbits.decorators import check_admin, check_super_user, parse_filters
|
||||
from lnbits.helpers import generate_filter_params_openapi
|
||||
from lnbits.helpers import encrypt_internal_message, generate_filter_params_openapi
|
||||
from lnbits.settings import EditableSettings, settings
|
||||
|
||||
users_router = APIRouter(prefix="/users/api/v1", dependencies=[Depends(check_admin)])
|
||||
@@ -75,6 +78,24 @@ async def api_users_delete_user(
|
||||
) from exc
|
||||
|
||||
|
||||
@users_router.put(
|
||||
"/user/{user_id}/reset_password", dependencies=[Depends(check_super_user)]
|
||||
)
|
||||
async def api_users_reset_password(user_id: str) -> str:
|
||||
if user_id == settings.super_user:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.FORBIDDEN,
|
||||
detail="Cannot change superuser password.",
|
||||
)
|
||||
|
||||
reset_data = ["reset", user_id, int(time.time())]
|
||||
reset_data_json = json.dumps(reset_data, separators=(",", ":"), ensure_ascii=False)
|
||||
reset_key = encrypt_internal_message(reset_data_json)
|
||||
assert reset_key, "Cannot generate reset key."
|
||||
reset_key_b64 = base64.b64encode(reset_key.encode()).decode()
|
||||
return f"reset_key_{reset_key_b64}"
|
||||
|
||||
|
||||
@users_router.get("/user/{user_id}/admin", dependencies=[Depends(check_super_user)])
|
||||
async def api_users_toggle_admin(user_id: str) -> None:
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user