Skip to content

Commit

Permalink
feat(email validation): email requirement and validation + better imp…
Browse files Browse the repository at this point in the history
…orter
  • Loading branch information
Nicolai Van der Storm authored and Nicolai Van der Storm committed Jun 13, 2022
1 parent cc69f66 commit d835336
Show file tree
Hide file tree
Showing 6 changed files with 79 additions and 60 deletions.
41 changes: 30 additions & 11 deletions server/lib/notifications/agents/email.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
NotificationAgentKey,
} from '../../settings';
import { BaseAgent, NotificationAgent, NotificationPayload } from './agent';
import * as EmailValidator from 'email-validator';

class EmailAgent
extends BaseAgent<NotificationAgentEmail>
Expand Down Expand Up @@ -215,14 +216,23 @@ class EmailAgent
this.getSettings(),
payload.notifyUser.settings?.pgpKey
);
await email.send(
this.buildMessage(
type,
payload,
payload.notifyUser.email,
payload.notifyUser.displayName
)
);
if (EmailValidator.validate(payload.notifyUser.email)) {
await email.send(
this.buildMessage(
type,
payload,
payload.notifyUser.email,
payload.notifyUser.displayName
)
);
} else {
logger.warn('Invalid email address provided for user', {
label: 'Notifications',
recipient: payload.notifyUser.displayName,
type: Notification[type],
subject: payload.subject,
});
}
} catch (e) {
logger.error('Error sending email notification', {
label: 'Notifications',
Expand Down Expand Up @@ -268,9 +278,18 @@ class EmailAgent
this.getSettings(),
user.settings?.pgpKey
);
await email.send(
this.buildMessage(type, payload, user.email, user.displayName)
);
if (EmailValidator.validate(user.email)) {
await email.send(
this.buildMessage(type, payload, user.email, user.displayName)
);
} else {
logger.warn('Invalid email address provided for user', {
label: 'Notifications',
recipient: user.displayName,
type: Notification[type],
subject: payload.subject,
});
}
} catch (e) {
logger.error('Error sending email notification', {
label: 'Notifications',
Expand Down
74 changes: 28 additions & 46 deletions server/routes/user/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Router } from 'express';
import gravatarUrl from 'gravatar-url';
import { findIndex, sortBy } from 'lodash';
import { findIndex, forEach, sortBy } from 'lodash';
import { getRepository, In, Not } from 'typeorm';
import JellyfinAPI from '../../api/jellyfin';
import PlexTvAPI from '../../api/plextv';
Expand Down Expand Up @@ -492,62 +492,44 @@ router.post(
);
jellyfinClient.setUserId(admin.jellyfinUserId ?? '');

const jellyfinUsersResponse = await jellyfinClient.getUsers();
//const jellyfinUsersResponse = await jellyfinClient.getUsers();
const createdUsers: User[] = [];
const { hostname, externalHostname } = getSettings().jellyfin;
const jellyfinHost =
externalHostname && externalHostname.length > 0
? externalHostname
: hostname;
for (const account of jellyfinUsersResponse.users) {
if (account.Name) {
const user = await userRepository
.createQueryBuilder('user')
.where('user.jellyfinUserId = :id', { id: account.Id })
.orWhere('user.email = :email', {
email: account.Name,
})
.getOne();

const avatar = account.PrimaryImageTag
? `${jellyfinHost}/Users/${account.Id}/Images/Primary/?tag=${account.PrimaryImageTag}&quality=90`
: '/os_logo_square.png';
forEach(body.jellyfinUserIds, async (jellyfinUserId) => {
jellyfinClient.setUserId(jellyfinUserId);
const jellyfinUser = await jellyfinClient.getUser();

if (user) {
// Update the user's avatar with their Jellyfin thumbnail, in case it changed
user.avatar = avatar;
user.email = account.Name;
user.jellyfinUsername = account.Name;
const user = await userRepository.findOne({
select: ['id', 'jellyfinUserId'],
where: { jellyfinUserId: jellyfinUserId },
});

// In case the user was previously a local account
if (user.userType === UserType.LOCAL) {
user.userType = UserType.JELLYFIN;
user.jellyfinUserId = account.Id;
}
await userRepository.save(user);
} else if (!body || body.jellyfinUserIds.includes(account.Id)) {
// logger.error('CREATED USER', {
// label: 'API',
// });

const newUser = new User({
jellyfinUsername: account.Name,
jellyfinUserId: account.Id,
jellyfinDeviceId: Buffer.from(
`BOT_overseerr_${account.Name ?? ''}`
).toString('base64'),
email: account.Name,
permissions: settings.main.defaultPermissions,
avatar,
userType: UserType.JELLYFIN,
});
await userRepository.save(newUser);
createdUsers.push(newUser);
}
if (!user) {
const newUser = new User({
jellyfinUsername: jellyfinUser.Name,
jellyfinUserId: jellyfinUser.Id,
jellyfinDeviceId: Buffer.from(
`BOT_jellyseerr_${jellyfinUser.Name ?? ''}`
).toString('base64'),
email: jellyfinUser.Name,
permissions: settings.main.defaultPermissions,
avatar: jellyfinUser.PrimaryImageTag
? `${jellyfinHost}/Users/${jellyfinUser.Id}/Images/Primary/?tag=${jellyfinUser.PrimaryImageTag}&quality=90`
: '/os_logo_square.png',
userType: UserType.JELLYFIN,
});

await userRepository.save(newUser);
createdUsers.push(newUser);
}
}

return res.status(201).json(User.filterMany(createdUsers));
return res.status(201).json(User.filterMany(createdUsers));
});
} catch (e) {
next({ status: 500, message: e.message });
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/Setup/LoginWithPlex.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useUser } from '../../hooks/useUser';
import PlexLoginButton from '../PlexLoginButton';

const messages = defineMessages({
welcome: 'Welcome to Overseerr',
welcome: 'Welcome to Jellyseerr',
signinMessage: 'Get started by signing in with your Plex account',
});

Expand Down
2 changes: 1 addition & 1 deletion src/components/Setup/SetupLogin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { MediaServerType } from '../../../server/constants/server';
import getConfig from 'next/config';

const messages = defineMessages({
welcome: 'Welcome to Overseerr',
welcome: 'Welcome to Jellyseerr',
signinMessage: 'Get started by signing in',
signinWithJellyfin: 'Use your {mediaServerName} account',
signinWithPlex: 'Use your Plex account',
Expand Down
16 changes: 16 additions & 0 deletions src/components/UserList/JellyfinImportModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import globalMessages from '../../i18n/globalMessages';
import Alert from '../Common/Alert';
import Modal from '../Common/Modal';
import getConfig from 'next/config';
import { UserResultsResponse } from '../../../server/interfaces/api/userInterfaces';

interface JellyfinImportProps {
onCancel?: () => void;
Expand All @@ -30,6 +31,7 @@ const messages = defineMessages({
const JellyfinImportModal: React.FC<JellyfinImportProps> = ({
onCancel,
onComplete,
children,
}) => {
const intl = useIntl();
const settings = useSettings();
Expand Down Expand Up @@ -117,6 +119,20 @@ const JellyfinImportModal: React.FC<JellyfinImportProps> = ({
}
};

const { data: existingUsers } = useSWR<UserResultsResponse>(
`/api/v1/user?take=${children}`
);

data?.forEach((user, pos) => {
if (
existingUsers?.results.some(
(existingUser) => existingUser.jellyfinUserId === user.id
)
) {
delete data[pos];
}
});

return (
<Modal
loading={!data && !error}
Expand Down
4 changes: 3 additions & 1 deletion src/components/UserList/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,9 @@ const UserList: React.FC = () => {
setShowImportModal(false);
revalidate();
}}
/>
>
{data.pageInfo.results}
</JellyfinImportModal>
)}
</Transition>

Expand Down

0 comments on commit d835336

Please sign in to comment.