password change UI (#543) (#548)

This commit is contained in:
h44z
2025-10-15 21:11:40 +02:00
committed by GitHub
parent 139fb17f98
commit 3d923b328e
9 changed files with 459 additions and 178 deletions

View File

@@ -221,6 +221,16 @@
"button-delete-text": "Passkey löschen. Sie können sich anschließend nicht mehr mit diesem Passkey anmelden.", "button-delete-text": "Passkey löschen. Sie können sich anschließend nicht mehr mit diesem Passkey anmelden.",
"button-register-title": "Passkey registrieren", "button-register-title": "Passkey registrieren",
"button-register-text": "Einen neuen Passkey registrieren, um Ihr Konto zu sichern." "button-register-text": "Einen neuen Passkey registrieren, um Ihr Konto zu sichern."
},
"password": {
"headline": "Passwort-Einstellungen",
"abstract": "Hier können Sie Ihr Passwort ändern.",
"current-label": "Aktuelles Passwort",
"new-label": "Neues Passwort",
"new-confirm-label": "Neues Passwort bestätigen",
"change-button-text": "Passwort ändern",
"invalid-confirm-label": "Passwörter stimmen nicht überein",
"weak-label": "Passwort ist zu schwach"
} }
}, },
"audit": { "audit": {

View File

@@ -221,6 +221,16 @@
"button-delete-text": "Delete the passkey. You will not be able to log in with this passkey anymore.", "button-delete-text": "Delete the passkey. You will not be able to log in with this passkey anymore.",
"button-register-title": "Register Passkey", "button-register-title": "Register Passkey",
"button-register-text": "Register a new Passkey to secure your account." "button-register-text": "Register a new Passkey to secure your account."
},
"password": {
"headline": "Password Settings",
"abstract": "Here you can change your password.",
"current-label": "Current Password",
"new-label": "New Password",
"new-confirm-label": "Confirm New Password",
"change-button-text": "Change Password",
"invalid-confirm-label": "Passwords do not match",
"weak-label": "Password is too weak"
} }
}, },
"audit": { "audit": {

View File

@@ -151,6 +151,17 @@ export const profileStore = defineStore('profile', {
}) })
}) })
}, },
async changePassword(formData) {
this.fetching = true
let currentUser = authStore().user.Identifier
return apiWrapper.post(`${baseUrl}/${base64_url_encode(currentUser)}/change-password`, formData)
.then(this.fetching = false)
.catch(error => {
this.fetching = false;
console.log("Failed to change password for ", currentUser, ": ", error);
throw new Error(error);
});
},
async LoadPeers() { async LoadPeers() {
this.fetching = true this.fetching = true
let currentUser = authStore().user.Identifier let currentUser = authStore().user.Identifier

View File

@@ -1,8 +1,9 @@
<script setup> <script setup>
import {onMounted, ref} from "vue"; import {computed, onMounted, ref} from "vue";
import { profileStore } from "@/stores/profile"; import { profileStore } from "@/stores/profile";
import { settingsStore } from "@/stores/settings"; import { settingsStore } from "@/stores/settings";
import { authStore } from "../stores/auth"; import { authStore } from "../stores/auth";
import {notify} from "@kyvg/vue3-notification";
const profile = profileStore() const profile = profileStore()
const settings = settingsStore() const settings = settingsStore()
@@ -34,6 +35,45 @@ async function saveRename(credential) {
console.error("Failed to rename credential:", error); console.error("Failed to rename credential:", error);
} }
} }
const pwFormData = ref({
OldPassword: '',
Password: '',
PasswordRepeat: '',
})
const passwordWeak = computed(() => {
return pwFormData.value.Password && pwFormData.value.Password.length > 0 && pwFormData.value.Password.length < settings.Setting('MinPasswordLength')
})
const passwordChangeAllowed = computed(() => {
return pwFormData.value.Password && pwFormData.value.Password.length >= settings.Setting('MinPasswordLength') &&
pwFormData.value.Password === pwFormData.value.PasswordRepeat &&
pwFormData.value.OldPassword && pwFormData.value.OldPassword.length > 0 && pwFormData.value.OldPassword !== pwFormData.value.Password;
})
const updatePassword = async () => {
try {
await profile.changePassword(pwFormData.value);
pwFormData.value.OldPassword = '';
pwFormData.value.Password = '';
pwFormData.value.PasswordRepeat = '';
notify({
title: "Password changed!",
text: "Your password has been changed successfully.",
type: 'success',
});
} catch (e) {
notify({
title: "Failed to update password!",
text: e.toString(),
type: 'error',
})
}
}
</script> </script>
<template> <template>
@@ -43,54 +83,47 @@ async function saveRename(credential) {
<p class="lead">{{ $t('settings.abstract') }}</p> <p class="lead">{{ $t('settings.abstract') }}</p>
<div v-if="auth.IsAdmin || !settings.Setting('ApiAdminOnly')"> <div class="card border-secondary p-5 mt-5" v-if="profile.user.Source === 'db'">
<div class="card border-secondary p-5" v-if="profile.user.ApiToken"> <h2 class="display-7">{{ $t('settings.password.headline') }}</h2>
<h2 class="display-7">{{ $t('settings.api.headline') }}</h2> <p class="lead">{{ $t('settings.password.abstract') }}</p>
<p class="lead">{{ $t('settings.api.abstract') }}</p>
<hr class="my-4"> <hr class="my-4">
<p>{{ $t('settings.api.active-description') }}</p>
<div class="row"> <div class="row">
<div class="col-6"> <div class="col-6">
<div class="form-group"> <div class="form-group">
<label class="form-label mt-4">{{ $t('settings.api.user-label') }}</label> <label class="form-label mt-4" for="oldpw">{{ $t('settings.password.current-label') }}</label>
<input v-model="profile.user.Identifier" class="form-control" :placeholder="$t('settings.api.user-placeholder')" type="text" readonly> <input id="oldpw" v-model="pwFormData.OldPassword" class="form-control" :class="{ 'is-invalid': pwFormData.Password && !pwFormData.OldPassword }" type="password">
</div>
</div>
<div class="col-6">
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group has-success">
<label class="form-label mt-4" for="newpw">{{ $t('settings.password.new-label') }}</label>
<input id="newpw" v-model="pwFormData.Password" class="form-control" :class="{ 'is-invalid': passwordWeak, 'is-valid': pwFormData.Password !== '' && !passwordWeak }" type="password">
<div class="invalid-feedback" v-if="passwordWeak">{{ $t('settings.password.weak-label') }}</div>
</div> </div>
</div> </div>
<div class="col-6"> <div class="col-6">
<div class="form-group"> <div class="form-group">
<label class="form-label mt-4">{{ $t('settings.api.token-label') }}</label> <label class="form-label mt-4" for="confirmnewpw">{{ $t('settings.password.new-confirm-label') }}</label>
<input v-model="profile.user.ApiToken" class="form-control" :placeholder="$t('settings.api.token-placeholder')" type="text" readonly> <input id="confirmnewpw" v-model="pwFormData.PasswordRepeat" class="form-control" :class="{ 'is-invalid': pwFormData.PasswordRepeat !== ''&& pwFormData.Password !== pwFormData.PasswordRepeat, 'is-valid': pwFormData.PasswordRepeat !== '' && pwFormData.Password === pwFormData.PasswordRepeat && !passwordWeak }" type="password">
</div> <div class="invalid-feedback" v-if="pwFormData.PasswordRepeat !== ''&& pwFormData.Password !== pwFormData.PasswordRepeat">{{ $t('settings.password.invalid-confirm-label') }}</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="form-group">
<p class="form-label mt-4">{{ $t('settings.api.token-created-label') }} {{profile.user.ApiTokenCreated}}</p>
</div> </div>
</div> </div>
</div> </div>
<div class="row mt-5"> <div class="row mt-5">
<div class="col-6"> <div class="col-6">
<button class="btn btn-primary" :title="$t('settings.api.button-disable-title')" @click.prevent="profile.disableApi()" :disabled="profile.isFetching"> <button class="btn btn-primary" :title="$t('settings.api.button-disable-title')" @click.prevent="updatePassword" :disabled="profile.isFetching || !passwordChangeAllowed">
<i class="fa-solid fa-minus-circle"></i> {{ $t('settings.api.button-disable-text') }} <i class="fa-solid fa-floppy-disk"></i> {{ $t('settings.password.change-button-text') }}
</button> </button>
</div> </div>
<div class="col-6"> <div class="col-6">
<a href="/api/v1/doc.html" target="_blank" :alt="$t('settings.api.api-link')">{{ $t('settings.api.api-link') }}</a>
</div> </div>
</div> </div>
</div> </div>
<div class="card border-secondary p-5" v-else>
<h2 class="display-7">{{ $t('settings.api.headline') }}</h2>
<p class="lead">{{ $t('settings.api.abstract') }}</p>
<hr class="my-4">
<p>{{ $t('settings.api.inactive-description') }}</p>
<button class="btn btn-primary" :title="$t('settings.api.button-enable-title')" @click.prevent="profile.enableApi()" :disabled="profile.isFetching">
<i class="fa-solid fa-plus-circle"></i> {{ $t('settings.api.button-enable-text') }}
</button>
</div>
</div>
<div class="card border-secondary p-5 mt-5" v-if="settings.Setting('WebAuthnEnabled')"> <div class="card border-secondary p-5 mt-5" v-if="settings.Setting('WebAuthnEnabled')">
<h2 class="display-7">{{ $t('settings.webauthn.headline') }}</h2> <h2 class="display-7">{{ $t('settings.webauthn.headline') }}</h2>
@@ -173,4 +206,53 @@ async function saveRename(credential) {
</div> </div>
</div> </div>
<div class="mt-5" v-if="auth.IsAdmin || !settings.Setting('ApiAdminOnly')">
<div class="card border-secondary p-5" v-if="profile.user.ApiToken">
<h2 class="display-7">{{ $t('settings.api.headline') }}</h2>
<p class="lead">{{ $t('settings.api.abstract') }}</p>
<hr class="my-4">
<p>{{ $t('settings.api.active-description') }}</p>
<div class="row">
<div class="col-6">
<div class="form-group">
<label class="form-label mt-4">{{ $t('settings.api.user-label') }}</label>
<input v-model="profile.user.Identifier" class="form-control" :placeholder="$t('settings.api.user-placeholder')" type="text" readonly>
</div>
</div>
<div class="col-6">
<div class="form-group">
<label class="form-label mt-4">{{ $t('settings.api.token-label') }}</label>
<input v-model="profile.user.ApiToken" class="form-control" :placeholder="$t('settings.api.token-placeholder')" type="text" readonly>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="form-group">
<p class="form-label mt-4">{{ $t('settings.api.token-created-label') }} {{profile.user.ApiTokenCreated}}</p>
</div>
</div>
</div>
<div class="row mt-5">
<div class="col-6">
<button class="btn btn-primary" :title="$t('settings.api.button-disable-title')" @click.prevent="profile.disableApi()" :disabled="profile.isFetching">
<i class="fa-solid fa-minus-circle"></i> {{ $t('settings.api.button-disable-text') }}
</button>
</div>
<div class="col-6">
<a href="/api/v1/doc.html" target="_blank" :alt="$t('settings.api.api-link')">{{ $t('settings.api.api-link') }}</a>
</div>
</div>
</div>
<div class="card border-secondary p-5" v-else>
<h2 class="display-7">{{ $t('settings.api.headline') }}</h2>
<p class="lead">{{ $t('settings.api.abstract') }}</p>
<hr class="my-4">
<p>{{ $t('settings.api.inactive-description') }}</p>
<button class="btn btn-primary" :title="$t('settings.api.button-enable-title')" @click.prevent="profile.enableApi()" :disabled="profile.isFetching">
<i class="fa-solid fa-plus-circle"></i> {{ $t('settings.api.button-enable-text') }}
</button>
</div>
</div>
</template> </template>

View File

@@ -1550,6 +1550,38 @@
} }
} }
}, },
"/user/{id}/change-password": {
"post": {
"produces": [
"application/json"
],
"tags": [
"Users"
],
"summary": "Change the password for the given user.",
"operationId": "users_handleChangePasswordPost",
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/model.User"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/model.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/model.Error"
}
}
}
}
},
"/user/{id}/interfaces": { "/user/{id}/interfaces": {
"get": { "get": {
"produces": [ "produces": [
@@ -2159,6 +2191,10 @@
} }
] ]
}, },
"UserDisplayName": {
"description": "the owner display name",
"type": "string"
},
"UserIdentifier": { "UserIdentifier": {
"description": "the owner", "description": "the owner",
"type": "string" "type": "string"

View File

@@ -322,6 +322,9 @@ definitions:
allOf: allOf:
- $ref: '#/definitions/model.ConfigOption-string' - $ref: '#/definitions/model.ConfigOption-string'
description: the routing table description: the routing table
UserDisplayName:
description: the owner display name
type: string
UserIdentifier: UserIdentifier:
description: the owner description: the owner
type: string type: string
@@ -1442,6 +1445,27 @@ paths:
summary: Enable the REST API for the given user. summary: Enable the REST API for the given user.
tags: tags:
- Users - Users
/user/{id}/change-password:
post:
operationId: users_handleChangePasswordPost
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/model.User'
"400":
description: Bad Request
schema:
$ref: '#/definitions/model.Error'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/model.Error'
summary: Change the password for the given user.
tags:
- Users
/user/{id}/interfaces: /user/{id}/interfaces:
get: get:
operationId: users_handleInterfacesGet operationId: users_handleInterfacesGet

View File

@@ -17,11 +17,6 @@
"paths": { "paths": {
"/interface/all": { "/interface/all": {
"get": { "get": {
"security": [
{
"BasicAuth": []
}
],
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -52,16 +47,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/interface/by-id/{id}": {
"get": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/interface/by-id/{id}": {
"get": {
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -110,14 +105,14 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}, },
"put": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
},
"put": {
"description": "This endpoint updates an existing interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...).", "description": "This endpoint updates an existing interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...).",
"produces": [ "produces": [
"application/json" "application/json"
@@ -182,14 +177,14 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}, },
"delete": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
},
"delete": {
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -241,16 +236,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/interface/new": {
"post": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/interface/new": {
"post": {
"description": "This endpoint creates a new interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...).", "description": "This endpoint creates a new interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...).",
"produces": [ "produces": [
"application/json" "application/json"
@@ -308,16 +303,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/interface/prepare": {
"get": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/interface/prepare": {
"get": {
"description": "This endpoint returns a new interface with default values (fresh key pair, valid name, new IP address pool, ...).", "description": "This endpoint returns a new interface with default values (fresh key pair, valid name, new IP address pool, ...).",
"produces": [ "produces": [
"application/json" "application/json"
@@ -352,16 +347,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/metrics/by-interface/{id}": {
"get": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/metrics/by-interface/{id}": {
"get": {
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -410,16 +405,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/metrics/by-peer/{id}": {
"get": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/metrics/by-peer/{id}": {
"get": {
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -468,16 +463,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/metrics/by-user/{id}": {
"get": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/metrics/by-user/{id}": {
"get": {
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -526,16 +521,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/peer/by-id/{id}": {
"get": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/peer/by-id/{id}": {
"get": {
"description": "Normal users can only access their own records. Admins can access all records.", "description": "Normal users can only access their own records. Admins can access all records.",
"produces": [ "produces": [
"application/json" "application/json"
@@ -585,14 +580,14 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}, },
"put": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
},
"put": {
"description": "Only admins can update existing records. The peer record must contain all required fields (e.g., public key, allowed IPs).", "description": "Only admins can update existing records. The peer record must contain all required fields (e.g., public key, allowed IPs).",
"produces": [ "produces": [
"application/json" "application/json"
@@ -657,14 +652,14 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}, },
"delete": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
},
"delete": {
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -716,16 +711,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/peer/by-interface/{id}": {
"get": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/peer/by-interface/{id}": {
"get": {
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -765,16 +760,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/peer/by-user/{id}": {
"get": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/peer/by-user/{id}": {
"get": {
"description": "Normal users can only access their own records. Admins can access all records.", "description": "Normal users can only access their own records. Admins can access all records.",
"produces": [ "produces": [
"application/json" "application/json"
@@ -815,16 +810,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/peer/new": {
"post": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/peer/new": {
"post": {
"description": "Only admins can create new records. The peer record must contain all required fields (e.g., public key, allowed IPs).", "description": "Only admins can create new records. The peer record must contain all required fields (e.g., public key, allowed IPs).",
"produces": [ "produces": [
"application/json" "application/json"
@@ -882,16 +877,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/peer/prepare/{id}": {
"get": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/peer/prepare/{id}": {
"get": {
"description": "This endpoint is used to prepare a new peer record. The returned data contains a fresh key pair and valid ip address.", "description": "This endpoint is used to prepare a new peer record. The returned data contains a fresh key pair and valid ip address.",
"produces": [ "produces": [
"application/json" "application/json"
@@ -947,16 +942,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/provisioning/data/peer-config": {
"get": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/provisioning/data/peer-config": {
"get": {
"description": "Normal users can only access their own record. Admins can access all records.", "description": "Normal users can only access their own record. Admins can access all records.",
"produces": [ "produces": [
"text/plain", "text/plain",
@@ -1013,16 +1008,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/provisioning/data/peer-qr": {
"get": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/provisioning/data/peer-qr": {
"get": {
"description": "Normal users can only access their own record. Admins can access all records.", "description": "Normal users can only access their own record. Admins can access all records.",
"produces": [ "produces": [
"image/png", "image/png",
@@ -1079,16 +1074,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/provisioning/data/user-info": {
"get": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/provisioning/data/user-info": {
"get": {
"description": "Normal users can only access their own record. Admins can access all records.", "description": "Normal users can only access their own record. Admins can access all records.",
"produces": [ "produces": [
"application/json" "application/json"
@@ -1149,16 +1144,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/provisioning/new-peer": {
"post": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/provisioning/new-peer": {
"post": {
"description": "Normal users can only create new peers if self provisioning is allowed. Admins can always add new peers.", "description": "Normal users can only create new peers if self provisioning is allowed. Admins can always add new peers.",
"produces": [ "produces": [
"application/json" "application/json"
@@ -1216,16 +1211,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/user/all": {
"get": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/user/all": {
"get": {
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -1256,16 +1251,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/user/by-id/{id}": {
"get": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/user/by-id/{id}": {
"get": {
"description": "Normal users can only access their own record. Admins can access all records.", "description": "Normal users can only access their own record. Admins can access all records.",
"produces": [ "produces": [
"application/json" "application/json"
@@ -1315,14 +1310,14 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}, },
"put": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
},
"put": {
"description": "Only admins can update existing records.", "description": "Only admins can update existing records.",
"produces": [ "produces": [
"application/json" "application/json"
@@ -1387,14 +1382,14 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}, },
"delete": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
},
"delete": {
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -1446,16 +1441,16 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
}
}
}, },
"/user/new": {
"post": {
"security": [ "security": [
{ {
"BasicAuth": [] "BasicAuth": []
} }
], ]
}
},
"/user/new": {
"post": {
"description": "Only admins can create new records.", "description": "Only admins can create new records.",
"produces": [ "produces": [
"application/json" "application/json"
@@ -1513,7 +1508,12 @@
"$ref": "#/definitions/models.Error" "$ref": "#/definitions/models.Error"
} }
} }
},
"security": [
{
"BasicAuth": []
} }
]
} }
} }
}, },

View File

@@ -2,6 +2,8 @@ package backend
import ( import (
"context" "context"
"fmt"
"strings"
"github.com/h44z/wg-portal/internal/config" "github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain" "github.com/h44z/wg-portal/internal/domain"
@@ -70,6 +72,44 @@ func (u UserService) DeactivateApi(ctx context.Context, id domain.UserIdentifier
return u.users.DeactivateApi(ctx, id) return u.users.DeactivateApi(ctx, id)
} }
func (u UserService) ChangePassword(ctx context.Context, id domain.UserIdentifier, oldPassword, newPassword string) (*domain.User, error) {
oldPassword = strings.TrimSpace(oldPassword)
newPassword = strings.TrimSpace(newPassword)
if newPassword == "" {
return nil, fmt.Errorf("new password must not be empty")
}
// ensure that the new password is different from the old one
if oldPassword == newPassword {
return nil, fmt.Errorf("new password must be different from the old one")
}
user, err := u.users.GetUser(ctx, id)
if err != nil {
return nil, fmt.Errorf("failed to get user: %w", err)
}
// ensure that the user uses the database backend; otherwise we can't change the password
if user.Source != domain.UserSourceDatabase {
return nil, fmt.Errorf("user source %s does not support password changes", user.Source)
}
// validate old password
if user.CheckPassword(oldPassword) != nil {
return nil, fmt.Errorf("current password is invalid")
}
user.Password = domain.PrivateString(newPassword)
// ensure that the new password is strong enough
if err := user.HasWeakPassword(u.cfg.Auth.MinPasswordLength); err != nil {
return nil, err
}
return u.users.UpdateUser(ctx, user)
}
func (u UserService) GetUserPeers(ctx context.Context, id domain.UserIdentifier) ([]domain.Peer, error) { func (u UserService) GetUserPeers(ctx context.Context, id domain.UserIdentifier) ([]domain.Peer, error) {
return u.wg.GetUserPeers(ctx, id) return u.wg.GetUserPeers(ctx, id)
} }

View File

@@ -28,6 +28,8 @@ type UserService interface {
ActivateApi(ctx context.Context, id domain.UserIdentifier) (*domain.User, error) ActivateApi(ctx context.Context, id domain.UserIdentifier) (*domain.User, error)
// DeactivateApi disables the API for the user with the given id. // DeactivateApi disables the API for the user with the given id.
DeactivateApi(ctx context.Context, id domain.UserIdentifier) (*domain.User, error) DeactivateApi(ctx context.Context, id domain.UserIdentifier) (*domain.User, error)
// ChangePassword changes the password for the user with the given id.
ChangePassword(ctx context.Context, id domain.UserIdentifier, oldPassword, newPassword string) (*domain.User, error)
// GetUserPeers returns all peers for the given user. // GetUserPeers returns all peers for the given user.
GetUserPeers(ctx context.Context, id domain.UserIdentifier) ([]domain.Peer, error) GetUserPeers(ctx context.Context, id domain.UserIdentifier) ([]domain.Peer, error)
// GetUserPeerStats returns all peer stats for the given user. // GetUserPeerStats returns all peer stats for the given user.
@@ -75,6 +77,7 @@ func (e UserEndpoint) RegisterRoutes(g *routegroup.Bundle) {
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("GET /{id}/interfaces", e.handleInterfacesGet()) apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("GET /{id}/interfaces", e.handleInterfacesGet())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("POST /{id}/api/enable", e.handleApiEnablePost()) apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("POST /{id}/api/enable", e.handleApiEnablePost())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("POST /{id}/api/disable", e.handleApiDisablePost()) apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("POST /{id}/api/disable", e.handleApiDisablePost())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("POST /{id}/change-password", e.handleChangePasswordPost())
} }
// handleAllGet returns a gorm Handler function. // handleAllGet returns a gorm Handler function.
@@ -391,3 +394,68 @@ func (e UserEndpoint) handleApiDisablePost() http.HandlerFunc {
respond.JSON(w, http.StatusOK, model.NewUser(user, false)) respond.JSON(w, http.StatusOK, model.NewUser(user, false))
} }
} }
// handleChangePasswordPost returns a gorm Handler function.
//
// @ID users_handleChangePasswordPost
// @Tags Users
// @Summary Change the password for the given user.
// @Produce json
// @Success 200 {object} model.User
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /user/{id}/change-password [post]
func (e UserEndpoint) handleChangePasswordPost() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userId := Base64UrlDecode(request.Path(r, "id"))
if userId == "" {
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusInternalServerError, Message: "missing id parameter"})
return
}
var passwordData struct {
OldPassword string `json:"OldPassword"`
Password string `json:"Password"`
PasswordRepeat string `json:"PasswordRepeat"`
}
if err := request.BodyJson(r, &passwordData); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if passwordData.OldPassword == "" {
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "old password missing"})
return
}
if passwordData.Password == "" {
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "new password missing"})
return
}
if passwordData.OldPassword == passwordData.Password {
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "password did not change"})
return
}
if passwordData.Password != passwordData.PasswordRepeat {
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "password mismatch"})
return
}
user, err := e.userService.ChangePassword(r.Context(), domain.UserIdentifier(userId),
passwordData.OldPassword, passwordData.Password)
if err != nil {
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
respond.JSON(w, http.StatusOK, model.NewUser(user, false))
}
}