mirror of
https://github.com/outline/outline.git
synced 2026-12-04 02:20:17 +03:00
api
This commit is contained in:
1 parent
a458690bfc
commit
86f66f8eed
6 files changed
+229
-1
No files matched your search
@@ -0,0 +1,67 @@
|
||||
import * as React from "react";
|
||||
import env from "@server/env";
|
||||
import BaseEmail, { EmailMessageCategory, EmailProps } from "./BaseEmail";
|
||||
import Body from "./components/Body";
|
||||
import Button from "./components/Button";
|
||||
import EmailTemplate from "./components/EmailLayout";
|
||||
import EmptySpace from "./components/EmptySpace";
|
||||
import Footer from "./components/Footer";
|
||||
import Header from "./components/Header";
|
||||
import Heading from "./components/Heading";
|
||||
|
||||
type Props = EmailProps & {
|
||||
token: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Email sent to a user when they request to change their email.
|
||||
*/
|
||||
export default class ConfirmUpdateEmail extends BaseEmail<Props> {
|
||||
protected get category() {
|
||||
return EmailMessageCategory.Authentication;
|
||||
}
|
||||
|
||||
protected subject() {
|
||||
return `Your email update request`;
|
||||
}
|
||||
|
||||
protected preview() {
|
||||
return `Here’s your email change confirmation.`;
|
||||
}
|
||||
|
||||
protected renderAsText({ token }: Props): string {
|
||||
return `
|
||||
You requested to update your ${env.APP_NAME} account email. Please
|
||||
follow the link below to confirm the change.
|
||||
|
||||
${this.updateLink(token)}
|
||||
|
||||
`;
|
||||
}
|
||||
|
||||
protected render({ token }: Props) {
|
||||
return (
|
||||
<EmailTemplate previewText={this.preview()}>
|
||||
<Header />
|
||||
|
||||
<Body>
|
||||
<Heading>Your email update request</Heading>
|
||||
<p>
|
||||
You requested to update your {env.APP_NAME} account email. Please
|
||||
click below to confirm the change.
|
||||
</p>
|
||||
<EmptySpace height={5} />
|
||||
<p>
|
||||
<Button href={this.updateLink(token)}>Confirm Change</Button>
|
||||
</p>
|
||||
</Body>
|
||||
|
||||
<Footer />
|
||||
</EmailTemplate>
|
||||
);
|
||||
}
|
||||
|
||||
private updateLink(token: string): string {
|
||||
return `${env.URL}/api/users.updateEmail?token=${token}`;
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,8 @@ import Fix from "./decorators/Fix";
|
||||
import IsUrlOrRelativePath from "./validators/IsUrlOrRelativePath";
|
||||
import Length from "./validators/Length";
|
||||
import NotContainsUrl from "./validators/NotContainsUrl";
|
||||
import { WhereOptions } from "sequelize";
|
||||
import { APIContext } from "@server/types";
|
||||
|
||||
/**
|
||||
* Flags that are available for setting on the user.
|
||||
@@ -581,6 +583,24 @@ class User extends ParanoidModel<
|
||||
this.jwtSecret
|
||||
);
|
||||
|
||||
/**
|
||||
* Returns a temporary token that can be used to update the users
|
||||
* email address.
|
||||
*
|
||||
* @param email The new email address
|
||||
* @returns The token
|
||||
*/
|
||||
getEmailUpdateToken = (email: string) =>
|
||||
JWT.sign(
|
||||
{
|
||||
id: this.id,
|
||||
createdAt: new Date().toISOString(),
|
||||
email,
|
||||
type: "email-update",
|
||||
},
|
||||
this.jwtSecret
|
||||
);
|
||||
|
||||
/**
|
||||
* Returns a list of teams that have a user matching this user's email.
|
||||
*
|
||||
@@ -705,6 +725,19 @@ class User extends ParanoidModel<
|
||||
}
|
||||
};
|
||||
|
||||
static findByEmail = async function (
|
||||
ctx: APIContext,
|
||||
email: string,
|
||||
) {
|
||||
return this.findOne({
|
||||
where: {
|
||||
teamId: ctx.context.auth.user.teamId,
|
||||
email: email.trim().toLowerCase(),
|
||||
},
|
||||
...ctx.context,
|
||||
});
|
||||
};
|
||||
|
||||
static getCounts = async function (teamId: string) {
|
||||
const countSql = `
|
||||
SELECT
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { z } from "zod";
|
||||
import { NotificationEventType, UserPreference, UserRole } from "@shared/types";
|
||||
import {
|
||||
Client,
|
||||
NotificationEventType,
|
||||
UserPreference,
|
||||
UserRole,
|
||||
} from "@shared/types";
|
||||
import { locales } from "@shared/utils/date";
|
||||
import User from "@server/models/User";
|
||||
import { zodEnumFromObjectKeys, zodTimezone } from "@server/utils/zod";
|
||||
@@ -99,6 +104,26 @@ export const UsersDeleteSchema = BaseSchema.extend({
|
||||
|
||||
export type UsersDeleteSchemaReq = z.infer<typeof UsersDeleteSchema>;
|
||||
|
||||
export const UsersUpdateEmailSchema = BaseSchema.extend({
|
||||
body: z.object({
|
||||
id: z.string().uuid().optional(),
|
||||
email: z.string().email(),
|
||||
}),
|
||||
});
|
||||
|
||||
export type UsersUpdateEmailReq = z.infer<typeof UsersUpdateEmailSchema>;
|
||||
|
||||
export const UsersUpdateEmailConfirmSchema = BaseSchema.extend({
|
||||
query: z.object({
|
||||
token: z.string(),
|
||||
follow: z.string().default(""),
|
||||
}),
|
||||
});
|
||||
|
||||
export type UsersUpdateEmailConfirmReq = z.infer<
|
||||
typeof UsersUpdateEmailConfirmSchema
|
||||
>;
|
||||
|
||||
export const UsersInfoSchema = BaseSchema.extend({
|
||||
body: z.object({
|
||||
id: z.string().uuid().optional(),
|
||||
|
||||
@@ -2,11 +2,13 @@ import Router from "koa-router";
|
||||
import { Op, Sequelize, WhereOptions } from "sequelize";
|
||||
import { UserPreference, UserRole } from "@shared/types";
|
||||
import { UserRoleHelper } from "@shared/utils/UserRoleHelper";
|
||||
import { settingsPath } from "@shared/utils/routeHelpers";
|
||||
import { UserValidation } from "@shared/validations";
|
||||
import userDestroyer from "@server/commands/userDestroyer";
|
||||
import userInviter from "@server/commands/userInviter";
|
||||
import userSuspender from "@server/commands/userSuspender";
|
||||
import userUnsuspender from "@server/commands/userUnsuspender";
|
||||
import ConfirmUpdateEmail from "@server/emails/templates/ConfirmUpdateEmail";
|
||||
import ConfirmUserDeleteEmail from "@server/emails/templates/ConfirmUserDeleteEmail";
|
||||
import InviteEmail from "@server/emails/templates/InviteEmail";
|
||||
import env from "@server/env";
|
||||
@@ -23,6 +25,7 @@ import { presentUser, presentPolicies } from "@server/presenters";
|
||||
import { APIContext } from "@server/types";
|
||||
import { RateLimiterStrategy } from "@server/utils/RateLimiter";
|
||||
import { safeEqual } from "@server/utils/crypto";
|
||||
import { getDetailsForEmailUpdateToken } from "@server/utils/jwt";
|
||||
import pagination from "../middlewares/pagination";
|
||||
import * as T from "./schema";
|
||||
|
||||
@@ -201,6 +204,72 @@ router.post(
|
||||
}
|
||||
);
|
||||
|
||||
router.post(
|
||||
"users.updateEmail",
|
||||
rateLimiter(RateLimiterStrategy.FivePerHour),
|
||||
auth(),
|
||||
validate(T.UsersUpdateEmailSchema),
|
||||
async (ctx: APIContext<T.UsersUpdateEmailReq>) => {
|
||||
const actor = ctx.state.auth.user;
|
||||
const email = ctx.input.body.email.trim().toLowerCase();
|
||||
|
||||
authorize(actor, "update", actor);
|
||||
|
||||
// Check if email already exists in workspace
|
||||
if (await User.findByEmail(ctx, email)) {
|
||||
throw ValidationError("User with email already exists");
|
||||
}
|
||||
|
||||
await new ConfirmUpdateEmail({
|
||||
to: email,
|
||||
token: actor.getEmailUpdateToken(email),
|
||||
}).schedule();
|
||||
|
||||
ctx.body = {
|
||||
success: true,
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
router.get(
|
||||
"users.updateEmail",
|
||||
rateLimiter(RateLimiterStrategy.FivePerHour),
|
||||
auth(),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.UsersUpdateEmailConfirmReq>) => {
|
||||
const { token, follow } = ctx.input.query;
|
||||
|
||||
// The link in the email does not include the follow query param, this
|
||||
// is to help prevent anti-virus, and email clients from pre-fetching the link
|
||||
// and spending the token before the user clicks on it. Instead we redirect
|
||||
// to the same URL with the follow query param added from the client side.
|
||||
if (!follow) {
|
||||
return ctx.redirectOnClient(ctx.request.href + "&follow=true");
|
||||
}
|
||||
let user: User;
|
||||
let email: string;
|
||||
|
||||
try {
|
||||
const res = await getDetailsForEmailUpdateToken(token as string);
|
||||
user = res.user;
|
||||
email = res.email;
|
||||
} catch (err) {
|
||||
ctx.redirect(`/?notice=expired-token`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if email already exists in workspace
|
||||
if (await User.findByEmail(ctx, email)) {
|
||||
// TODO: Redirect to error?
|
||||
throw ValidationError("User with email already exists");
|
||||
}
|
||||
|
||||
await user.updateWithCtx(ctx, { email });
|
||||
|
||||
ctx.redirect(settingsPath("profile"));
|
||||
}
|
||||
);
|
||||
|
||||
router.post(
|
||||
"users.update",
|
||||
auth(),
|
||||
|
||||
@@ -105,3 +105,33 @@ export async function getUserForEmailSigninToken(token: string): Promise<User> {
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
export async function getDetailsForEmailUpdateToken(
|
||||
token: string
|
||||
): Promise<{ user: User; email: string }> {
|
||||
const payload = getJWTPayload(token);
|
||||
|
||||
if (payload.type !== "email-update") {
|
||||
throw AuthenticationError("Invalid token");
|
||||
}
|
||||
|
||||
// check the token is within it's expiration time
|
||||
if (payload.createdAt) {
|
||||
if (new Date(payload.createdAt) < subMinutes(new Date(), 10)) {
|
||||
throw AuthenticationError("Expired token");
|
||||
}
|
||||
}
|
||||
|
||||
const email = payload.email;
|
||||
const user = await User.scope("withTeam").findByPk(payload.id, {
|
||||
rejectOnEmpty: true,
|
||||
});
|
||||
|
||||
try {
|
||||
JWT.verify(token, user.jwtSecret);
|
||||
} catch (err) {
|
||||
throw AuthenticationError("Invalid token");
|
||||
}
|
||||
|
||||
return { user, email };
|
||||
}
|
||||
@@ -2,6 +2,10 @@ export function signin(service = "slack"): string {
|
||||
return `/auth/${service}`;
|
||||
}
|
||||
|
||||
export function settingsPath(section?: string): string {
|
||||
return "/settings" + (section ? `/${section}` : "");
|
||||
}
|
||||
|
||||
export function integrationSettingsPath(id: string): string {
|
||||
return `/settings/integrations/${id}`;
|
||||
}
|
||||
Reference in new issue
Block a user