ChangePasswordCard.jsx 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. "use client";
  2. import React from "react";
  3. import { useAuth } from "@/components/auth/authContext";
  4. import { changePassword, ApiClientError } from "@/lib/frontend/apiClient";
  5. import {
  6. notifyError,
  7. notifySuccess,
  8. notifyApiError,
  9. } from "@/lib/frontend/ui/toast";
  10. import { buildLoginUrl, LOGIN_REASONS } from "@/lib/frontend/authRedirect";
  11. import {
  12. getPasswordPolicyHintLinesDe,
  13. reasonsToHintLinesDe,
  14. buildWeakPasswordMessageDe,
  15. } from "@/lib/frontend/profile/passwordPolicyUi";
  16. import { Button } from "@/components/ui/button";
  17. import { Input } from "@/components/ui/input";
  18. import { Label } from "@/components/ui/label";
  19. import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert";
  20. import {
  21. Card,
  22. CardHeader,
  23. CardTitle,
  24. CardDescription,
  25. CardContent,
  26. CardFooter,
  27. } from "@/components/ui/card";
  28. function isNonEmptyString(value) {
  29. return typeof value === "string" && value.trim().length > 0;
  30. }
  31. export default function ChangePasswordCard() {
  32. const { status, user } = useAuth();
  33. const isAuthenticated = status === "authenticated" && user;
  34. const [currentPassword, setCurrentPassword] = React.useState("");
  35. const [newPassword, setNewPassword] = React.useState("");
  36. const [confirmNewPassword, setConfirmNewPassword] = React.useState("");
  37. const [isSubmitting, setIsSubmitting] = React.useState(false);
  38. const [error, setError] = React.useState(null);
  39. // error: { title: string, description?: string|null, field?: string|null, hints?: string[]|null }
  40. const policyLines = React.useMemo(() => {
  41. return getPasswordPolicyHintLinesDe();
  42. }, []);
  43. function clearForm() {
  44. setCurrentPassword("");
  45. setNewPassword("");
  46. setConfirmNewPassword("");
  47. }
  48. function redirectToLoginExpired() {
  49. const next =
  50. typeof window !== "undefined"
  51. ? `${window.location.pathname}${window.location.search}`
  52. : "/profile";
  53. window.location.replace(
  54. buildLoginUrl({ reason: LOGIN_REASONS.EXPIRED, next }),
  55. );
  56. }
  57. async function onSubmit(e) {
  58. e.preventDefault();
  59. if (isSubmitting) return;
  60. setError(null);
  61. if (!isAuthenticated) {
  62. notifyError({
  63. title: "Nicht angemeldet",
  64. description: "Bitte melden Sie sich an, um Ihr Passwort zu ändern.",
  65. });
  66. return;
  67. }
  68. if (!isNonEmptyString(currentPassword)) {
  69. setError({
  70. field: "currentPassword",
  71. title: "Bitte aktuelles Passwort eingeben.",
  72. description: null,
  73. });
  74. return;
  75. }
  76. if (!isNonEmptyString(newPassword)) {
  77. setError({
  78. field: "newPassword",
  79. title: "Bitte ein neues Passwort eingeben.",
  80. description: null,
  81. });
  82. return;
  83. }
  84. if (!isNonEmptyString(confirmNewPassword)) {
  85. setError({
  86. field: "confirmNewPassword",
  87. title: "Bitte neues Passwort bestätigen.",
  88. description: null,
  89. });
  90. return;
  91. }
  92. if (newPassword !== confirmNewPassword) {
  93. setError({
  94. field: "confirmNewPassword",
  95. title: "Passwörter stimmen nicht überein.",
  96. description: "Bitte prüfen Sie die Bestätigung.",
  97. });
  98. return;
  99. }
  100. if (newPassword === currentPassword) {
  101. setError({
  102. field: "newPassword",
  103. title: "Neues Passwort ist ungültig.",
  104. description:
  105. "Neues Passwort darf nicht identisch zum aktuellen Passwort sein.",
  106. });
  107. return;
  108. }
  109. setIsSubmitting(true);
  110. try {
  111. await changePassword({
  112. currentPassword,
  113. newPassword,
  114. });
  115. clearForm();
  116. notifySuccess({
  117. title: "Passwort geändert",
  118. description: "Ihr Passwort wurde erfolgreich aktualisiert.",
  119. });
  120. } catch (err) {
  121. if (err instanceof ApiClientError) {
  122. if (err.code === "AUTH_UNAUTHENTICATED") {
  123. notifyApiError(err);
  124. redirectToLoginExpired();
  125. return;
  126. }
  127. if (err.code === "AUTH_INVALID_CREDENTIALS") {
  128. const title = "Aktuelles Passwort ist falsch.";
  129. setError({ field: "currentPassword", title, description: null });
  130. notifyError({ title });
  131. return;
  132. }
  133. if (err.code === "VALIDATION_WEAK_PASSWORD") {
  134. const reasons = err.details?.reasons;
  135. const minLength = err.details?.minLength;
  136. const hints = reasonsToHintLinesDe({ reasons, minLength });
  137. const description = buildWeakPasswordMessageDe({
  138. reasons,
  139. minLength,
  140. });
  141. setError({
  142. field: "newPassword",
  143. title: "Neues Passwort ist zu schwach.",
  144. description,
  145. hints,
  146. });
  147. notifyError({
  148. title: "Neues Passwort ist zu schwach.",
  149. description,
  150. });
  151. return;
  152. }
  153. }
  154. setError({
  155. field: null,
  156. title: "Passwort konnte nicht geändert werden.",
  157. description: "Bitte versuchen Sie es erneut.",
  158. });
  159. notifyApiError(err, {
  160. fallbackTitle: "Passwort konnte nicht geändert werden.",
  161. fallbackDescription: "Bitte versuchen Sie es erneut.",
  162. });
  163. } finally {
  164. setIsSubmitting(false);
  165. }
  166. }
  167. const showError = Boolean(error && error.title);
  168. return (
  169. <Card>
  170. <CardHeader>
  171. <CardTitle>Passwort</CardTitle>
  172. <CardDescription>Ändern Sie Ihr Passwort.</CardDescription>
  173. </CardHeader>
  174. <CardContent className="space-y-4">
  175. {!isAuthenticated ? (
  176. <p className="text-sm text-muted-foreground">
  177. Hinweis: Passwortänderungen sind nur verfügbar, wenn Sie angemeldet
  178. sind.
  179. </p>
  180. ) : null}
  181. {showError ? (
  182. <Alert variant="destructive">
  183. <AlertTitle>{error.title}</AlertTitle>
  184. {error.description ? (
  185. <AlertDescription>{error.description}</AlertDescription>
  186. ) : null}
  187. {Array.isArray(error.hints) && error.hints.length > 0 ? (
  188. <AlertDescription>
  189. <ul className="mt-2 list-disc pl-5">
  190. {error.hints.map((line) => (
  191. <li key={line}>{line}</li>
  192. ))}
  193. </ul>
  194. </AlertDescription>
  195. ) : null}
  196. </Alert>
  197. ) : null}
  198. <form onSubmit={onSubmit} className="space-y-4">
  199. <div className="grid gap-2">
  200. <Label htmlFor="currentPassword">Aktuelles Passwort</Label>
  201. <Input
  202. id="currentPassword"
  203. type="password"
  204. autoComplete="current-password"
  205. value={currentPassword}
  206. onChange={(e) => setCurrentPassword(e.target.value)}
  207. disabled={!isAuthenticated || isSubmitting}
  208. aria-invalid={
  209. error?.field === "currentPassword" ? "true" : "false"
  210. }
  211. />
  212. </div>
  213. <div className="grid gap-2">
  214. <Label htmlFor="newPassword">Neues Passwort</Label>
  215. <Input
  216. id="newPassword"
  217. type="password"
  218. autoComplete="new-password"
  219. value={newPassword}
  220. onChange={(e) => setNewPassword(e.target.value)}
  221. disabled={!isAuthenticated || isSubmitting}
  222. aria-invalid={error?.field === "newPassword" ? "true" : "false"}
  223. />
  224. <ul className="mt-1 list-disc pl-5 text-xs text-muted-foreground">
  225. {policyLines.map((line) => (
  226. <li key={line}>{line}</li>
  227. ))}
  228. </ul>
  229. </div>
  230. <div className="grid gap-2">
  231. <Label htmlFor="confirmNewPassword">
  232. Neues Passwort bestätigen
  233. </Label>
  234. <Input
  235. id="confirmNewPassword"
  236. type="password"
  237. autoComplete="new-password"
  238. value={confirmNewPassword}
  239. onChange={(e) => setConfirmNewPassword(e.target.value)}
  240. disabled={!isAuthenticated || isSubmitting}
  241. aria-invalid={
  242. error?.field === "confirmNewPassword" ? "true" : "false"
  243. }
  244. />
  245. </div>
  246. <CardFooter className="p-0 flex justify-end">
  247. <Button
  248. type="submit"
  249. disabled={!isAuthenticated || isSubmitting}
  250. title={!isAuthenticated ? "Bitte anmelden" : "Passwort ändern"}
  251. >
  252. {isSubmitting ? "Speichern…" : "Passwort ändern"}
  253. </Button>
  254. </CardFooter>
  255. </form>
  256. </CardContent>
  257. </Card>
  258. );
  259. }