feat: user profile/settings pages (#958)
parent
29b97ef6d8
commit
bbb683e637
@ -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;
|
||||
}
|
@ -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"`);
|
||||
}
|
||||
}
|
@ -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,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;
|
@ -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;
|
@ -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…
Reference in new issue