feat: user profile/settings pages (#958)

pull/946/head
sct 4 years ago committed by GitHub
parent 29b97ef6d8
commit bbb683e637
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -36,6 +36,7 @@ These variables are usually the target user of the notification.
- `{{notifyuser_username}}` Target user's username.
- `{{notifyuser_email}}` Target user's email.
- `{{notifyuser_avatar}}` Target user's avatar.
- `{{notifyuser_settings_discordId}}` Target user's discord ID (if one is set).
### Media

@ -82,11 +82,23 @@ components:
readOnly: true
items:
$ref: '#/components/schemas/MediaRequest'
settings:
$ref: '#/components/schemas/UserSettings'
required:
- id
- email
- createdAt
- updatedAt
UserSettings:
type: object
properties:
enableNotifications:
type: boolean
default: true
discordId:
type: string
required:
- enableNotifications
MainSettings:
type: object
properties:
@ -1514,6 +1526,17 @@ components:
searchForMissingEpisodes:
type: boolean
nullable: true
UserSettingsNotifications:
type: object
properties:
enableNotifications:
type: boolean
default: true
discordId:
type: string
nullable: true
required:
- enableNotifications
securitySchemes:
cookieAuth:
type: apiKey
@ -2876,6 +2899,250 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/User'
/user/{userId}/requests:
get:
summary: Get user by ID
description: |
Retrieves a user's requests in a JSON object.
tags:
- users
parameters:
- in: path
name: userId
required: true
schema:
type: number
- in: query
name: take
schema:
type: number
nullable: true
example: 20
- in: query
name: skip
schema:
type: number
nullable: true
example: 0
responses:
'200':
description: User's requests returned
content:
application/json:
schema:
type: object
properties:
pageInfo:
$ref: '#/components/schemas/PageInfo'
results:
type: array
items:
$ref: '#/components/schemas/MediaRequest'
/user/{userId}/settings/main:
get:
summary: Get general settings for a user
description: Returns general settings for a specific user. Requires `MANAGE_USERS` permission if viewing other users.
tags:
- users
parameters:
- in: path
name: userId
required: true
schema:
type: number
responses:
'200':
description: User general settings returned
content:
application/json:
schema:
type: object
properties:
username:
type: string
example: 'Mr User'
post:
summary: Update general settings for a user
description: Updates and returns general settings for a specific user. Requires `MANAGE_USERS` permission if editing other users.
tags:
- users
parameters:
- in: path
name: userId
required: true
schema:
type: number
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
username:
type: string
nullable: true
responses:
'200':
description: Updated user general settings returned
content:
application/json:
schema:
type: object
properties:
username:
type: string
example: 'Mr User'
/user/{userId}/settings/password:
get:
summary: Get password page informatiom
description: Returns important data for the password page to function correctly. Requires `MANAGE_USERS` permission if viewing other users.
tags:
- users
parameters:
- in: path
name: userId
required: true
schema:
type: number
responses:
'200':
description: User password page information returned
content:
application/json:
schema:
type: object
properties:
hasPassword:
type: boolean
example: true
post:
summary: Update password for a user
description: Updates a user's password. Requires `MANAGE_USERS` permission if editing other users.
tags:
- users
parameters:
- in: path
name: userId
required: true
schema:
type: number
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
currentPassword:
type: string
nullable: true
newPassword:
type: string
required:
- newPassword
responses:
'204':
description: User password updated
/user/{userId}/settings/notifications:
get:
summary: Get notification settings for a user
description: Returns notification settings for a specific user. Requires `MANAGE_USERS` permission if viewing other users.
tags:
- users
parameters:
- in: path
name: userId
required: true
schema:
type: number
responses:
'200':
description: User notification settings returned
content:
application/json:
schema:
$ref: '#/components/schemas/UserSettingsNotifications'
post:
summary: Update notification settings for a user
description: Updates and returns notification settings for a specific user. Requires `MANAGE_USERS` permission if editing other users.
tags:
- users
parameters:
- in: path
name: userId
required: true
schema:
type: number
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/UserSettingsNotifications'
responses:
'200':
description: Updated user notification settings returned
content:
application/json:
schema:
$ref: '#/components/schemas/UserSettingsNotifications'
/user/{userId}/settings/permissions:
get:
summary: Get permission settings for a user
description: Returns permission settings for a specific user. Requires `MANAGE_USERS` permission if viewing other users.
tags:
- users
parameters:
- in: path
name: userId
required: true
schema:
type: number
responses:
'200':
description: User permission settings returned
content:
application/json:
schema:
type: object
properties:
permissions:
type: number
example: 2
post:
summary: Update permission settings for a user
description: Updates and returns permission settings for a specific user. Requires `MANAGE_USERS` permission if editing other users.
tags:
- users
parameters:
- in: path
name: userId
required: true
schema:
type: number
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
permissions:
type: number
required:
- permissions
responses:
'200':
description: Updated user general settings returned
content:
application/json:
schema:
type: object
properties:
permissions:
type: number
example: 2
/search:
get:
summary: Search for movies, TV shows, or people

@ -7,6 +7,7 @@ import {
OneToMany,
RelationCount,
AfterLoad,
OneToOne,
} from 'typeorm';
import {
Permission,
@ -22,18 +23,18 @@ import { getSettings } from '../lib/settings';
import { default as generatePassword } from 'secure-random-password';
import { UserType } from '../constants/user';
import { v4 as uuid } from 'uuid';
import { UserSettings } from './UserSettings';
@Entity()
export class User {
public static filterMany(users: User[]): Partial<User>[] {
return users.map((u) => u.filter());
public static filterMany(
users: User[],
showFiltered?: boolean
): Partial<User>[] {
return users.map((u) => u.filter(showFiltered));
}
static readonly filteredFields: string[] = [
'plexToken',
'password',
'resetPasswordGuid',
];
static readonly filteredFields: string[] = ['email'];
public displayName: string;
@ -79,6 +80,13 @@ export class User {
@OneToMany(() => MediaRequest, (request) => request.requestedBy)
public requests: MediaRequest[];
@OneToOne(() => UserSettings, (settings) => settings.user, {
cascade: true,
eager: true,
onDelete: 'CASCADE',
})
public settings?: UserSettings;
@CreateDateColumn()
public createdAt: Date;
@ -89,11 +97,11 @@ export class User {
Object.assign(this, init);
}
public filter(): Partial<User> {
public filter(showFiltered?: boolean): Partial<User> {
const filtered: Partial<User> = Object.assign(
{},
...(Object.keys(this) as (keyof User)[])
.filter((k) => !User.filteredFields.includes(k))
.filter((k) => showFiltered || !User.filteredFields.includes(k))
.map((k) => ({ [k]: this[k] }))
);

@ -0,0 +1,28 @@
import {
Column,
Entity,
JoinColumn,
OneToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
import { User } from './User';
@Entity()
export class UserSettings {
constructor(init?: Partial<UserSettings>) {
Object.assign(this, init);
}
@PrimaryGeneratedColumn()
public id: number;
@OneToOne(() => User, (user) => user.settings, { onDelete: 'CASCADE' })
@JoinColumn()
public user: User;
@Column({ default: true })
public enableNotifications: boolean;
@Column({ nullable: true })
public discordId?: string;
}

@ -0,0 +1,6 @@
import { MediaRequest } from '../../entity/MediaRequest';
import { PaginatedResponse } from './common';
export interface UserRequestsResponse extends PaginatedResponse {
results: MediaRequest[];
}

@ -0,0 +1,4 @@
export interface UserSettingsNotificationsResponse {
enableNotifications: boolean;
discordId?: string;
}

@ -24,6 +24,6 @@ export abstract class BaseAgent<T extends NotificationAgentConfig> {
}
export interface NotificationAgent {
shouldSend(type: Notification): boolean;
shouldSend(type: Notification, payload: NotificationPayload): boolean;
send(type: Notification, payload: NotificationPayload): Promise<boolean>;
}

@ -74,6 +74,12 @@ interface DiscordWebhookPayload {
username: string;
avatar_url?: string;
tts: boolean;
content?: string;
allowed_mentions?: {
parse?: ('users' | 'roles' | 'everyone')[];
roles?: string[];
users?: string[];
};
}
class DiscordAgent
@ -204,9 +210,24 @@ class DiscordAgent
return false;
}
const mentionedUsers: string[] = [];
let content = undefined;
if (
payload.notifyUser.settings?.enableNotifications &&
payload.notifyUser.settings?.discordId
) {
mentionedUsers.push(payload.notifyUser.settings.discordId);
content = `<@${payload.notifyUser.settings.discordId}>`;
}
await axios.post(webhookUrl, {
username: settings.main.applicationTitle,
embeds: [this.buildEmbed(type, payload)],
content,
allowed_mentions: {
users: mentionedUsers,
},
} as DiscordWebhookPayload);
return true;
@ -214,6 +235,7 @@ class DiscordAgent
logger.error('Error sending Discord notification', {
label: 'Notifications',
message: e.message,
response: e.response.data,
});
return false;
}

@ -21,12 +21,13 @@ class EmailAgent
return settings.notifications.agents.email;
}
public shouldSend(type: Notification): boolean {
public shouldSend(type: Notification, payload: NotificationPayload): boolean {
const settings = this.getSettings();
if (
settings.enabled &&
hasNotificationType(type, this.getSettings().types)
hasNotificationType(type, this.getSettings().types) &&
(payload.notifyUser.settings?.enableNotifications ?? true)
) {
return true;
}

@ -19,6 +19,7 @@ const KeyMap: Record<string, string | KeyMapFunction> = {
notifyuser_username: 'notifyUser.displayName',
notifyuser_email: 'notifyUser.email',
notifyuser_avatar: 'notifyUser.avatar',
notifyuser_settings_discordId: 'notifyUser.settings.discordId',
media_tmdbid: 'media.tmdbId',
media_imdbid: 'media.imdbId',
media_tvdbid: 'media.tvdbId',

@ -49,7 +49,7 @@ class NotificationManager {
label: 'Notifications',
});
this.activeAgents.forEach((agent) => {
if (settings.enabled && agent.shouldSend(type)) {
if (settings.enabled && agent.shouldSend(type, payload)) {
agent.send(type, payload);
}
});

@ -0,0 +1,35 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateUserSettings1613615266968 implements MigrationInterface {
name = 'CreateUserSettings1613615266968';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "user_settings" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "enableNotifications" boolean NOT NULL DEFAULT (1), "discordId" varchar, "userId" integer, CONSTRAINT "REL_986a2b6d3c05eb4091bb8066f7" UNIQUE ("userId"))`
);
await queryRunner.query(
`CREATE TABLE "temporary_user_settings" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "enableNotifications" boolean NOT NULL DEFAULT (1), "discordId" varchar, "userId" integer, CONSTRAINT "REL_986a2b6d3c05eb4091bb8066f7" UNIQUE ("userId"), CONSTRAINT "FK_986a2b6d3c05eb4091bb8066f78" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`
);
await queryRunner.query(
`INSERT INTO "temporary_user_settings"("id", "enableNotifications", "discordId", "userId") SELECT "id", "enableNotifications", "discordId", "userId" FROM "user_settings"`
);
await queryRunner.query(`DROP TABLE "user_settings"`);
await queryRunner.query(
`ALTER TABLE "temporary_user_settings" RENAME TO "user_settings"`
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "user_settings" RENAME TO "temporary_user_settings"`
);
await queryRunner.query(
`CREATE TABLE "user_settings" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "enableNotifications" boolean NOT NULL DEFAULT (1), "discordId" varchar, "userId" integer, CONSTRAINT "REL_986a2b6d3c05eb4091bb8066f7" UNIQUE ("userId"))`
);
await queryRunner.query(
`INSERT INTO "user_settings"("id", "enableNotifications", "discordId", "userId") SELECT "id", "enableNotifications", "discordId", "userId" FROM "temporary_user_settings"`
);
await queryRunner.query(`DROP TABLE "temporary_user_settings"`);
await queryRunner.query(`DROP TABLE "user_settings"`);
}
}

@ -23,7 +23,7 @@ authRoutes.get('/me', isAuthenticated(), async (req, res) => {
where: { id: req.user.id },
});
return res.status(200).json(user.filter());
return res.status(200).json(user);
});
authRoutes.post('/login', async (req, res, next) => {

@ -35,7 +35,7 @@ router.get('/status/appdata', (_req, res) => {
});
});
router.use('/user', isAuthenticated(Permission.MANAGE_USERS), user);
router.use('/user', user);
router.get('/settings/public', (_req, res) => {
const settings = getSettings();

@ -1,289 +0,0 @@
import { Router } from 'express';
import { getRepository, Not } from 'typeorm';
import PlexTvAPI from '../api/plextv';
import { MediaRequest } from '../entity/MediaRequest';
import { User } from '../entity/User';
import { hasPermission, Permission } from '../lib/permissions';
import { getSettings } from '../lib/settings';
import logger from '../logger';
import gravatarUrl from 'gravatar-url';
import { UserType } from '../constants/user';
const router = Router();
router.get('/', async (req, res) => {
let query = getRepository(User).createQueryBuilder('user');
switch (req.query.sort) {
case 'updated':
query = query.orderBy('user.updatedAt', 'DESC');
break;
case 'displayname':
query = query.orderBy(
'(CASE WHEN user.username IS NULL THEN user.plexUsername ELSE user.username END)',
'ASC'
);
break;
case 'requests':
query = query
.addSelect((subQuery) => {
return subQuery
.select('COUNT(request.id)', 'requestCount')
.from(MediaRequest, 'request')
.where('request.requestedBy.id = user.id');
}, 'requestCount')
.orderBy('requestCount', 'DESC');
break;
default:
query = query.orderBy('user.id', 'ASC');
break;
}
const users = await query.getMany();
return res.status(200).json(User.filterMany(users));
});
router.post('/', async (req, res, next) => {
try {
const settings = getSettings();
const body = req.body;
const userRepository = getRepository(User);
const passedExplicitPassword = body.password && body.password.length > 0;
const avatar = gravatarUrl(body.email, { default: 'mm', size: 200 });
if (!passedExplicitPassword && !settings.notifications.agents.email) {
throw new Error('Email notifications must be enabled');
}
const user = new User({
avatar: body.avatar ?? avatar,
username: body.username ?? body.email,
email: body.email,
password: body.password,
permissions: settings.main.defaultPermissions,
plexToken: '',
userType: UserType.LOCAL,
});
if (passedExplicitPassword) {
await user?.setPassword(body.password);
} else {
await user?.generatePassword();
}
await userRepository.save(user);
return res.status(201).json(user.filter());
} catch (e) {
next({ status: 500, message: e.message });
}
});
router.get<{ id: string }>('/:id', async (req, res, next) => {
try {
const userRepository = getRepository(User);
const user = await userRepository.findOneOrFail({
where: { id: Number(req.params.id) },
});
return res.status(200).json(user.filter());
} catch (e) {
next({ status: 404, message: 'User not found' });
}
});
const canMakePermissionsChange = (permissions: number, user?: User) =>
// Only let the owner grant admin privileges
!(hasPermission(Permission.ADMIN, permissions) && user?.id !== 1) ||
// Only let users with the manage settings permission, grant the same permission
!(
hasPermission(Permission.MANAGE_SETTINGS, permissions) &&
!hasPermission(Permission.MANAGE_SETTINGS, user?.permissions ?? 0)
);
router.put<
Record<string, never>,
Partial<User>[],
{ ids: string[]; permissions: number }
>('/', async (req, res, next) => {
try {
const isOwner = req.user?.id === 1;
if (!canMakePermissionsChange(req.body.permissions, req.user)) {
return next({
status: 403,
message: 'You do not have permission to grant this level of access',
});
}
const userRepository = getRepository(User);
const users = await userRepository.findByIds(req.body.ids, {
...(!isOwner ? { id: Not(1) } : {}),
});
const updatedUsers = await Promise.all(
users.map(async (user) => {
return userRepository.save(<User>{
...user,
...{ permissions: req.body.permissions },
});
})
);
return res.status(200).json(updatedUsers);
} catch (e) {
next({ status: 500, message: e.message });
}
});
router.put<{ id: string }>('/:id', async (req, res, next) => {
try {
const userRepository = getRepository(User);
const user = await userRepository.findOneOrFail({
where: { id: Number(req.params.id) },
});
// Only let the owner user modify themselves
if (user.id === 1 && req.user?.id !== 1) {
return next({
status: 403,
message: 'You do not have permission to modify this user',
});
}
if (!canMakePermissionsChange(req.body.permissions, req.user)) {
return next({
status: 403,
message: 'You do not have permission to grant this level of access',
});
}
Object.assign(user, {
username: req.body.username,
permissions: req.body.permissions,
});
await userRepository.save(user);
return res.status(200).json(user.filter());
} catch (e) {
next({ status: 404, message: 'User not found' });
}
});
router.delete<{ id: string }>('/:id', async (req, res, next) => {
try {
const userRepository = getRepository(User);
const user = await userRepository.findOne({
where: { id: Number(req.params.id) },
relations: ['requests'],
});
if (!user) {
return next({ status: 404, message: 'User not found' });
}
if (user.id === 1) {
return next({ status: 405, message: 'This account cannot be deleted.' });
}
if (user.hasPermission(Permission.ADMIN)) {
return next({
status: 405,
message: 'You cannot delete users with administrative privileges.',
});
}
const requestRepository = getRepository(MediaRequest);
/**
* Requests are usually deleted through a cascade constraint. Those however, do
* not trigger the removal event so listeners to not run and the parent Media
* will not be updated back to unknown for titles that were still pending. So
* we manually remove all requests from the user here so the parent media's
* properly reflect the change.
*/
await requestRepository.remove(user.requests);
await userRepository.delete(user.id);
return res.status(200).json(user.filter());
} catch (e) {
logger.error('Something went wrong deleting a user', {
label: 'API',
userId: req.params.id,
errorMessage: e.message,
});
return next({
status: 500,
message: 'Something went wrong deleting the user',
});
}
});
router.post('/import-from-plex', async (req, res, next) => {
try {
const settings = getSettings();
const userRepository = getRepository(User);
// taken from auth.ts
const mainUser = await userRepository.findOneOrFail({
select: ['id', 'plexToken'],
order: { id: 'ASC' },
});
const mainPlexTv = new PlexTvAPI(mainUser.plexToken ?? '');
const plexUsersResponse = await mainPlexTv.getUsers();
const createdUsers: User[] = [];
for (const rawUser of plexUsersResponse.MediaContainer.User) {
const account = rawUser.$;
const user = await userRepository.findOne({
where: [{ plexId: account.id }, { email: account.email }],
});
if (user) {
// Update the users avatar with their plex thumbnail (incase it changed)
user.avatar = account.thumb;
user.email = account.email;
user.plexUsername = account.username;
// in-case the user was previously a local account
if (user.userType === UserType.LOCAL) {
user.userType = UserType.PLEX;
user.plexId = parseInt(account.id);
if (user.username === account.username) {
user.username = '';
}
}
await userRepository.save(user);
} else {
// Check to make sure it's a real account
if (account.email && account.username) {
const newUser = new User({
plexUsername: account.username,
email: account.email,
permissions: settings.main.defaultPermissions,
plexId: parseInt(account.id),
plexToken: '',
avatar: account.thumb,
userType: UserType.PLEX,
});
await userRepository.save(newUser);
createdUsers.push(newUser);
}
}
}
return res.status(201).json(User.filterMany(createdUsers));
} catch (e) {
next({ status: 500, message: e.message });
}
});
export default router;

@ -0,0 +1,358 @@
import { Router } from 'express';
import { getRepository, Not } from 'typeorm';
import PlexTvAPI from '../../api/plextv';
import { MediaRequest } from '../../entity/MediaRequest';
import { User } from '../../entity/User';
import { hasPermission, Permission } from '../../lib/permissions';
import { getSettings } from '../../lib/settings';
import logger from '../../logger';
import gravatarUrl from 'gravatar-url';
import { UserType } from '../../constants/user';
import { isAuthenticated } from '../../middleware/auth';
import { UserRequestsResponse } from '../../interfaces/api/userInterfaces';
import userSettingsRoutes from './usersettings';
const router = Router();
router.get('/', async (req, res) => {
let query = getRepository(User).createQueryBuilder('user');
switch (req.query.sort) {
case 'updated':
query = query.orderBy('user.updatedAt', 'DESC');
break;
case 'displayname':
query = query.orderBy(
'(CASE WHEN user.username IS NULL THEN user.plexUsername ELSE user.username END)',
'ASC'
);
break;
case 'requests':
query = query
.addSelect((subQuery) => {
return subQuery
.select('COUNT(request.id)', 'requestCount')
.from(MediaRequest, 'request')
.where('request.requestedBy.id = user.id');
}, 'requestCount')
.orderBy('requestCount', 'DESC');
break;
default:
query = query.orderBy('user.id', 'ASC');
break;
}
const users = await query.getMany();
return res
.status(200)
.json(
User.filterMany(users, req.user?.hasPermission(Permission.MANAGE_USERS))
);
});
router.post(
'/',
isAuthenticated(Permission.MANAGE_USERS),
async (req, res, next) => {
try {
const settings = getSettings();
const body = req.body;
const userRepository = getRepository(User);
const passedExplicitPassword = body.password && body.password.length > 0;
const avatar = gravatarUrl(body.email, { default: 'mm', size: 200 });
if (!passedExplicitPassword && !settings.notifications.agents.email) {
throw new Error('Email notifications must be enabled');
}
const user = new User({
avatar: body.avatar ?? avatar,
username: body.username ?? body.email,
email: body.email,
password: body.password,
permissions: settings.main.defaultPermissions,
plexToken: '',
userType: UserType.LOCAL,
});
if (passedExplicitPassword) {
await user?.setPassword(body.password);
} else {
await user?.generatePassword();
}
await userRepository.save(user);
return res.status(201).json(user.filter());
} catch (e) {
next({ status: 500, message: e.message });
}
}
);
router.get<{ id: string }>('/:id', async (req, res, next) => {
try {
const userRepository = getRepository(User);
const user = await userRepository.findOneOrFail({
where: { id: Number(req.params.id) },
});
return res
.status(200)
.json(user.filter(req.user?.hasPermission(Permission.MANAGE_USERS)));
} catch (e) {
next({ status: 404, message: 'User not found.' });
}
});
router.use('/:id/settings', userSettingsRoutes);
router.get<{ id: string }, UserRequestsResponse>(
'/:id/requests',
async (req, res, next) => {
const userRepository = getRepository(User);
const requestRepository = getRepository(MediaRequest);
const pageSize = req.query.take ? Number(req.query.take) : 20;
const skip = req.query.skip ? Number(req.query.skip) : 0;
try {
const user = await userRepository.findOne({
where: { id: Number(req.params.id) },
});
if (!user) {
return next({ status: 404, message: 'User not found.' });
}
const [requests, requestCount] = await requestRepository.findAndCount({
where: { requestedBy: user },
take: pageSize,
skip,
});
return res.status(200).json({
pageInfo: {
pages: Math.ceil(requestCount / pageSize),
pageSize,
results: requestCount,
page: Math.ceil(skip / pageSize) + 1,
},
results: requests,
});
} catch (e) {
next({ status: 500, message: e.message });
}
}
);
const canMakePermissionsChange = (permissions: number, user?: User) =>
// Only let the owner grant admin privileges
!(hasPermission(Permission.ADMIN, permissions) && user?.id !== 1) ||
// Only let users with the manage settings permission, grant the same permission
!(
hasPermission(Permission.MANAGE_SETTINGS, permissions) &&
!hasPermission(Permission.MANAGE_SETTINGS, user?.permissions ?? 0)
);
router.put<
Record<string, never>,
Partial<User>[],
{ ids: string[]; permissions: number }
>('/', isAuthenticated(Permission.MANAGE_USERS), async (req, res, next) => {
try {
const isOwner = req.user?.id === 1;
if (!canMakePermissionsChange(req.body.permissions, req.user)) {
return next({
status: 403,
message: 'You do not have permission to grant this level of access',
});
}
const userRepository = getRepository(User);
const users = await userRepository.findByIds(req.body.ids, {
...(!isOwner ? { id: Not(1) } : {}),
});
const updatedUsers = await Promise.all(
users.map(async (user) => {
return userRepository.save(<User>{
...user,
...{ permissions: req.body.permissions },
});
})
);
return res.status(200).json(updatedUsers);
} catch (e) {
next({ status: 500, message: e.message });
}
});
router.put<{ id: string }>(
'/:id',
isAuthenticated(Permission.MANAGE_USERS),
async (req, res, next) => {
try {
const userRepository = getRepository(User);
const user = await userRepository.findOneOrFail({
where: { id: Number(req.params.id) },
});
// Only let the owner user modify themselves
if (user.id === 1 && req.user?.id !== 1) {
return next({
status: 403,
message: 'You do not have permission to modify this user',
});
}
if (!canMakePermissionsChange(req.body.permissions, req.user)) {
return next({
status: 403,
message: 'You do not have permission to grant this level of access',
});
}
Object.assign(user, {
username: req.body.username,
permissions: req.body.permissions,
});
await userRepository.save(user);
return res.status(200).json(user.filter());
} catch (e) {
next({ status: 404, message: 'User not found.' });
}
}
);
router.delete<{ id: string }>(
'/:id',
isAuthenticated(Permission.MANAGE_USERS),
async (req, res, next) => {
try {
const userRepository = getRepository(User);
const user = await userRepository.findOne({
where: { id: Number(req.params.id) },
relations: ['requests'],
});
if (!user) {
return next({ status: 404, message: 'User not found.' });
}
if (user.id === 1) {
return next({
status: 405,
message: 'This account cannot be deleted.',
});
}
if (user.hasPermission(Permission.ADMIN)) {
return next({
status: 405,
message: 'You cannot delete users with administrative privileges.',
});
}
const requestRepository = getRepository(MediaRequest);
/**
* Requests are usually deleted through a cascade constraint. Those however, do
* not trigger the removal event so listeners to not run and the parent Media
* will not be updated back to unknown for titles that were still pending. So
* we manually remove all requests from the user here so the parent media's
* properly reflect the change.
*/
await requestRepository.remove(user.requests);
await userRepository.delete(user.id);
return res.status(200).json(user.filter());
} catch (e) {
logger.error('Something went wrong deleting a user', {
label: 'API',
userId: req.params.id,
errorMessage: e.message,
});
return next({
status: 500,
message: 'Something went wrong deleting the user',
});
}
}
);
router.post(
'/import-from-plex',
isAuthenticated(Permission.MANAGE_USERS),
async (req, res, next) => {
try {
const settings = getSettings();
const userRepository = getRepository(User);
// taken from auth.ts
const mainUser = await userRepository.findOneOrFail({
select: ['id', 'plexToken'],
order: { id: 'ASC' },
});
const mainPlexTv = new PlexTvAPI(mainUser.plexToken ?? '');
const plexUsersResponse = await mainPlexTv.getUsers();
const createdUsers: User[] = [];
for (const rawUser of plexUsersResponse.MediaContainer.User) {
const account = rawUser.$;
const user = await userRepository.findOne({
where: [{ plexId: account.id }, { email: account.email }],
});
if (user) {
// Update the users avatar with their plex thumbnail (incase it changed)
user.avatar = account.thumb;
user.email = account.email;
user.plexUsername = account.username;
// in-case the user was previously a local account
if (user.userType === UserType.LOCAL) {
user.userType = UserType.PLEX;
user.plexId = parseInt(account.id);
if (user.username === account.username) {
user.username = '';
}
}
await userRepository.save(user);
} else {
// Check to make sure it's a real account
if (account.email && account.username) {
const newUser = new User({
plexUsername: account.username,
email: account.email,
permissions: settings.main.defaultPermissions,
plexId: parseInt(account.id),
plexToken: '',
avatar: account.thumb,
userType: UserType.PLEX,
});
await userRepository.save(newUser);
createdUsers.push(newUser);
}
}
}
return res.status(201).json(User.filterMany(createdUsers));
} catch (e) {
next({ status: 500, message: e.message });
}
}
);
export default router;

@ -0,0 +1,280 @@
import { Router } from 'express';
import { getRepository } from 'typeorm';
import { User } from '../../entity/User';
import { UserSettings } from '../../entity/UserSettings';
import { UserSettingsNotificationsResponse } from '../../interfaces/api/userSettingsInterfaces';
import { Permission } from '../../lib/permissions';
import logger from '../../logger';
import { isAuthenticated } from '../../middleware/auth';
const isOwnProfileOrAdmin = (): Middleware => {
const authMiddleware: Middleware = (req, res, next) => {
if (
!req.user?.hasPermission(Permission.MANAGE_USERS) &&
req.user?.id !== Number(req.params.id)
) {
return next({
status: 403,
message: "You do not have permission to view this user's settings.",
});
}
next();
};
return authMiddleware;
};
const userSettingsRoutes = Router({ mergeParams: true });
userSettingsRoutes.get<{ id: string }, { username?: string }>(
'/main',
isOwnProfileOrAdmin(),
async (req, res, next) => {
const userRepository = getRepository(User);
try {
const user = await userRepository.findOne({
where: { id: Number(req.params.id) },
});
if (!user) {
return next({ status: 404, message: 'User not found.' });
}
return res.status(200).json({ username: user.username });
} catch (e) {
next({ status: 500, message: e.message });
}
}
);
userSettingsRoutes.post<
{ id: string },
{ username?: string },
{ username?: string }
>('/main', isOwnProfileOrAdmin(), async (req, res, next) => {
const userRepository = getRepository(User);
try {
const user = await userRepository.findOne({
where: { id: Number(req.params.id) },
});
if (!user) {
return next({ status: 404, message: 'User not found.' });
}
user.username = req.body.username;
await userRepository.save(user);
return res.status(200).json({ username: user.username });
} catch (e) {
next({ status: 500, message: e.message });
}
});
userSettingsRoutes.get<{ id: string }, { hasPassword: boolean }>(
'/password',
isOwnProfileOrAdmin(),
async (req, res, next) => {
const userRepository = getRepository(User);
try {
const user = await userRepository.findOne({
where: { id: Number(req.params.id) },
select: ['id', 'password'],
});
if (!user) {
return next({ status: 404, message: 'User not found.' });
}
return res.status(200).json({ hasPassword: !!user.password });
} catch (e) {
next({ status: 500, message: e.message });
}
}
);
userSettingsRoutes.post<
{ id: string },
null,
{ currentPassword?: string; newPassword: string }
>('/password', isOwnProfileOrAdmin(), async (req, res, next) => {
const userRepository = getRepository(User);
try {
const user = await userRepository.findOne({
where: { id: Number(req.params.id) },
});
const userWithPassword = await userRepository.findOne({
select: ['id', 'password'],
where: { id: Number(req.params.id) },
});
if (!user || !userWithPassword) {
return next({ status: 404, message: 'User not found.' });
}
if (req.body.newPassword.length < 8) {
return next({
status: 400,
message: 'Password must be at least 8 characters',
});
}
// If the user has the permission to manage users and they are not
// editing themselves, we will just set the new password
if (
req.user?.hasPermission(Permission.MANAGE_USERS) &&
req.user?.id !== user.id
) {
await user.setPassword(req.body.newPassword);
await userRepository.save(user);
logger.debug('Password overriden by user.', {
label: 'User Settings',
userEmail: user.email,
changingUser: req.user.email,
});
return res.status(204).send();
}
// If the user has a password, we need to check the currentPassword is correct
if (
user.password &&
(!req.body.currentPassword ||
!(await userWithPassword.passwordMatch(req.body.currentPassword)))
) {
logger.debug(
'Attempt to change password for user failed. Invalid current password provided.',
{ label: 'User Settings', userEmail: user.email }
);
return next({ status: 403, message: 'Current password is invalid.' });
}
await user.setPassword(req.body.newPassword);
await userRepository.save(user);
return res.status(204).send();
} catch (e) {
next({ status: 500, message: e.message });
}
});
userSettingsRoutes.get<{ id: string }, UserSettingsNotificationsResponse>(
'/notifications',
isOwnProfileOrAdmin(),
async (req, res, next) => {
const userRepository = getRepository(User);
try {
const user = await userRepository.findOne({
where: { id: Number(req.params.id) },
});
if (!user) {
return next({ status: 404, message: 'User not found.' });
}
return res.status(200).json({
enableNotifications: user.settings?.enableNotifications ?? true,
discordId: user.settings?.discordId,
});
} catch (e) {
next({ status: 500, message: e.message });
}
}
);
userSettingsRoutes.post<
{ id: string },
UserSettingsNotificationsResponse,
UserSettingsNotificationsResponse
>('/notifications', isOwnProfileOrAdmin(), async (req, res, next) => {
const userRepository = getRepository(User);
try {
const user = await userRepository.findOne({
where: { id: Number(req.params.id) },
});
if (!user) {
return next({ status: 404, message: 'User not found.' });
}
if (!user.settings) {
user.settings = new UserSettings({
user: req.user,
enableNotifications: req.body.enableNotifications,
discordId: req.body.discordId,
});
} else {
user.settings.enableNotifications = req.body.enableNotifications;
user.settings.discordId = req.body.discordId;
}
userRepository.save(user);
return res.status(200).json({
enableNotifications: user.settings.enableNotifications,
discordId: user.settings.discordId,
});
} catch (e) {
next({ status: 500, message: e.message });
}
});
userSettingsRoutes.get<{ id: string }, { permissions?: number }>(
'/permissions',
isAuthenticated(Permission.MANAGE_USERS),
async (req, res, next) => {
const userRepository = getRepository(User);
try {
const user = await userRepository.findOne({
where: { id: Number(req.params.id) },
});
if (!user) {
return next({ status: 404, message: 'User not found.' });
}
return res.status(200).json({ permissions: user.permissions });
} catch (e) {
next({ status: 500, message: e.message });
}
}
);
userSettingsRoutes.post<
{ id: string },
{ permissions?: number },
{ permissions: number }
>(
'/permissions',
isAuthenticated(Permission.MANAGE_USERS),
async (req, res, next) => {
const userRepository = getRepository(User);
try {
const user = await userRepository.findOne({
where: { id: Number(req.params.id) },
});
if (!user) {
return next({ status: 404, message: 'User not found.' });
}
user.permissions = req.body.permissions;
await userRepository.save(user);
return res.status(200).json({ permissions: user.permissions });
} catch (e) {
next({ status: 500, message: e.message });
}
}
);
export default userSettingsRoutes;

@ -1,4 +1,4 @@
import React from 'react';
import React, { ForwardedRef } from 'react';
export type ButtonType =
| 'default'
@ -16,6 +16,10 @@ type MergeElementProps<
type ElementTypes = 'button' | 'a';
type Element<P extends ElementTypes = 'button'> = P extends 'a'
? HTMLAnchorElement
: HTMLButtonElement;
type BaseProps<P> = {
buttonType?: ButtonType;
buttonSize?: 'default' | 'lg' | 'md' | 'sm';
@ -29,16 +33,19 @@ type ButtonProps<P extends React.ElementType> = {
as?: P;
} & MergeElementProps<P, BaseProps<P>>;
function Button<P extends ElementTypes = 'button'>({
buttonType = 'default',
buttonSize = 'default',
as,
children,
className,
...props
}: ButtonProps<P>): JSX.Element {
function Button<P extends ElementTypes = 'button'>(
{
buttonType = 'default',
buttonSize = 'default',
as,
children,
className,
...props
}: ButtonProps<P>,
ref?: React.Ref<Element<P>>
): JSX.Element {
const buttonStyle = [
'inline-flex items-center justify-center border border-transparent leading-5 font-medium rounded-md focus:outline-none transition ease-in-out duration-150',
'inline-flex items-center justify-center border border-transparent leading-5 font-medium rounded-md focus:outline-none transition ease-in-out duration-150 cursor-pointer',
];
switch (buttonType) {
case 'primary':
@ -93,6 +100,7 @@ function Button<P extends ElementTypes = 'button'>({
<a
className={buttonStyle.join(' ')}
{...(props as React.ComponentProps<'a'>)}
ref={ref as ForwardedRef<HTMLAnchorElement>}
>
<span className="flex items-center">{children}</span>
</a>
@ -102,6 +110,7 @@ function Button<P extends ElementTypes = 'button'>({
<button
className={buttonStyle.join(' ')}
{...(props as React.ComponentProps<'button'>)}
ref={ref as ForwardedRef<HTMLButtonElement>}
>
<span className="flex items-center">{children}</span>
</button>
@ -109,4 +118,4 @@ function Button<P extends ElementTypes = 'button'>({
}
}
export default Button;
export default React.forwardRef(Button) as typeof Button;

@ -3,13 +3,17 @@ import Transition from '../../Transition';
import { useUser } from '../../../hooks/useUser';
import axios from 'axios';
import useClickOutside from '../../../hooks/useClickOutside';
import { defineMessages, FormattedMessage } from 'react-intl';
import { defineMessages, useIntl } from 'react-intl';
import Link from 'next/link';
const messages = defineMessages({
myprofile: 'Profile',
settings: 'Settings',
signout: 'Sign Out',
});
const UserDropdown: React.FC = () => {
const intl = useIntl();
const dropdownRef = useRef<HTMLDivElement>(null);
const { user, revalidate } = useUser();
const [isDropdownOpen, setDropdownOpen] = useState(false);
@ -55,13 +59,43 @@ const UserDropdown: React.FC = () => {
aria-orientation="vertical"
aria-labelledby="user-menu"
>
<Link href={`/profile`}>
<a
className="block px-4 py-2 text-sm text-gray-200 transition duration-150 ease-in-out hover:bg-gray-600"
role="menuitem"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'Enter') {
setDropdownOpen(false);
}
}}
onClick={() => setDropdownOpen(false)}
>
{intl.formatMessage(messages.myprofile)}
</a>
</Link>
<Link href={`/profile/settings`}>
<a
className="block px-4 py-2 text-sm text-gray-200 transition duration-150 ease-in-out hover:bg-gray-600"
role="menuitem"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'Enter') {
setDropdownOpen(false);
}
}}
onClick={() => setDropdownOpen(false)}
>
{intl.formatMessage(messages.settings)}
</a>
</Link>
<a
href="#"
className="block px-4 py-2 text-sm text-gray-200 transition duration-150 ease-in-out hover:bg-gray-600"
role="menuitem"
onClick={() => logout()}
>
<FormattedMessage {...messages.signout} />
{intl.formatMessage(messages.signout)}
</a>
</div>
</div>

@ -36,6 +36,9 @@ const Layout: React.FC = ({ children }) => {
return (
<div className="flex h-full min-w-0 min-h-full bg-gray-900">
<div className="absolute w-full h-64 from-gray-800 to-gray-900 bg-gradient-to-bl">
<div className="relative inset-0 w-full h-full from-gray-900 to-transparent bg-gradient-to-t" />
</div>
<Sidebar open={isSidebarOpen} setClosed={() => setSidebarOpen(false)} />
<div className="relative flex flex-col flex-1 w-0 min-w-0 mb-16 md:ml-64">

@ -4,6 +4,7 @@ import Button from '../Common/Button';
import { Field, Form, Formik } from 'formik';
import * as Yup from 'yup';
import axios from 'axios';
import Link from 'next/link';
const messages = defineMessages({
email: 'Email Address',
@ -99,9 +100,11 @@ const LocalLogin: React.FC<LocalLoginProps> = ({ revalidate }) => {
<div className="pt-5 mt-8 border-t border-gray-700">
<div className="flex justify-between">
<span className="inline-flex rounded-md shadow-sm">
<Button as="a" buttonType="ghost" href="/resetpassword">
{intl.formatMessage(messages.forgotpassword)}
</Button>
<Link href="/resetpassword" passHref>
<Button as="a" buttonType="ghost">
{intl.formatMessage(messages.forgotpassword)}
</Button>
</Link>
</span>
<span className="inline-flex rounded-md shadow-sm">
<Button

@ -1,4 +1,4 @@
import React, { useContext } from 'react';
import React, { useContext, useEffect } from 'react';
import { useInView } from 'react-intersection-observer';
import type { MediaRequest } from '../../../server/entity/MediaRequest';
import type { TvDetails } from '../../../server/models/Tv';
@ -37,9 +37,10 @@ const RequestCardPlaceholder: React.FC = () => {
interface RequestCardProps {
request: MediaRequest;
onTitleData?: (requestId: number, title: MovieDetails | TvDetails) => void;
}
const RequestCard: React.FC<RequestCardProps> = ({ request }) => {
const RequestCard: React.FC<RequestCardProps> = ({ request, onTitleData }) => {
const { ref, inView } = useInView({
triggerOnce: true,
});
@ -69,6 +70,12 @@ const RequestCard: React.FC<RequestCardProps> = ({ request }) => {
}
};
useEffect(() => {
if (title && onTitleData) {
onTitleData(request.id, title);
}
}, [title, onTitleData, request]);
if (!title && !error) {
return (
<div ref={ref}>
@ -105,16 +112,18 @@ const RequestCard: React.FC<RequestCardProps> = ({ request }) => {
{isMovie(title) ? title.title : title.name}
</Link>
</h2>
<div className="flex items-center">
<img
src={requestData.requestedBy.avatar}
alt=""
className="w-4 mr-1 rounded-full sm:mr-2 sm:w-5"
/>
<span className="text-xs truncate sm:text-sm">
{requestData.requestedBy.displayName}
</span>
</div>
<Link href={`/users/${requestData.requestedBy.id}`}>
<a className="flex items-center group">
<img
src={requestData.requestedBy.avatar}
alt=""
className="w-4 mr-1 rounded-full sm:mr-2 sm:w-5"
/>
<span className="text-xs truncate sm:text-sm group-hover:underline">
{requestData.requestedBy.displayName}
</span>
</a>
</Link>
{requestData.media.status && (
<div className="mt-1 sm:mt-2">
<StatusBadge

@ -162,16 +162,18 @@ const RequestItem: React.FC<RequestItemProps> = ({
{isMovie(title) ? title.title : title.name}
</a>
</Link>
<div className="flex items-center">
<img
src={requestData.requestedBy.avatar}
alt=""
className="w-5 mr-2 rounded-full"
/>
<span className="text-sm">
{requestData.requestedBy.displayName}
</span>
</div>
<Link href={`/users/${requestData.requestedBy.id}`}>
<a className="flex items-center mt-1">
<img
src={requestData.requestedBy.avatar}
alt=""
className="w-5 mr-2 rounded-full"
/>
<span className="text-sm hover:underline">
{requestData.requestedBy.displayName}
</span>
</a>
</Link>
{requestData.seasons.length > 0 && (
<div className="items-center hidden mt-2 text-sm sm:flex">
<span className="mr-2">

@ -6,6 +6,7 @@ import Button from '../Common/Button';
import { Field, Form, Formik } from 'formik';
import * as Yup from 'yup';
import axios from 'axios';
import Link from 'next/link';
const messages = defineMessages({
forgotpassword: 'Forgot Your Password?',
@ -60,13 +61,15 @@ const ResetPassword: React.FC = () => {
<div className="px-10 py-8">
{hasSubmitted ? (
<>
<p className="text-md text-gray-300">
<p className="text-gray-300 text-md">
{intl.formatMessage(messages.requestresetlinksuccessmessage)}
</p>
<span className="flex rounded-md shadow-sm justify-center mt-4">
<Button as="a" href="/login" buttonType="ghost">
{intl.formatMessage(messages.gobacklogin)}
</Button>
<span className="flex justify-center mt-4 rounded-md shadow-sm">
<Link href="/login" passHref>
<Button as="a" buttonType="ghost">
{intl.formatMessage(messages.gobacklogin)}
</Button>
</Link>
</span>
</>
) : (
@ -105,7 +108,7 @@ const ResetPassword: React.FC = () => {
name="email"
type="text"
placeholder="name@example.com"
className="text-white flex-1 block w-full min-w-0 transition duration-150 ease-in-out bg-gray-700 border border-gray-500 rounded-md form-input sm:text-sm sm:leading-5"
className="flex-1 block w-full min-w-0 text-white transition duration-150 ease-in-out bg-gray-700 border border-gray-500 rounded-md form-input sm:text-sm sm:leading-5"
/>
</div>
{errors.email && touched.email && (

@ -7,6 +7,7 @@ import { Field, Form, Formik } from 'formik';
import * as Yup from 'yup';
import axios from 'axios';
import { useRouter } from 'next/router';
import Link from 'next/link';
const messages = defineMessages({
resetpassword: 'Reset Password',
@ -76,13 +77,15 @@ const ResetPassword: React.FC = () => {
<div className="px-10 py-8">
{hasSubmitted ? (
<>
<p className="text-md text-gray-300">
<p className="text-gray-300 text-md">
{intl.formatMessage(messages.resetpasswordsuccessmessage)}
</p>
<span className="flex rounded-md shadow-sm justify-center mt-4">
<Button as="a" href="/login" buttonType="ghost">
{intl.formatMessage(messages.gobacklogin)}
</Button>
<span className="flex justify-center mt-4 rounded-md shadow-sm">
<Link href="/login" passHref>
<Button as="a" buttonType="ghost">
{intl.formatMessage(messages.gobacklogin)}
</Button>
</Link>
</span>
</>
) : (
@ -124,7 +127,7 @@ const ResetPassword: React.FC = () => {
placeholder={intl.formatMessage(
messages.password
)}
className="text-white flex-1 block w-full min-w-0 transition duration-150 ease-in-out bg-gray-700 border border-gray-500 rounded-md form-input sm:text-sm sm:leading-5"
className="flex-1 block w-full min-w-0 text-white transition duration-150 ease-in-out bg-gray-700 border border-gray-500 rounded-md form-input sm:text-sm sm:leading-5"
/>
</div>
{errors.password && touched.password && (
@ -144,7 +147,7 @@ const ResetPassword: React.FC = () => {
name="confirmPassword"
placeholder="Confirm Password"
type="password"
className="text-white flex-1 block w-full min-w-0 transition duration-150 ease-in-out bg-gray-700 border border-gray-500 rounded-md form-input sm:text-sm sm:leading-5"
className="flex-1 block w-full min-w-0 text-white transition duration-150 ease-in-out bg-gray-700 border border-gray-500 rounded-md form-input sm:text-sm sm:leading-5"
/>
</div>
{errors.confirmPassword &&

@ -1,198 +0,0 @@
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import LoadingSpinner from '../Common/LoadingSpinner';
import { useUser } from '../../hooks/useUser';
import Button from '../Common/Button';
import { useIntl, defineMessages, FormattedMessage } from 'react-intl';
import axios from 'axios';
import { useToasts } from 'react-toast-notifications';
import Header from '../Common/Header';
import PermissionEdit from '../PermissionEdit';
import { Field, Form, Formik } from 'formik';
import { UserType } from '../../../server/constants/user';
import PageTitle from '../Common/PageTitle';
import * as Yup from 'yup';
export const messages = defineMessages({
edituser: 'Edit User',
plexUsername: 'Plex Username',
username: 'Display Name',
avatar: 'Avatar',
email: 'Email',
permissions: 'Permissions',
save: 'Save Changes',
saving: 'Saving…',
usersaved: 'User saved!',
userfail: 'Something went wrong while saving the user.',
validationEmail: 'You must provide a valid email address',
});
const UserEdit: React.FC = () => {
const router = useRouter();
const intl = useIntl();
const { addToast } = useToasts();
const { user: currentUser } = useUser();
const { user, error, revalidate } = useUser({
id: Number(router.query.userId),
});
const [currentPermission, setCurrentPermission] = useState(0);
useEffect(() => {
if (currentPermission !== user?.permissions ?? 0) {
setCurrentPermission(user?.permissions ?? 0);
}
// We know what we are doing here.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [user]);
const UserEditSchema = Yup.object().shape({
email: Yup.string()
.required(intl.formatMessage(messages.validationEmail))
.email(intl.formatMessage(messages.validationEmail)),
});
if (!user && !error) {
return <LoadingSpinner />;
}
return (
<Formik
initialValues={{
plexUsername: user?.plexUsername,
username: user?.username,
email: user?.email,
}}
validationSchema={UserEditSchema}
onSubmit={async (values) => {
try {
await axios.put(`/api/v1/user/${user?.id}`, {
permissions: currentPermission,
email: user?.email,
username: values.username,
});
addToast(intl.formatMessage(messages.usersaved), {
appearance: 'success',
autoDismiss: true,
});
} catch (e) {
addToast(intl.formatMessage(messages.userfail), {
appearance: 'error',
autoDismiss: true,
});
throw new Error(
`Something went wrong while saving the user: ${e.message}`
);
} finally {
revalidate();
}
}}
>
{({ errors, touched, isSubmitting, handleSubmit }) => (
<Form>
<PageTitle title={intl.formatMessage(messages.edituser)} />
<div>
<div className="flex flex-col justify-between sm:flex-row">
<Header>
<FormattedMessage {...messages.edituser} />
</Header>
</div>
{user?.userType === UserType.PLEX && (
<div className="form-row">
<label htmlFor="plexUsername" className="text-label">
{intl.formatMessage(messages.plexUsername)}
</label>
<div className="form-input">
<div className="flex max-w-lg rounded-md shadow-sm">
<Field
id="plexUsername"
name="plexUsername"
type="text"
readOnly
/>
</div>
</div>
</div>
)}
<div className="form-row">
<label htmlFor="username" className="text-label">
{intl.formatMessage(messages.username)}
</label>
<div className="form-input">
<div className="flex max-w-lg rounded-md shadow-sm">
<Field id="username" name="username" type="text" />
</div>
</div>
</div>
<div className="form-row">
<label htmlFor="email" className="text-label">
<FormattedMessage {...messages.email} />
</label>
<div className="form-input">
<div className="flex max-w-lg rounded-md shadow-sm">
<Field id="email" name="email" type="text" readOnly />
</div>
{errors.email && touched.email && (
<div className="error">{errors.email}</div>
)}
</div>
</div>
<div className="form-row">
<span className="text-label">
<FormattedMessage {...messages.avatar} />
</span>
<div className="form-input">
<div className="flex max-w-lg rounded-md shadow-sm">
<img
className="w-40 h-40 rounded-full"
src={user?.avatar}
alt=""
/>
</div>
</div>
</div>
</div>
<div
role="group"
aria-labelledby="group-label"
className="form-group"
>
<div className="form-row">
<span id="group-label" className="group-label">
<FormattedMessage {...messages.permissions} />
</span>
<div className="form-input">
<div className="max-w-lg">
<PermissionEdit
user={currentUser}
currentPermission={currentPermission}
onUpdate={(newPermission) =>
setCurrentPermission(newPermission)
}
/>
</div>
</div>
</div>
</div>
<div className="actions">
<div className="flex justify-end">
<span className="inline-flex ml-3 rounded-md shadow-sm">
<Button
buttonType="primary"
type="submit"
disabled={isSubmitting}
onClick={() => handleSubmit}
>
{isSubmitting
? intl.formatMessage(messages.saving)
: intl.formatMessage(messages.save)}
</Button>
</span>
</div>
</div>
</Form>
)}
</Formik>
);
};
export default UserEdit;

@ -5,7 +5,6 @@ import { User, useUser } from '../../hooks/useUser';
import { defineMessages, FormattedMessage, useIntl } from 'react-intl';
import axios from 'axios';
import { useToasts } from 'react-toast-notifications';
import { messages as userEditMessages } from '../UserEdit';
interface BulkEditProps {
selectedUserIds: number[];
@ -17,6 +16,11 @@ interface BulkEditProps {
const messages = defineMessages({
userssaved: 'Users saved',
save: 'Save Changes',
saving: 'Saving…',
userfail: 'Something went wrong while saving the user.',
permissions: 'Permissions',
edituser: 'Edit User',
});
const BulkEditModal: React.FC<BulkEditProps> = ({
@ -53,7 +57,7 @@ const BulkEditModal: React.FC<BulkEditProps> = ({
autoDismiss: true,
});
} catch (e) {
addToast(intl.formatMessage(userEditMessages.userfail), {
addToast(intl.formatMessage(messages.userfail), {
appearance: 'error',
autoDismiss: true,
});
@ -81,12 +85,12 @@ const BulkEditModal: React.FC<BulkEditProps> = ({
return (
<Modal
title={intl.formatMessage(userEditMessages.edituser)}
title={intl.formatMessage(messages.edituser)}
onOk={() => {
updateUsers();
}}
okDisabled={isSaving}
okText={intl.formatMessage(userEditMessages.save)}
okText={intl.formatMessage(messages.save)}
onCancel={onCancel}
>
<div className="mt-6 mb-6">
@ -94,7 +98,7 @@ const BulkEditModal: React.FC<BulkEditProps> = ({
<div className="form-row">
<div>
<div id="group-label" className="group-label">
<FormattedMessage {...userEditMessages.permissions} />
<FormattedMessage {...messages.permissions} />
</div>
</div>
<div className="form-input">

@ -1,12 +1,11 @@
import React, { useState } from 'react';
import useSWR from 'swr';
import LoadingSpinner from '../Common/LoadingSpinner';
import type { User } from '../../../server/entity/User';
import Badge from '../Common/Badge';
import { FormattedDate, defineMessages, useIntl } from 'react-intl';
import Button from '../Common/Button';
import { hasPermission } from '../../../server/lib/permissions';
import { Permission, UserType, useUser } from '../../hooks/useUser';
import { Permission, User, UserType, useUser } from '../../hooks/useUser';
import { useRouter } from 'next/router';
import Header from '../Common/Header';
import Table from '../Common/Table';
@ -21,6 +20,7 @@ import AddUserIcon from '../../assets/useradd.svg';
import Alert from '../Common/Alert';
import BulkEditModal from './BulkEditModal';
import PageTitle from '../Common/PageTitle';
import Link from 'next/link';
const messages = defineMessages({
users: 'Users',
@ -485,17 +485,21 @@ const UserList: React.FC = () => {
</Table.TD>
<Table.TD>
<div className="flex items-center">
<div className="flex-shrink-0 w-10 h-10">
<img
className="w-10 h-10 rounded-full"
src={user.avatar}
alt=""
/>
</div>
<Link href={`/users/${user.id}`}>
<a className="flex-shrink-0 w-10 h-10">
<img
className="w-10 h-10 rounded-full"
src={user.avatar}
alt=""
/>
</a>
</Link>
<div className="ml-4">
<div className="text-sm font-medium leading-5">
{user.displayName}
</div>
<Link href={`/users/${user.id}`}>
<a className="text-sm font-medium leading-5">
{user.displayName}
</a>
</Link>
<div className="text-sm leading-5 text-gray-300">
{user.email}
</div>
@ -533,8 +537,8 @@ const UserList: React.FC = () => {
className="mr-2"
onClick={() =>
router.push(
'/users/[userId]/edit',
`/users/${user.id}/edit`
'/users/[userId]/settings',
`/users/${user.id}/settings`
)
}
>

@ -0,0 +1,120 @@
import Link from 'next/link';
import React from 'react';
import { defineMessages, useIntl } from 'react-intl';
import { Permission, User, useUser } from '../../../hooks/useUser';
import Button from '../../Common/Button';
const messages = defineMessages({
settings: 'Edit Settings',
profile: 'View Profile',
});
interface ProfileHeaderProps {
user: User;
isSettingsPage?: boolean;
}
const ProfileHeader: React.FC<ProfileHeaderProps> = ({
user,
isSettingsPage,
}) => {
const intl = useIntl();
const { user: loggedInUser, hasPermission } = useUser();
return (
<div className="relative z-40 mt-6 mb-12 md:flex md:items-end md:justify-between md:space-x-5">
<div className="flex items-end space-x-5 justify-items-end">
<div className="flex-shrink-0">
<div className="relative">
<img
className="w-24 h-24 bg-gray-600 rounded-full"
src={user.avatar}
alt=""
/>
<span
className="absolute inset-0 rounded-full shadow-inner"
aria-hidden="true"
></span>
</div>
</div>
<div className="pt-1.5">
<h1 className="flex flex-col mb-1 sm:items-center sm:flex-row">
<Link
href={
user.id === loggedInUser?.id ? '/profile' : `/users/${user.id}`
}
>
<a className="text-lg font-bold text-transparent sm:text-2xl bg-clip-text bg-gradient-to-br from-indigo-400 to-purple-400 hover:to-purple-200">
{user.displayName}
</a>
</Link>
{user.email && (
<span className="text-sm text-gray-400 sm:text-lg sm:ml-2">
({user.email})
</span>
)}
</h1>
<p className="text-sm font-medium text-gray-400">
Joined {intl.formatDate(user.createdAt)} |{' '}
{intl.formatNumber(user.requestCount)} Requests
</p>
</div>
</div>
<div className="flex flex-col-reverse mt-6 space-y-4 space-y-reverse justify-stretch sm:flex-row-reverse sm:justify-end sm:space-x-reverse sm:space-y-0 sm:space-x-3 md:mt-0 md:flex-row md:space-x-3">
{(loggedInUser?.id === user.id ||
hasPermission(Permission.MANAGE_USERS)) &&
!isSettingsPage ? (
<Link
href={
loggedInUser?.id === user.id
? `/profile/settings`
: `/users/${user.id}/settings`
}
passHref
>
<Button as="a">
<svg
className="w-5 h-5 mr-1"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
d="M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z"
clipRule="evenodd"
/>
</svg>
{intl.formatMessage(messages.settings)}
</Button>
</Link>
) : (
<Link
href={
loggedInUser?.id === user.id ? `/profile` : `/users/${user.id}`
}
passHref
>
<Button as="a">
<svg
className="w-5 h-5 mr-1"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z"
clipRule="evenodd"
/>
</svg>
{intl.formatMessage(messages.profile)}
</Button>
</Link>
)}
</div>
</div>
);
};
export default ProfileHeader;

@ -0,0 +1,135 @@
import axios from 'axios';
import { Field, Form, Formik } from 'formik';
import { useRouter } from 'next/router';
import React from 'react';
import { defineMessages, useIntl } from 'react-intl';
import { useToasts } from 'react-toast-notifications';
import useSWR from 'swr';
import { UserType, useUser } from '../../../../hooks/useUser';
import Error from '../../../../pages/_error';
import Badge from '../../../Common/Badge';
import Button from '../../../Common/Button';
import LoadingSpinner from '../../../Common/LoadingSpinner';
const messages = defineMessages({
generalsettings: 'General Settings',
displayName: 'Display Name',
save: 'Save Changes',
saving: 'Saving…',
plexuser: 'Plex User',
localuser: 'Local User',
toastSettingsSuccess: 'Settings successfully saved!',
toastSettingsFailure: 'Something went wrong while saving settings.',
});
const UserGeneralSettings: React.FC = () => {
const intl = useIntl();
const { addToast } = useToasts();
const router = useRouter();
const { user, mutate } = useUser({ id: Number(router.query.userId) });
const { data, error, revalidate } = useSWR<{ username?: string }>(
user ? `/api/v1/user/${user?.id}/settings/main` : null
);
if (!data && !error) {
return <LoadingSpinner />;
}
if (!data) {
return <Error statusCode={500} />;
}
return (
<>
<div className="mb-6">
<h3 className="heading">
{intl.formatMessage(messages.generalsettings)}
</h3>
</div>
<Formik
initialValues={{
displayName: data?.username,
}}
enableReinitialize
onSubmit={async (values) => {
try {
await axios.post(`/api/v1/user/${user?.id}/settings/main`, {
username: values.displayName,
});
addToast(intl.formatMessage(messages.toastSettingsSuccess), {
autoDismiss: true,
appearance: 'success',
});
} catch (e) {
addToast(intl.formatMessage(messages.toastSettingsFailure), {
autoDismiss: true,
appearance: 'error',
});
} finally {
revalidate();
mutate();
}
}}
>
{({ errors, touched, isSubmitting }) => {
return (
<Form className="section">
<div className="form-row">
<div className="text-label">Account Type</div>
<div className="mb-1 text-sm font-medium leading-5 text-gray-400 sm:mt-2">
<div className="flex items-center max-w-lg">
{user?.userType === UserType.PLEX ? (
<Badge badgeType="warning">
{intl.formatMessage(messages.plexuser)}
</Badge>
) : (
<Badge badgeType="default">
{intl.formatMessage(messages.localuser)}
</Badge>
)}
</div>
</div>
</div>
<div className="form-row">
<label htmlFor="displayName" className="text-label">
{intl.formatMessage(messages.displayName)}
</label>
<div className="form-input">
<div className="flex max-w-lg rounded-md shadow-sm">
<Field
id="displayName"
name="displayName"
type="text"
placeholder={user?.displayName}
/>
</div>
{errors.displayName && touched.displayName && (
<div className="error">{errors.displayName}</div>
)}
</div>
</div>
<div className="actions">
<div className="flex justify-end">
<span className="inline-flex ml-3 rounded-md shadow-sm">
<Button
buttonType="primary"
type="submit"
disabled={isSubmitting}
>
{isSubmitting
? intl.formatMessage(messages.saving)
: intl.formatMessage(messages.save)}
</Button>
</span>
</div>
</div>
</Form>
);
}}
</Formik>
</>
);
};
export default UserGeneralSettings;

@ -0,0 +1,134 @@
import axios from 'axios';
import { Field, Form, Formik } from 'formik';
import { useRouter } from 'next/router';
import React from 'react';
import { defineMessages, useIntl } from 'react-intl';
import { useToasts } from 'react-toast-notifications';
import useSWR from 'swr';
import { useUser } from '../../../../hooks/useUser';
import Error from '../../../../pages/_error';
import Button from '../../../Common/Button';
import LoadingSpinner from '../../../Common/LoadingSpinner';
import { UserSettingsNotificationsResponse } from '../../../../../server/interfaces/api/userSettingsInterfaces';
const messages = defineMessages({
notificationsettings: 'Notification Settings',
enableNotifications: 'Enable Notifications',
discordId: 'Discord ID',
save: 'Save Changes',
saving: 'Saving…',
plexuser: 'Plex User',
localuser: 'Local User',
toastSettingsSuccess: 'Settings successfully saved!',
toastSettingsFailure: 'Something went wrong while saving settings.',
});
const UserNotificationSettings: React.FC = () => {
const intl = useIntl();
const { addToast } = useToasts();
const router = useRouter();
const { user, mutate } = useUser({ id: Number(router.query.userId) });
const { data, error, revalidate } = useSWR<UserSettingsNotificationsResponse>(
user ? `/api/v1/user/${user?.id}/settings/notifications` : null
);
if (!data && !error) {
return <LoadingSpinner />;
}
if (!data) {
return <Error statusCode={500} />;
}
return (
<>
<div className="mb-6">
<h3 className="heading">
{intl.formatMessage(messages.notificationsettings)}
</h3>
</div>
<Formik
initialValues={{
enableNotifications: data?.enableNotifications,
discordId: data?.discordId,
}}
enableReinitialize
onSubmit={async (values) => {
try {
await axios.post(
`/api/v1/user/${user?.id}/settings/notifications`,
{
enableNotifications: values.enableNotifications,
discordId: values.discordId,
}
);
addToast(intl.formatMessage(messages.toastSettingsSuccess), {
autoDismiss: true,
appearance: 'success',
});
} catch (e) {
addToast(intl.formatMessage(messages.toastSettingsFailure), {
autoDismiss: true,
appearance: 'error',
});
} finally {
revalidate();
mutate();
}
}}
>
{({ errors, touched, isSubmitting }) => {
return (
<Form className="section">
<div className="form-row">
<label htmlFor="enableNotifications" className="checkbox-label">
<span className="mr-2">
{intl.formatMessage(messages.enableNotifications)}
</span>
</label>
<div className="form-input">
<Field
type="checkbox"
id="enableNotifications"
name="enableNotifications"
/>
</div>
</div>
<div className="form-row">
<label htmlFor="discordId" className="text-label">
{intl.formatMessage(messages.discordId)}
</label>
<div className="form-input">
<div className="flex max-w-lg rounded-md shadow-sm">
<Field id="discordId" name="discordId" type="text" />
</div>
{errors.discordId && touched.discordId && (
<div className="error">{errors.discordId}</div>
)}
</div>
</div>
<div className="actions">
<div className="flex justify-end">
<span className="inline-flex ml-3 rounded-md shadow-sm">
<Button
buttonType="primary"
type="submit"
disabled={isSubmitting}
>
{isSubmitting
? intl.formatMessage(messages.saving)
: intl.formatMessage(messages.save)}
</Button>
</span>
</div>
</div>
</Form>
);
}}
</Formik>
</>
);
};
export default UserNotificationSettings;

@ -0,0 +1,192 @@
import axios from 'axios';
import { Field, Form, Formik } from 'formik';
import { useRouter } from 'next/router';
import React from 'react';
import { defineMessages, useIntl } from 'react-intl';
import { useToasts } from 'react-toast-notifications';
import useSWR from 'swr';
import { useUser } from '../../../../hooks/useUser';
import Error from '../../../../pages/_error';
import Alert from '../../../Common/Alert';
import Button from '../../../Common/Button';
import LoadingSpinner from '../../../Common/LoadingSpinner';
import * as Yup from 'yup';
const messages = defineMessages({
password: 'Password',
currentpassword: 'Current Password',
newpassword: 'New Password',
confirmpassword: 'Confirm Password',
save: 'Save Changes',
saving: 'Saving…',
toastSettingsSuccess: 'Password changed!',
toastSettingsFailure:
'Something went wrong while changing the password. Is your current password correct?',
validationCurrentPassword: 'You must provide your current password',
validationNewPassword: 'You must provide a new password',
validationNewPasswordLength:
'Password is too short; should be a minimum of 8 characters',
validationConfirmPassword: 'You must confirm your new password',
validationConfirmPasswordSame: 'Password must match',
nopasswordset: 'No Password Set',
nopasswordsetDescription:
'This user account currently does not have an Overseerr-specific password. Configure a password below to allow this account to sign-in as a "local user."',
});
const UserPasswordChange: React.FC = () => {
const intl = useIntl();
const { addToast } = useToasts();
const router = useRouter();
const { user: currentUser } = useUser();
const { user } = useUser({ id: Number(router.query.userId) });
const { data, error, revalidate } = useSWR<{ hasPassword: boolean }>(
user ? `/api/v1/user/${user?.id}/settings/password` : null
);
const PasswordChangeSchema = Yup.object().shape({
currentPassword: Yup.lazy(() =>
data?.hasPassword
? Yup.string().required(
intl.formatMessage(messages.validationCurrentPassword)
)
: Yup.mixed().optional()
),
newPassword: Yup.string()
.required(intl.formatMessage(messages.validationNewPassword))
.min(8, intl.formatMessage(messages.validationNewPasswordLength)),
confirmPassword: Yup.string()
.required(intl.formatMessage(messages.validationConfirmPassword))
.oneOf(
[Yup.ref('newPassword'), null],
intl.formatMessage(messages.validationConfirmPasswordSame)
),
});
if (!data && !error) {
return <LoadingSpinner />;
}
if (!data) {
return <Error statusCode={500} />;
}
return (
<>
<div className="mb-6">
<h3 className="heading">{intl.formatMessage(messages.password)}</h3>
</div>
<Formik
initialValues={{
currentPassword: '',
newPassword: '',
confirmPassword: '',
}}
validationSchema={PasswordChangeSchema}
enableReinitialize
onSubmit={async (values, { resetForm }) => {
try {
await axios.post(`/api/v1/user/${user?.id}/settings/password`, {
currentPassword: values.currentPassword,
newPassword: values.newPassword,
confirmPassword: values.confirmPassword,
});
addToast(intl.formatMessage(messages.toastSettingsSuccess), {
autoDismiss: true,
appearance: 'success',
});
} catch (e) {
addToast(intl.formatMessage(messages.toastSettingsFailure), {
autoDismiss: true,
appearance: 'error',
});
} finally {
revalidate();
resetForm();
}
}}
>
{({ errors, touched, isSubmitting }) => {
return (
<Form className="section">
{!data.hasPassword && (
<Alert
type="warning"
title={intl.formatMessage(messages.nopasswordset)}
>
{intl.formatMessage(messages.nopasswordsetDescription)}
</Alert>
)}
{data.hasPassword && user?.id === currentUser?.id && (
<div className="pb-6 form-row">
<label htmlFor="currentPassword" className="text-label">
{intl.formatMessage(messages.currentpassword)}
</label>
<div className="form-input">
<div className="flex max-w-lg rounded-md shadow-sm">
<Field
id="currentPassword"
name="currentPassword"
type="text"
/>
</div>
{errors.currentPassword && touched.currentPassword && (
<div className="error">{errors.currentPassword}</div>
)}
</div>
</div>
)}
<div className="form-row">
<label htmlFor="newPassword" className="text-label">
{intl.formatMessage(messages.newpassword)}
</label>
<div className="form-input">
<div className="flex max-w-lg rounded-md shadow-sm">
<Field id="newPassword" name="newPassword" type="text" />
</div>
{errors.newPassword && touched.newPassword && (
<div className="error">{errors.newPassword}</div>
)}
</div>
</div>
<div className="form-row">
<label htmlFor="confirmPassword" className="text-label">
{intl.formatMessage(messages.confirmpassword)}
</label>
<div className="form-input">
<div className="flex max-w-lg rounded-md shadow-sm">
<Field
id="confirmPassword"
name="confirmPassword"
type="text"
/>
</div>
{errors.confirmPassword && touched.confirmPassword && (
<div className="error">{errors.confirmPassword}</div>
)}
</div>
</div>
<div className="actions">
<div className="flex justify-end">
<span className="inline-flex ml-3 rounded-md shadow-sm">
<Button
buttonType="primary"
type="submit"
disabled={isSubmitting}
>
{isSubmitting
? intl.formatMessage(messages.saving)
: intl.formatMessage(messages.save)}
</Button>
</span>
</div>
</div>
</Form>
);
}}
</Formik>
</>
);
};
export default UserPasswordChange;

@ -0,0 +1,122 @@
import axios from 'axios';
import { Form, Formik } from 'formik';
import { useRouter } from 'next/router';
import React from 'react';
import { defineMessages, useIntl } from 'react-intl';
import { useToasts } from 'react-toast-notifications';
import useSWR from 'swr';
import { useUser } from '../../../../hooks/useUser';
import Error from '../../../../pages/_error';
import Button from '../../../Common/Button';
import LoadingSpinner from '../../../Common/LoadingSpinner';
import PermissionEdit from '../../../PermissionEdit';
const messages = defineMessages({
displayName: 'Display Name',
save: 'Save Changes',
saving: 'Saving…',
plexuser: 'Plex User',
localuser: 'Local User',
toastSettingsSuccess: 'Settings successfully saved!',
toastSettingsFailure: 'Something went wrong while saving settings.',
permissions: 'Permissions',
});
const UserPermissions: React.FC = () => {
const intl = useIntl();
const { addToast } = useToasts();
const router = useRouter();
const { user: currentUser } = useUser();
const { user, mutate } = useUser({ id: Number(router.query.userId) });
const { data, error, revalidate } = useSWR<{ permissions?: number }>(
user ? `/api/v1/user/${user?.id}/settings/permissions` : null
);
if (!data && !error) {
return <LoadingSpinner />;
}
if (!data) {
return <Error statusCode={500} />;
}
return (
<>
<div className="mb-6">
<h3 className="heading">{intl.formatMessage(messages.permissions)}</h3>
</div>
<Formik
initialValues={{
currentPermissions: data?.permissions,
}}
enableReinitialize
onSubmit={async (values) => {
try {
await axios.post(`/api/v1/user/${user?.id}/settings/permissions`, {
permissions: values.currentPermissions ?? 0,
});
addToast(intl.formatMessage(messages.toastSettingsSuccess), {
autoDismiss: true,
appearance: 'success',
});
} catch (e) {
addToast(intl.formatMessage(messages.toastSettingsFailure), {
autoDismiss: true,
appearance: 'error',
});
} finally {
revalidate();
mutate();
}
}}
>
{({ isSubmitting, setFieldValue, values }) => {
return (
<Form className="section">
<div
role="group"
aria-labelledby="group-label"
className="form-group"
>
<div className="form-row">
<span id="group-label" className="group-label">
{intl.formatMessage(messages.permissions)}
</span>
<div className="form-input">
<div className="max-w-lg">
<PermissionEdit
user={currentUser}
currentPermission={values.currentPermissions ?? 0}
onUpdate={(newPermission) =>
setFieldValue('currentPermissions', newPermission)
}
/>
</div>
</div>
</div>
</div>
<div className="actions">
<div className="flex justify-end">
<span className="inline-flex ml-3 rounded-md shadow-sm">
<Button
buttonType="primary"
type="submit"
disabled={isSubmitting}
>
{isSubmitting
? intl.formatMessage(messages.saving)
: intl.formatMessage(messages.save)}
</Button>
</span>
</div>
</div>
</Form>
);
}}
</Formik>
</>
);
};
export default UserPermissions;

@ -0,0 +1,172 @@
import Link from 'next/link';
import { useRouter } from 'next/router';
import React from 'react';
import { defineMessages, useIntl } from 'react-intl';
import { Permission, useUser } from '../../../hooks/useUser';
import Error from '../../../pages/_error';
import LoadingSpinner from '../../Common/LoadingSpinner';
import PageTitle from '../../Common/PageTitle';
import ProfileHeader from '../ProfileHeader';
const messages = defineMessages({
settings: 'User Settings',
menuGeneralSettings: 'General Settings',
menuChangePass: 'Password',
menuNotifications: 'Notifications',
menuPermissions: 'Permissions',
});
interface SettingsRoute {
text: string;
route: string;
regex: RegExp;
requiredPermission?: Permission | Permission[];
permissionType?: { type: 'and' | 'or' };
}
const UserSettings: React.FC = ({ children }) => {
const router = useRouter();
const { hasPermission } = useUser();
const { user, error } = useUser({ id: Number(router.query.userId) });
const intl = useIntl();
if (!user && !error) {
return <LoadingSpinner />;
}
if (!user) {
return <Error statusCode={500} />;
}
const settingsRoutes: SettingsRoute[] = [
{
text: intl.formatMessage(messages.menuGeneralSettings),
route: '/settings/main',
regex: /\/settings(\/main)?$/,
},
{
text: intl.formatMessage(messages.menuChangePass),
route: '/settings/password',
regex: /\/settings\/password/,
},
{
text: intl.formatMessage(messages.menuNotifications),
route: '/settings/notifications',
regex: /\/settings\/notifications/,
},
{
text: intl.formatMessage(messages.menuPermissions),
route: '/settings/permissions',
regex: /\/settings\/permissions/,
requiredPermission: Permission.MANAGE_USERS,
},
];
const activeLinkColor =
'border-indigo-600 text-indigo-500 focus:outline-none focus:text-indigo-500 focus:border-indigo-500';
const inactiveLinkColor =
'border-transparent text-gray-500 hover:text-gray-400 hover:border-gray-300 focus:outline-none focus:text-gray-4700 focus:border-gray-300';
const SettingsLink: React.FC<{
route: string;
regex: RegExp;
isMobile?: boolean;
}> = ({ children, route, regex, isMobile = false }) => {
const finalRoute = router.asPath.includes('/profile')
? `/profile${route}`
: `/users/${user.id}${route}`;
if (isMobile) {
return <option value={finalRoute}>{children}</option>;
}
return (
<Link href={finalRoute}>
<a
className={`whitespace-nowrap ml-8 first:ml-0 py-4 px-1 border-b-2 border-transparent font-medium text-sm leading-5 ${
router.pathname.match(regex) ? activeLinkColor : inactiveLinkColor
}`}
aria-current="page"
>
{children}
</a>
</Link>
);
};
const currentRoute = settingsRoutes.find(
(route) => !!router.pathname.match(route.regex)
)?.route;
const finalRoute = router.asPath.includes('/profile')
? `/profile${currentRoute}`
: `/users/${user.id}${currentRoute}`;
return (
<>
<PageTitle title={intl.formatMessage(messages.settings)} />
<ProfileHeader user={user} isSettingsPage />
<div className="mt-6">
<div className="sm:hidden">
<select
onChange={(e) => {
router.push(e.target.value);
}}
onBlur={(e) => {
router.push(e.target.value);
}}
defaultValue={finalRoute}
aria-label="Selected tab"
>
{settingsRoutes
.filter((route) =>
route.requiredPermission
? hasPermission(
route.requiredPermission,
route.permissionType
)
: true
)
.map((route, index) => (
<SettingsLink
route={route.route}
regex={route.regex}
isMobile
key={`mobile-settings-link-${index}`}
>
{route.text}
</SettingsLink>
))}
</select>
</div>
<div className="hidden sm:block">
<div className="border-b border-gray-600">
<nav className="flex -mb-px">
{settingsRoutes
.filter((route) =>
route.requiredPermission
? hasPermission(
route.requiredPermission,
route.permissionType
)
: true
)
.map((route, index) => (
<SettingsLink
route={route.route}
regex={route.regex}
key={`standard-settings-link-${index}`}
>
{route.text}
</SettingsLink>
))}
</nav>
</div>
</div>
</div>
<div className="mt-10 text-white">{children}</div>
</>
);
};
export default UserSettings;

@ -0,0 +1,105 @@
import { useRouter } from 'next/router';
import React, { useCallback, useEffect, useState } from 'react';
import useSWR from 'swr';
import { useUser } from '../../hooks/useUser';
import Error from '../../pages/_error';
import LoadingSpinner from '../Common/LoadingSpinner';
import { UserRequestsResponse } from '../../../server/interfaces/api/userInterfaces';
import Slider from '../Slider';
import RequestCard from '../RequestCard';
import { MovieDetails } from '../../../server/models/Movie';
import { TvDetails } from '../../../server/models/Tv';
import ImageFader from '../Common/ImageFader';
import PageTitle from '../Common/PageTitle';
import ProfileHeader from './ProfileHeader';
import { defineMessages, useIntl } from 'react-intl';
const messages = defineMessages({
recentrequests: 'Recent Requests',
});
type MediaTitle = MovieDetails | TvDetails;
const UserProfile: React.FC = () => {
const intl = useIntl();
const router = useRouter();
const { user, error } = useUser({
id: Number(router.query.userId),
});
const [availableTitles, setAvailableTitles] = useState<
Record<number, MediaTitle>
>({});
const { data: requests, error: requestError } = useSWR<UserRequestsResponse>(
user ? `/api/v1/user/${user?.id}/requests?take=10&skip=0` : null
);
const updateAvailableTitles = useCallback(
(requestId: number, mediaTitle: MediaTitle) => {
setAvailableTitles((titles) => ({
...titles,
[requestId]: mediaTitle,
}));
},
[]
);
useEffect(() => {
setAvailableTitles({});
}, [user?.id]);
if (!user && !error) {
return <LoadingSpinner />;
}
if (!user) {
return <Error statusCode={404} />;
}
return (
<>
<PageTitle title={user.displayName} />
{Object.keys(availableTitles).length > 0 && (
<div className="absolute left-0 right-0 z-0 -top-16 h-96">
<ImageFader
key={user.id}
isDarker
backgroundImages={Object.values(availableTitles)
.filter((media) => media.backdropPath)
.map(
(media) =>
`//image.tmdb.org/t/p/w1920_and_h800_multi_faces/${media.backdropPath}`
)
.slice(0, 6)}
/>
</div>
)}
<ProfileHeader user={user} />
<div className="relative z-40 mt-6 mb-4 md:flex md:items-center md:justify-between">
<div className="flex-1 min-w-0">
<div className="inline-flex items-center text-xl leading-7 text-gray-300 cursor-default sm:text-2xl sm:leading-9 sm:truncate">
<span>{intl.formatMessage(messages.recentrequests)}</span>
</div>
</div>
</div>
<div className="relative z-40">
<Slider
sliderKey="requests"
isLoading={!requests && !requestError}
isEmpty={!!requests && !requestError && requests.results.length === 0}
items={(requests?.results ?? []).map((request) => (
<RequestCard
key={`request-slider-item-${request.id}`}
request={request}
onTitleData={updateAvailableTitles}
/>
))}
placeholder={<RequestCard.Placeholder />}
emptyMessage={'No Requests'}
/>
</div>
</>
);
};
export default UserProfile;

@ -5,6 +5,7 @@ import {
PermissionCheckOptions,
} from '../../server/lib/permissions';
import { UserType } from '../../server/constants/user';
import { mutateCallback } from 'swr/dist/types';
export { Permission, UserType };
@ -17,6 +18,9 @@ export interface User {
avatar: string;
permissions: number;
userType: number;
createdAt: Date;
updatedAt: Date;
requestCount: number;
}
interface UserHookResponse {
@ -24,6 +28,10 @@ interface UserHookResponse {
loading: boolean;
error: string;
revalidate: () => Promise<boolean>;
mutate: (
data?: User | Promise<User> | mutateCallback<User> | undefined,
shouldRevalidate?: boolean | undefined
) => Promise<User | undefined>;
hasPermission: (
permission: Permission | Permission[],
options?: PermissionCheckOptions
@ -34,7 +42,7 @@ export const useUser = ({
id,
initialData,
}: { id?: number; initialData?: User } = {}): UserHookResponse => {
const { data, error, revalidate } = useSwr<User>(
const { data, error, revalidate, mutate } = useSwr<User>(
id ? `/api/v1/user/${id}` : `/api/v1/auth/me`,
{
initialData,
@ -57,5 +65,6 @@ export const useUser = ({
error,
revalidate,
hasPermission: checkPermission,
mutate,
};
};

@ -28,6 +28,8 @@
"components.Layout.Sidebar.requests": "Requests",
"components.Layout.Sidebar.settings": "Settings",
"components.Layout.Sidebar.users": "Users",
"components.Layout.UserDropdown.myprofile": "Profile",
"components.Layout.UserDropdown.settings": "Settings",
"components.Layout.UserDropdown.signout": "Sign Out",
"components.Layout.alphawarning": "This is ALPHA software. Features may be broken and/or unstable. Please report issues on GitHub!",
"components.Login.email": "Email Address",
@ -614,17 +616,6 @@
"components.TvDetails.userrating": "User Rating",
"components.TvDetails.viewfullcrew": "View Full Crew",
"components.TvDetails.watchtrailer": "Watch Trailer",
"components.UserEdit.avatar": "Avatar",
"components.UserEdit.edituser": "Edit User",
"components.UserEdit.email": "Email Address",
"components.UserEdit.permissions": "Permissions",
"components.UserEdit.plexUsername": "Plex Username",
"components.UserEdit.save": "Save Changes",
"components.UserEdit.saving": "Saving…",
"components.UserEdit.userfail": "Something went wrong while saving the user.",
"components.UserEdit.username": "Display Name",
"components.UserEdit.usersaved": "User saved!",
"components.UserEdit.validationEmail": "You must provide a valid email address",
"components.UserList.admin": "Admin",
"components.UserList.autogeneratepassword": "Automatically generate password",
"components.UserList.bulkedit": "Bulk Edit",
@ -637,6 +628,7 @@
"components.UserList.deleteconfirm": "Are you sure you want to delete this user? All existing request data from this user will be removed.",
"components.UserList.deleteuser": "Delete User",
"components.UserList.edit": "Edit",
"components.UserList.edituser": "Edit User",
"components.UserList.email": "Email Address",
"components.UserList.importedfromplex": "{userCount, plural, =0 {No new users} one {# new user} other {# new users}} imported from Plex",
"components.UserList.importfromplex": "Import Users from Plex",
@ -646,8 +638,11 @@
"components.UserList.password": "Password",
"components.UserList.passwordinfo": "Password Information",
"components.UserList.passwordinfodescription": "Email notifications need to be configured and enabled in order to automatically generate passwords.",
"components.UserList.permissions": "Permissions",
"components.UserList.plexuser": "Plex User",
"components.UserList.role": "Role",
"components.UserList.save": "Save Changes",
"components.UserList.saving": "Saving…",
"components.UserList.sortCreated": "Creation Date",
"components.UserList.sortDisplayName": "Display Name",
"components.UserList.sortRequests": "Request Count",
@ -658,12 +653,61 @@
"components.UserList.usercreatedsuccess": "User created successfully!",
"components.UserList.userdeleted": "User deleted.",
"components.UserList.userdeleteerror": "Something went wrong while deleting the user.",
"components.UserList.userfail": "Something went wrong while saving the user.",
"components.UserList.userlist": "User List",
"components.UserList.users": "Users",
"components.UserList.userssaved": "Users saved!",
"components.UserList.usertype": "User Type",
"components.UserList.validationEmail": "You must provide a valid email address",
"components.UserList.validationpasswordminchars": "Password is too short; should be a minimum of 8 characters",
"components.UserProfile.ProfileHeader.profile": "View Profile",
"components.UserProfile.ProfileHeader.settings": "Edit Settings",
"components.UserProfile.UserSettings.UserGeneralSettings.displayName": "Display Name",
"components.UserProfile.UserSettings.UserGeneralSettings.generalsettings": "General Settings",
"components.UserProfile.UserSettings.UserGeneralSettings.localuser": "Local User",
"components.UserProfile.UserSettings.UserGeneralSettings.plexuser": "Plex User",
"components.UserProfile.UserSettings.UserGeneralSettings.save": "Save Changes",
"components.UserProfile.UserSettings.UserGeneralSettings.saving": "Saving…",
"components.UserProfile.UserSettings.UserGeneralSettings.toastSettingsFailure": "Something went wrong while saving settings.",
"components.UserProfile.UserSettings.UserGeneralSettings.toastSettingsSuccess": "Settings successfully saved!",
"components.UserProfile.UserSettings.UserNotificationSettings.discordId": "Discord ID",
"components.UserProfile.UserSettings.UserNotificationSettings.enableNotifications": "Enable Notifications",
"components.UserProfile.UserSettings.UserNotificationSettings.localuser": "Local User",
"components.UserProfile.UserSettings.UserNotificationSettings.notificationsettings": "Notification Settings",
"components.UserProfile.UserSettings.UserNotificationSettings.plexuser": "Plex User",
"components.UserProfile.UserSettings.UserNotificationSettings.save": "Save Changes",
"components.UserProfile.UserSettings.UserNotificationSettings.saving": "Saving…",
"components.UserProfile.UserSettings.UserNotificationSettings.toastSettingsFailure": "Something went wrong while saving settings.",
"components.UserProfile.UserSettings.UserNotificationSettings.toastSettingsSuccess": "Settings successfully saved!",
"components.UserProfile.UserSettings.UserPasswordChange.confirmpassword": "Confirm Password",
"components.UserProfile.UserSettings.UserPasswordChange.currentpassword": "Current Password",
"components.UserProfile.UserSettings.UserPasswordChange.newpassword": "New Password",
"components.UserProfile.UserSettings.UserPasswordChange.nopasswordset": "No Password Set",
"components.UserProfile.UserSettings.UserPasswordChange.nopasswordsetDescription": "This user account currently does not have an Overseerr-specific password. Configure a password below to allow this account to sign-in as a \"local user.\"",
"components.UserProfile.UserSettings.UserPasswordChange.password": "Password",
"components.UserProfile.UserSettings.UserPasswordChange.save": "Save Changes",
"components.UserProfile.UserSettings.UserPasswordChange.saving": "Saving…",
"components.UserProfile.UserSettings.UserPasswordChange.toastSettingsFailure": "Something went wrong while changing the password. Is your current password correct?",
"components.UserProfile.UserSettings.UserPasswordChange.toastSettingsSuccess": "Password changed!",
"components.UserProfile.UserSettings.UserPasswordChange.validationConfirmPassword": "You must confirm your new password",
"components.UserProfile.UserSettings.UserPasswordChange.validationConfirmPasswordSame": "Password must match",
"components.UserProfile.UserSettings.UserPasswordChange.validationCurrentPassword": "You must provide your current password",
"components.UserProfile.UserSettings.UserPasswordChange.validationNewPassword": "You must provide a new password",
"components.UserProfile.UserSettings.UserPasswordChange.validationNewPasswordLength": "Password is too short; should be a minimum of 8 characters",
"components.UserProfile.UserSettings.UserPermissions.displayName": "Display Name",
"components.UserProfile.UserSettings.UserPermissions.localuser": "Local User",
"components.UserProfile.UserSettings.UserPermissions.permissions": "Permissions",
"components.UserProfile.UserSettings.UserPermissions.plexuser": "Plex User",
"components.UserProfile.UserSettings.UserPermissions.save": "Save Changes",
"components.UserProfile.UserSettings.UserPermissions.saving": "Saving…",
"components.UserProfile.UserSettings.UserPermissions.toastSettingsFailure": "Something went wrong while saving settings.",
"components.UserProfile.UserSettings.UserPermissions.toastSettingsSuccess": "Settings successfully saved!",
"components.UserProfile.UserSettings.menuChangePass": "Password",
"components.UserProfile.UserSettings.menuGeneralSettings": "General Settings",
"components.UserProfile.UserSettings.menuNotifications": "Notifications",
"components.UserProfile.UserSettings.menuPermissions": "Permissions",
"components.UserProfile.UserSettings.settings": "User Settings",
"components.UserProfile.recentrequests": "Recent Requests",
"i18n.advanced": "Advanced",
"i18n.approve": "Approve",
"i18n.approved": "Approved",

@ -0,0 +1,9 @@
import { NextPage } from 'next';
import React from 'react';
import UserProfile from '../../components/UserProfile';
const UserPage: NextPage = () => {
return <UserProfile />;
};
export default UserPage;

@ -0,0 +1,14 @@
import { NextPage } from 'next';
import React from 'react';
import UserSettings from '../../../components/UserProfile/UserSettings';
import UserGeneralSettings from '../../../components/UserProfile/UserSettings/UserGeneralSettings';
const UserSettingsPage: NextPage = () => {
return (
<UserSettings>
<UserGeneralSettings />
</UserSettings>
);
};
export default UserSettingsPage;

@ -0,0 +1,14 @@
import { NextPage } from 'next';
import React from 'react';
import UserSettings from '../../../components/UserProfile/UserSettings';
import UserGeneralSettings from '../../../components/UserProfile/UserSettings/UserGeneralSettings';
const UserSettingsMainPage: NextPage = () => {
return (
<UserSettings>
<UserGeneralSettings />
</UserSettings>
);
};
export default UserSettingsMainPage;

@ -0,0 +1,14 @@
import { NextPage } from 'next';
import React from 'react';
import UserSettings from '../../../components/UserProfile/UserSettings';
import UserNotificationSettings from '../../../components/UserProfile/UserSettings/UserNotificationSettings';
const UserSettingsMainPage: NextPage = () => {
return (
<UserSettings>
<UserNotificationSettings />
</UserSettings>
);
};
export default UserSettingsMainPage;

@ -0,0 +1,14 @@
import { NextPage } from 'next';
import React from 'react';
import UserSettings from '../../../components/UserProfile/UserSettings';
import UserPasswordChange from '../../../components/UserProfile/UserSettings/UserPasswordChange';
const UserPassswordPage: NextPage = () => {
return (
<UserSettings>
<UserPasswordChange />
</UserSettings>
);
};
export default UserPassswordPage;

@ -0,0 +1,14 @@
import { NextPage } from 'next';
import React from 'react';
import UserSettings from '../../../components/UserProfile/UserSettings';
import UserPermissions from '../../../components/UserProfile/UserSettings/UserPermissions';
const UserPermissionsPage: NextPage = () => {
return (
<UserSettings>
<UserPermissions />
</UserSettings>
);
};
export default UserPermissionsPage;

@ -1,12 +0,0 @@
import React from 'react';
import { NextPage } from 'next';
import UserEdit from '../../../components/UserEdit';
import useRouteGuard from '../../../hooks/useRouteGuard';
import { Permission } from '../../../hooks/useUser';
const UserProfilePage: NextPage = () => {
useRouteGuard(Permission.MANAGE_USERS);
return <UserEdit />;
};
export default UserProfilePage;

@ -0,0 +1,9 @@
import { NextPage } from 'next';
import React from 'react';
import UserProfile from '../../../components/UserProfile';
const UserPage: NextPage = () => {
return <UserProfile />;
};
export default UserPage;

@ -0,0 +1,17 @@
import { NextPage } from 'next';
import React from 'react';
import UserSettings from '../../../../components/UserProfile/UserSettings';
import UserGeneralSettings from '../../../../components/UserProfile/UserSettings/UserGeneralSettings';
import useRouteGuard from '../../../../hooks/useRouteGuard';
import { Permission } from '../../../../hooks/useUser';
const UserSettingsPage: NextPage = () => {
useRouteGuard(Permission.MANAGE_USERS);
return (
<UserSettings>
<UserGeneralSettings />
</UserSettings>
);
};
export default UserSettingsPage;

@ -0,0 +1,17 @@
import { NextPage } from 'next';
import React from 'react';
import UserSettings from '../../../../components/UserProfile/UserSettings';
import UserGeneralSettings from '../../../../components/UserProfile/UserSettings/UserGeneralSettings';
import useRouteGuard from '../../../../hooks/useRouteGuard';
import { Permission } from '../../../../hooks/useUser';
const UserSettingsMainPage: NextPage = () => {
useRouteGuard(Permission.MANAGE_USERS);
return (
<UserSettings>
<UserGeneralSettings />
</UserSettings>
);
};
export default UserSettingsMainPage;

@ -0,0 +1,17 @@
import { NextPage } from 'next';
import React from 'react';
import UserSettings from '../../../../components/UserProfile/UserSettings';
import UserNotificationSettings from '../../../../components/UserProfile/UserSettings/UserNotificationSettings';
import useRouteGuard from '../../../../hooks/useRouteGuard';
import { Permission } from '../../../../hooks/useUser';
const UserSettingsMainPage: NextPage = () => {
useRouteGuard(Permission.MANAGE_USERS);
return (
<UserSettings>
<UserNotificationSettings />
</UserSettings>
);
};
export default UserSettingsMainPage;

@ -0,0 +1,17 @@
import { NextPage } from 'next';
import React from 'react';
import UserSettings from '../../../../components/UserProfile/UserSettings';
import UserPasswordChange from '../../../../components/UserProfile/UserSettings/UserPasswordChange';
import useRouteGuard from '../../../../hooks/useRouteGuard';
import { Permission } from '../../../../hooks/useUser';
const UserPassswordPage: NextPage = () => {
useRouteGuard(Permission.MANAGE_USERS);
return (
<UserSettings>
<UserPasswordChange />
</UserSettings>
);
};
export default UserPassswordPage;

@ -0,0 +1,17 @@
import { NextPage } from 'next';
import React from 'react';
import UserSettings from '../../../../components/UserProfile/UserSettings';
import UserPermissions from '../../../../components/UserProfile/UserSettings/UserPermissions';
import useRouteGuard from '../../../../hooks/useRouteGuard';
import { Permission } from '../../../../hooks/useUser';
const UserPermissionsPage: NextPage = () => {
useRouteGuard(Permission.MANAGE_USERS);
return (
<UserSettings>
<UserPermissions />
</UserSettings>
);
};
export default UserPermissionsPage;
Loading…
Cancel
Save