mirror of
https://github.com/Kareadita/Kavita.git
synced 2025-05-24 00:52:23 -04:00
Ability to restrict a user's ability to change passwords (#1018)
* Implemented a new role "Change Password". This role allows you to change your own password. By default, all users will have it. A user can have it removed arbitrarliy. Removed components that are no longer going to be used. * Cleaned up some code
This commit is contained in:
parent
9d20343f4e
commit
6ee8320c2b
@ -20,8 +20,12 @@ namespace API.Constants
|
||||
/// Used to give a user ability to download files from the server
|
||||
/// </summary>
|
||||
public const string DownloadRole = "Download";
|
||||
/// <summary>
|
||||
/// Used to give a user ability to change their own password
|
||||
/// </summary>
|
||||
public const string ChangePasswordRole = "Change Password";
|
||||
|
||||
public static readonly ImmutableArray<string> ValidRoles =
|
||||
ImmutableArray.Create(AdminRole, PlebRole, DownloadRole);
|
||||
ImmutableArray.Create(AdminRole, PlebRole, DownloadRole, ChangePasswordRole);
|
||||
}
|
||||
}
|
||||
|
@ -73,7 +73,7 @@ namespace API.Controllers
|
||||
_logger.LogInformation("{UserName} is changing {ResetUser}'s password", User.GetUsername(), resetPasswordDto.UserName);
|
||||
var user = await _userManager.Users.SingleAsync(x => x.UserName == resetPasswordDto.UserName);
|
||||
|
||||
if (resetPasswordDto.UserName != User.GetUsername() && !User.IsInRole(PolicyConstants.AdminRole))
|
||||
if (resetPasswordDto.UserName != User.GetUsername() && !(User.IsInRole(PolicyConstants.AdminRole) || User.IsInRole(PolicyConstants.ChangePasswordRole)))
|
||||
return Unauthorized("You are not permitted to this operation.");
|
||||
|
||||
var errors = await _accountService.ChangeUserPassword(user, resetPasswordDto.Password);
|
||||
@ -245,45 +245,6 @@ namespace API.Controllers
|
||||
f => (string) f.GetValue(null)).Values.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the given roles to the user.
|
||||
/// </summary>
|
||||
/// <param name="updateRbsDto"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("update-rbs")]
|
||||
public async Task<ActionResult> UpdateRoles(UpdateRbsDto updateRbsDto)
|
||||
{
|
||||
var user = await _userManager.Users
|
||||
.Include(u => u.UserPreferences)
|
||||
.SingleOrDefaultAsync(x => x.NormalizedUserName == updateRbsDto.Username.ToUpper());
|
||||
if (updateRbsDto.Roles.Contains(PolicyConstants.AdminRole) ||
|
||||
updateRbsDto.Roles.Contains(PolicyConstants.PlebRole))
|
||||
{
|
||||
return BadRequest("Invalid Roles");
|
||||
}
|
||||
|
||||
var existingRoles = (await _userManager.GetRolesAsync(user))
|
||||
.Where(s => s != PolicyConstants.AdminRole && s != PolicyConstants.PlebRole)
|
||||
.ToList();
|
||||
|
||||
// Find what needs to be added and what needs to be removed
|
||||
var rolesToRemove = existingRoles.Except(updateRbsDto.Roles);
|
||||
var result = await _userManager.AddToRolesAsync(user, updateRbsDto.Roles);
|
||||
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
await _unitOfWork.RollbackAsync();
|
||||
return BadRequest("Something went wrong, unable to update user's roles");
|
||||
}
|
||||
if ((await _userManager.RemoveFromRolesAsync(user, rolesToRemove)).Succeeded)
|
||||
{
|
||||
return Ok();
|
||||
}
|
||||
|
||||
await _unitOfWork.RollbackAsync();
|
||||
return BadRequest("Something went wrong, unable to update user's roles");
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the API Key assigned with a user
|
||||
|
18
API/Data/MigrateChangePasswordRoles.cs
Normal file
18
API/Data/MigrateChangePasswordRoles.cs
Normal file
@ -0,0 +1,18 @@
|
||||
using System.Threading.Tasks;
|
||||
using API.Constants;
|
||||
using API.Entities;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace API.Data;
|
||||
|
||||
public static class MigrateChangePasswordRoles
|
||||
{
|
||||
public static async Task Migrate(IUnitOfWork unitOfWork, UserManager<AppUser> userManager)
|
||||
{
|
||||
foreach (var user in await unitOfWork.UserRepository.GetAllUsers())
|
||||
{
|
||||
await userManager.RemoveFromRoleAsync(user, "ChangePassword");
|
||||
await userManager.AddToRoleAsync(user, PolicyConstants.ChangePasswordRole);
|
||||
}
|
||||
}
|
||||
}
|
@ -52,6 +52,7 @@ public interface IUserRepository
|
||||
Task<AppUser> GetUserWithReadingListsByUsernameAsync(string username);
|
||||
Task<IList<AppUserBookmark>> GetAllBookmarksByIds(IList<int> bookmarkIds);
|
||||
Task<AppUser> GetUserByEmailAsync(string email);
|
||||
Task<IEnumerable<AppUser>> GetAllUsers();
|
||||
}
|
||||
|
||||
public class UserRepository : IUserRepository
|
||||
@ -214,6 +215,11 @@ public class UserRepository : IUserRepository
|
||||
return await _context.AppUser.SingleOrDefaultAsync(u => u.Email.ToLower().Equals(email.ToLower()));
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<AppUser>> GetAllUsers()
|
||||
{
|
||||
return await _context.AppUser.ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<AppUser>> GetAdminUsersAsync()
|
||||
{
|
||||
return await _userManager.GetUsersInRoleAsync(PolicyConstants.AdminRole);
|
||||
|
@ -67,6 +67,7 @@ namespace API.Extensions
|
||||
{
|
||||
opt.AddPolicy("RequireAdminRole", policy => policy.RequireRole(PolicyConstants.AdminRole));
|
||||
opt.AddPolicy("RequireDownloadRole", policy => policy.RequireRole(PolicyConstants.DownloadRole, PolicyConstants.AdminRole));
|
||||
opt.AddPolicy("RequireChangePasswordRole", policy => policy.RequireRole(PolicyConstants.ChangePasswordRole, PolicyConstants.AdminRole));
|
||||
});
|
||||
|
||||
return services;
|
||||
|
@ -6,6 +6,7 @@ using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading.Tasks;
|
||||
using API.Data;
|
||||
using API.Entities;
|
||||
using API.Extensions;
|
||||
using API.Middleware;
|
||||
using API.Services;
|
||||
@ -20,6 +21,7 @@ using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.ResponseCompression;
|
||||
using Microsoft.AspNetCore.StaticFiles;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
@ -140,27 +142,16 @@ namespace API
|
||||
Task.Run(async () =>
|
||||
{
|
||||
// Apply all migrations on startup
|
||||
// If we have pending migrations, make a backup first
|
||||
//var isDocker = new OsInfo(Array.Empty<IOsVersionAdapter>()).IsDocker;
|
||||
var logger = serviceProvider.GetRequiredService<ILogger<Program>>();
|
||||
var context = serviceProvider.GetRequiredService<DataContext>();
|
||||
// var pendingMigrations = await context.Database.GetPendingMigrationsAsync();
|
||||
// if (pendingMigrations.Any())
|
||||
// {
|
||||
// logger.LogInformation("Performing backup as migrations are needed");
|
||||
// await backupService.BackupDatabase();
|
||||
// }
|
||||
//
|
||||
// await context.Database.MigrateAsync();
|
||||
// var roleManager = serviceProvider.GetRequiredService<RoleManager<AppRole>>();
|
||||
//
|
||||
// await Seed.SeedRoles(roleManager);
|
||||
// await Seed.SeedSettings(context, directoryService);
|
||||
// await Seed.SeedUserApiKeys(context);
|
||||
var userManager = serviceProvider.GetRequiredService<UserManager<AppUser>>();
|
||||
|
||||
|
||||
await MigrateBookmarks.Migrate(directoryService, unitOfWork,
|
||||
logger, cacheService);
|
||||
|
||||
await MigrateChangePasswordRoles.Migrate(unitOfWork, userManager);
|
||||
|
||||
var requiresCoverImageMigration = !Directory.Exists(directoryService.CoverImageDirectory);
|
||||
try
|
||||
{
|
||||
|
@ -41,6 +41,10 @@ export class AccountService implements OnDestroy {
|
||||
return user && user.roles.includes('Admin');
|
||||
}
|
||||
|
||||
hasChangePasswordRole(user: User) {
|
||||
return user && user.roles.includes('Change Password');
|
||||
}
|
||||
|
||||
hasDownloadRole(user: User) {
|
||||
return user && user.roles.includes('Download');
|
||||
}
|
||||
|
@ -36,9 +36,6 @@ export class MemberService {
|
||||
return this.httpClient.get<boolean>(this.baseUrl + 'users/has-reading-progress?libraryId=' + librayId);
|
||||
}
|
||||
|
||||
updateMemberRoles(username: string, roles: string[]) {
|
||||
return this.httpClient.post(this.baseUrl + 'account/update-rbs', {username, roles});
|
||||
}
|
||||
|
||||
getPendingInvites() {
|
||||
return this.httpClient.get<Array<Member>>(this.baseUrl + 'users/pending');
|
||||
|
@ -1,23 +0,0 @@
|
||||
|
||||
<div class="modal-header">
|
||||
<h4 class="modal-title" id="modal-basic-title">Edit {{member?.username}}'s Roles</h4>
|
||||
<button type="button" class="close" aria-label="Close" (click)="close()">
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<ul class="list-group">
|
||||
<li class="list-group-item" *ngFor="let role of selectedRoles; let i = index">
|
||||
<div class="form-check">
|
||||
<input id="library-{{i}}" type="checkbox" attr.aria-label="Library {{role.data}}" class="form-check-input"
|
||||
[(ngModel)]="role.selected" name="library">
|
||||
<label attr.for="library-{{i}}" class="form-check-label">{{role.data}}</label>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-light" (click)="reset()">Reset</button>
|
||||
<button type="button" class="btn btn-secondary" (click)="close()">Cancel</button>
|
||||
<button type="button" class="btn btn-primary" (click)="save()">Save</button>
|
||||
</div>
|
@ -1,74 +0,0 @@
|
||||
import { Component, Input, OnInit } from '@angular/core';
|
||||
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { Member } from 'src/app/_models/member';
|
||||
import { AccountService } from 'src/app/_services/account.service';
|
||||
import { MemberService } from 'src/app/_services/member.service';
|
||||
|
||||
// TODO: Remove this component, edit-user will take over
|
||||
|
||||
@Component({
|
||||
selector: 'app-edit-rbs-modal',
|
||||
templateUrl: './edit-rbs-modal.component.html',
|
||||
styleUrls: ['./edit-rbs-modal.component.scss']
|
||||
})
|
||||
export class EditRbsModalComponent implements OnInit {
|
||||
|
||||
@Input() member: Member | undefined;
|
||||
allRoles: string[] = [];
|
||||
selectedRoles: Array<{selected: boolean, data: string}> = [];
|
||||
|
||||
constructor(public modal: NgbActiveModal, private accountService: AccountService, private memberService: MemberService) { }
|
||||
|
||||
ngOnInit(): void {
|
||||
this.accountService.getRoles().subscribe(roles => {
|
||||
roles = roles.filter(item => item != 'Admin' && item != 'Pleb'); // Do not allow the user to modify Account RBS
|
||||
this.allRoles = roles;
|
||||
this.selectedRoles = roles.map(item => {
|
||||
return {selected: false, data: item};
|
||||
});
|
||||
|
||||
this.preselect();
|
||||
});
|
||||
}
|
||||
|
||||
close() {
|
||||
this.modal.close(undefined);
|
||||
}
|
||||
|
||||
save() {
|
||||
if (this.member?.username === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedRoles = this.selectedRoles.filter(item => item.selected).map(item => item.data);
|
||||
this.memberService.updateMemberRoles(this.member?.username, selectedRoles).subscribe(() => {
|
||||
if (this.member) {
|
||||
this.member.roles = selectedRoles;
|
||||
this.modal.close(this.member);
|
||||
return;
|
||||
}
|
||||
this.modal.close(undefined);
|
||||
});
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.selectedRoles = this.allRoles.map(item => {
|
||||
return {selected: false, data: item};
|
||||
});
|
||||
|
||||
|
||||
this.preselect();
|
||||
}
|
||||
|
||||
preselect() {
|
||||
if (this.member !== undefined) {
|
||||
this.member.roles.forEach(role => {
|
||||
const foundRole = this.selectedRoles.filter(item => item.data === role);
|
||||
if (foundRole.length > 0) {
|
||||
foundRole[0].selected = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -12,7 +12,6 @@ import { DirectoryPickerComponent } from './_modals/directory-picker/directory-p
|
||||
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
|
||||
import { ResetPasswordModalComponent } from './_modals/reset-password-modal/reset-password-modal.component';
|
||||
import { ManageSettingsComponent } from './manage-settings/manage-settings.component';
|
||||
import { EditRbsModalComponent } from './_modals/edit-rbs-modal/edit-rbs-modal.component';
|
||||
import { ManageSystemComponent } from './manage-system/manage-system.component';
|
||||
import { ChangelogComponent } from './changelog/changelog.component';
|
||||
import { PipeModule } from '../pipe/pipe.module';
|
||||
@ -34,7 +33,6 @@ import { EditUserComponent } from './edit-user/edit-user.component';
|
||||
DirectoryPickerComponent,
|
||||
ResetPasswordModalComponent,
|
||||
ManageSettingsComponent,
|
||||
EditRbsModalComponent,
|
||||
ManageSystemComponent,
|
||||
ChangelogComponent,
|
||||
InviteUserComponent,
|
||||
|
@ -62,10 +62,6 @@
|
||||
<ng-template #showRoles>
|
||||
<app-tag-badge *ngFor="let role of getRoles(member)">{{role}}</app-tag-badge>
|
||||
</ng-template>
|
||||
<button class="btn btn-icon" attr.aria-labelledby="member-name--{{idx}}" title="{{hasAdminRole(member) ? 'Admins have all feature permissions' : 'Edit Role'}}" (click)="openEditRole(member)" [disabled]="hasAdminRole(member)">
|
||||
<i class="fa fa-pen" aria-hidden="true"></i>
|
||||
<span class="sr-only">Edit Role</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
|
@ -8,7 +8,6 @@ import { AccountService } from 'src/app/_services/account.service';
|
||||
import { ToastrService } from 'ngx-toastr';
|
||||
import { ResetPasswordModalComponent } from '../_modals/reset-password-modal/reset-password-modal.component';
|
||||
import { ConfirmService } from 'src/app/shared/confirm.service';
|
||||
import { EditRbsModalComponent } from '../_modals/edit-rbs-modal/edit-rbs-modal.component';
|
||||
import { Subject } from 'rxjs';
|
||||
import { MessageHubService } from 'src/app/_services/message-hub.service';
|
||||
import { InviteUserComponent } from '../invite-user/invite-user.component';
|
||||
@ -112,16 +111,6 @@ export class ManageUsersComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
openEditRole(member: Member) {
|
||||
const modalRef = this.modalService.open(EditRbsModalComponent);
|
||||
modalRef.componentInstance.member = member;
|
||||
modalRef.closed.subscribe((updatedMember: Member) => {
|
||||
if (updatedMember !== undefined) {
|
||||
member = updatedMember;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
inviteUser() {
|
||||
const modalRef = this.modalService.open(InviteUserComponent, {size: 'lg'});
|
||||
modalRef.closed.subscribe((successful: boolean) => {
|
||||
|
@ -194,7 +194,7 @@
|
||||
<app-series-bookmarks></app-series-bookmarks>
|
||||
</ng-container>
|
||||
<ng-container *ngIf="tab.fragment === 'password'">
|
||||
<ng-container *ngIf="isAdmin">
|
||||
<ng-container *ngIf="(isAdmin || hasChangePasswordRole); else noPermission">
|
||||
<p>Change your Password</p>
|
||||
<div class="alert alert-danger" role="alert" *ngIf="resetPasswordErrors.length > 0">
|
||||
<div *ngFor="let error of resetPasswordErrors">{{error}}</div>
|
||||
@ -227,6 +227,9 @@
|
||||
</div>
|
||||
</form>
|
||||
</ng-container>
|
||||
<ng-template #noPermission>
|
||||
<p>You do not have permission to change your password. Reach out to the admin of the server.</p>
|
||||
</ng-template>
|
||||
</ng-container>
|
||||
<ng-container *ngIf="tab.fragment === 'clients'">
|
||||
<p>All 3rd Party clients will either use the API key or the Connection Url below. These are like passwords, keep it private.</p>
|
||||
|
@ -11,6 +11,7 @@ import { AccountService } from 'src/app/_services/account.service';
|
||||
import { NavService } from 'src/app/_services/nav.service';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
import { SettingsService } from 'src/app/admin/settings.service';
|
||||
import { Member } from 'src/app/_models/member';
|
||||
|
||||
@Component({
|
||||
selector: 'app-user-preferences',
|
||||
@ -28,6 +29,7 @@ export class UserPreferencesComponent implements OnInit, OnDestroy {
|
||||
passwordChangeForm: FormGroup = new FormGroup({});
|
||||
user: User | undefined = undefined;
|
||||
isAdmin: boolean = false;
|
||||
hasChangePasswordRole: boolean = false;
|
||||
|
||||
passwordsMatch = false;
|
||||
resetPasswordErrors: string[] = [];
|
||||
@ -85,6 +87,7 @@ export class UserPreferencesComponent implements OnInit, OnDestroy {
|
||||
if (user) {
|
||||
this.user = user;
|
||||
this.isAdmin = this.accountService.hasAdminRole(user);
|
||||
this.hasChangePasswordRole = this.accountService.hasChangePasswordRole(user);
|
||||
|
||||
if (this.fontFamilies.indexOf(this.user.preferences.bookReaderFontFamily) < 0) {
|
||||
this.user.preferences.bookReaderFontFamily = 'default';
|
||||
|
Loading…
x
Reference in New Issue
Block a user