diff --git a/api/src/routes/auth/login.ts b/api/src/routes/auth/login.ts
index 7fd0f870..ff04f8aa 100644
--- a/api/src/routes/auth/login.ts
+++ b/api/src/routes/auth/login.ts
@@ -1,93 +1,70 @@
import { Request, Response, Router } from "express";
-import { check, FieldErrors, Length } from "../../util/instanceOf";
+import { FieldErrors, route } from "@fosscord/api";
import bcrypt from "bcrypt";
-import jwt from "jsonwebtoken";
-import { Config, User } from "@fosscord/util";
-import { adjustEmail } from "./register";
+import { Config, User, generateToken, adjustEmail } from "@fosscord/util";
const router: Router = Router();
export default router;
-router.post(
- "/",
- check({
- login: new Length(String, 2, 100), // email or telephone
- password: new Length(String, 8, 72),
- $undelete: Boolean,
- $captcha_key: String,
- $login_source: String,
- $gift_code_sku_id: String
- }),
- async (req: Request, res: Response) => {
- const { login, password, captcha_key, undelete } = req.body;
- const email = adjustEmail(login);
- console.log("login", email);
-
- const config = Config.get();
-
- if (config.login.requireCaptcha && config.security.captcha.enabled) {
- if (!captcha_key) {
- const { sitekey, service } = config.security.captcha;
- return res.status(400).json({
- captcha_key: ["captcha-required"],
- captcha_sitekey: sitekey,
- captcha_service: service
- });
- }
+export interface LoginSchema {
+ login: string;
+ password: string;
+ undelete?: boolean;
+ captcha_key?: string;
+ login_source?: string;
+ gift_code_sku_id?: string;
+}
- // TODO: check captcha
- }
+router.post("/", route({ body: "LoginSchema" }), async (req: Request, res: Response) => {
+ const { login, password, captcha_key, undelete } = req.body as LoginSchema;
+ const email = adjustEmail(login);
+ console.log("login", email);
- const user = await User.findOneOrFail({
- where: [{ phone: login }, { email: login }],
- select: ["data", "id", "disabled", "deleted", "settings"]
- }).catch((e) => {
- throw FieldErrors({ login: { message: req.t("auth:login.INVALID_LOGIN"), code: "INVALID_LOGIN" } });
- });
+ const config = Config.get();
- if (undelete) {
- // undelete refers to un'disable' here
- if (user.disabled) await User.update({ id: user.id }, { disabled: false });
- if (user.deleted) await User.update({ id: user.id }, { deleted: false });
- } else {
- if (user.deleted) return res.status(400).json({ message: "This account is scheduled for deletion.", code: 20011 });
- if (user.disabled) return res.status(400).json({ message: req.t("auth:login.ACCOUNT_DISABLED"), code: 20013 });
+ if (config.login.requireCaptcha && config.security.captcha.enabled) {
+ if (!captcha_key) {
+ const { sitekey, service } = config.security.captcha;
+ return res.status(400).json({
+ captcha_key: ["captcha-required"],
+ captcha_sitekey: sitekey,
+ captcha_service: service
+ });
}
- // the salt is saved in the password refer to bcrypt docs
- const same_password = await bcrypt.compare(password, user.data.hash || "");
- if (!same_password) {
- throw FieldErrors({ password: { message: req.t("auth:login.INVALID_PASSWORD"), code: "INVALID_PASSWORD" } });
- }
+ // TODO: check captcha
+ }
- const token = await generateToken(user.id);
+ const user = await User.findOneOrFail({
+ where: [{ phone: login }, { email: login }],
+ select: ["data", "id", "disabled", "deleted", "settings"]
+ }).catch((e) => {
+ throw FieldErrors({ login: { message: req.t("auth:login.INVALID_LOGIN"), code: "INVALID_LOGIN" } });
+ });
- // Notice this will have a different token structure, than discord
- // Discord header is just the user id as string, which is not possible with npm-jsonwebtoken package
- // https://user-images.githubusercontent.com/6506416/81051916-dd8c9900-8ec2-11ea-8794-daf12d6f31f0.png
+ if (undelete) {
+ // undelete refers to un'disable' here
+ if (user.disabled) await User.update({ id: user.id }, { disabled: false });
+ if (user.deleted) await User.update({ id: user.id }, { deleted: false });
+ } else {
+ if (user.deleted) return res.status(400).json({ message: "This account is scheduled for deletion.", code: 20011 });
+ if (user.disabled) return res.status(400).json({ message: req.t("auth:login.ACCOUNT_DISABLED"), code: 20013 });
+ }
- res.json({ token, settings: user.settings });
+ // the salt is saved in the password refer to bcrypt docs
+ const same_password = await bcrypt.compare(password, user.data.hash || "");
+ if (!same_password) {
+ throw FieldErrors({ password: { message: req.t("auth:login.INVALID_PASSWORD"), code: "INVALID_PASSWORD" } });
}
-);
-export async function generateToken(id: string) {
- const iat = Math.floor(Date.now() / 1000);
- const algorithm = "HS256";
+ const token = await generateToken(user.id);
- return new Promise((res, rej) => {
- jwt.sign(
- { id: id, iat },
- Config.get().security.jwtSecret,
- {
- algorithm
- },
- (err, token) => {
- if (err) return rej(err);
- return res(token);
- }
- );
- });
-}
+ // Notice this will have a different token structure, than discord
+ // Discord header is just the user id as string, which is not possible with npm-jsonwebtoken package
+ // https://user-images.githubusercontent.com/6506416/81051916-dd8c9900-8ec2-11ea-8794-daf12d6f31f0.png
+
+ res.json({ token, settings: user.settings });
+});
/**
* POST /auth/login
diff --git a/api/src/routes/auth/register.ts b/api/src/routes/auth/register.ts
index a9518e91..9c058399 100644
--- a/api/src/routes/auth/register.ts
+++ b/api/src/routes/auth/register.ts
@@ -1,234 +1,230 @@
import { Request, Response, Router } from "express";
-import { trimSpecial, User, Snowflake, Config, defaultSettings } from "@fosscord/util";
+import { trimSpecial, User, Snowflake, Config, defaultSettings, generateToken, Invite, adjustEmail } from "@fosscord/util";
import bcrypt from "bcrypt";
-import { check, Email, EMAIL_REGEX, FieldErrors, Length } from "../../util/instanceOf";
+import { FieldErrors, route, getIpAdress, IPAnalysis, isProxy } from "@fosscord/api";
import "missing-native-js-functions";
-import { generateToken } from "./login";
-import { getIpAdress, IPAnalysis, isProxy } from "../../util/ipAddress";
import { HTTPError } from "lambert-server";
-import { In } from "typeorm";
const router: Router = Router();
-router.post(
- "/",
- check({
- username: new Length(String, 2, 32),
- // TODO: check min password length in config
- // prevent Denial of Service with max length of 72 chars
- password: new Length(String, 8, 72),
- consent: Boolean,
- $email: new Length(Email, 5, 100),
- $fingerprint: String,
- $invite: String,
- $date_of_birth: Date, // "2000-04-03"
- $gift_code_sku_id: String,
- $captcha_key: String
- }),
- async (req: Request, res: Response) => {
- const {
- email,
- username,
- password,
- consent,
- fingerprint,
- invite,
- date_of_birth,
- gift_code_sku_id, // ? what is this
- captcha_key
- } = req.body;
+export interface RegisterSchema {
+ /**
+ * @minLength 2
+ * @maxLength 32
+ */
+ username: string;
+ /**
+ * @minLength 1
+ * @maxLength 72
+ */
+ password?: string;
+ consent: boolean;
+ /**
+ * @TJS-format email
+ */
+ email?: string;
+ fingerprint?: string;
+ invite?: string;
+ /**
+ * @TJS-type string
+ */
+ date_of_birth?: Date; // "2000-04-03"
+ gift_code_sku_id?: string;
+ captcha_key?: string;
+}
- // get register Config
- const { register, security } = Config.get();
- const ip = getIpAdress(req);
+router.post("/", route({ body: "RegisterSchema" }), async (req: Request, res: Response) => {
+ let {
+ email,
+ username,
+ password,
+ consent,
+ fingerprint,
+ invite,
+ date_of_birth,
+ gift_code_sku_id, // ? what is this
+ captcha_key
+ } = req.body;
- if (register.blockProxies) {
- if (isProxy(await IPAnalysis(ip))) {
- console.log(`proxy ${ip} blocked from registration`);
- throw new HTTPError("Your IP is blocked from registration");
- }
+ // get register Config
+ const { register, security } = Config.get();
+ const ip = getIpAdress(req);
+
+ if (register.blockProxies) {
+ if (isProxy(await IPAnalysis(ip))) {
+ console.log(`proxy ${ip} blocked from registration`);
+ throw new HTTPError("Your IP is blocked from registration");
}
+ }
- console.log("register", req.body.email, req.body.username, ip);
- // TODO: automatically join invite
- // TODO: gift_code_sku_id?
- // TODO: check password strength
+ console.log("register", req.body.email, req.body.username, ip);
+ // TODO: gift_code_sku_id?
+ // TODO: check password strength
- // adjusted_email will be slightly modified version of the user supplied email -> e.g. protection against GMail Trick
- let adjusted_email = adjustEmail(email);
+ // email will be slightly modified version of the user supplied email -> e.g. protection against GMail Trick
+ email = adjustEmail(email);
- // adjusted_password will be the hash of the password
- let adjusted_password = "";
+ // trim special uf8 control characters -> Backspace, Newline, ...
+ username = trimSpecial(username);
- // trim special uf8 control characters -> Backspace, Newline, ...
- let adjusted_username = trimSpecial(username);
+ // discriminator will be randomly generated
+ let discriminator = "";
- // discriminator will be randomly generated
- let discriminator = "";
+ // check if registration is allowed
+ if (!register.allowNewRegistration) {
+ throw FieldErrors({
+ email: { code: "REGISTRATION_DISABLED", message: req.t("auth:register.REGISTRATION_DISABLED") }
+ });
+ }
- // check if registration is allowed
- if (!register.allowNewRegistration) {
- throw FieldErrors({
- email: { code: "REGISTRATION_DISABLED", message: req.t("auth:register.REGISTRATION_DISABLED") }
- });
- }
+ // check if the user agreed to the Terms of Service
+ if (!consent) {
+ throw FieldErrors({
+ consent: { code: "CONSENT_REQUIRED", message: req.t("auth:register.CONSENT_REQUIRED") }
+ });
+ }
- // check if the user agreed to the Terms of Service
- if (!consent) {
- throw FieldErrors({
- consent: { code: "CONSENT_REQUIRED", message: req.t("auth:register.CONSENT_REQUIRED") }
- });
- }
+ if (email) {
+ // replace all dots and chars after +, if its a gmail.com email
+ if (!email) throw FieldErrors({ email: { code: "INVALID_EMAIL", message: req.t("auth:register.INVALID_EMAIL") } });
- // require invite to register -> e.g. for organizations to send invites to their employees
- if (register.requireInvite && !invite) {
+ // check if there is already an account with this email
+ const exists = await User.findOneOrFail({ email: email }).catch((e) => {});
+
+ if (exists) {
throw FieldErrors({
- email: { code: "INVITE_ONLY", message: req.t("auth:register.INVITE_ONLY") }
+ email: {
+ code: "EMAIL_ALREADY_REGISTERED",
+ message: req.t("auth:register.EMAIL_ALREADY_REGISTERED")
+ }
});
}
+ } else if (register.email.required) {
+ throw FieldErrors({
+ email: { code: "BASE_TYPE_REQUIRED", message: req.t("common:field.BASE_TYPE_REQUIRED") }
+ });
+ }
- if (email) {
- // replace all dots and chars after +, if its a gmail.com email
- if (!adjusted_email) throw FieldErrors({ email: { code: "INVALID_EMAIL", message: req.t("auth:register.INVALID_EMAIL") } });
-
- // check if there is already an account with this email
- const exists = await User.findOneOrFail({ email: adjusted_email }).catch((e) => {});
+ if (register.dateOfBirth.required && !date_of_birth) {
+ throw FieldErrors({
+ date_of_birth: { code: "BASE_TYPE_REQUIRED", message: req.t("common:field.BASE_TYPE_REQUIRED") }
+ });
+ } else if (register.dateOfBirth.minimum) {
+ const minimum = new Date();
+ minimum.setFullYear(minimum.getFullYear() - register.dateOfBirth.minimum);
+ date_of_birth = new Date(date_of_birth);
- if (exists) {
- throw FieldErrors({
- email: {
- code: "EMAIL_ALREADY_REGISTERED",
- message: req.t("auth:register.EMAIL_ALREADY_REGISTERED")
- }
- });
- }
- } else if (register.email.necessary) {
+ // higher is younger
+ if (date_of_birth > minimum) {
throw FieldErrors({
- email: { code: "BASE_TYPE_REQUIRED", message: req.t("common:field.BASE_TYPE_REQUIRED") }
+ date_of_birth: {
+ code: "DATE_OF_BIRTH_UNDERAGE",
+ message: req.t("auth:register.DATE_OF_BIRTH_UNDERAGE", { years: register.dateOfBirth.minimum })
+ }
});
}
+ }
+
+ if (!register.allowMultipleAccounts) {
+ // TODO: check if fingerprint was eligible generated
+ const exists = await User.findOne({ where: { fingerprints: fingerprint } });
- if (register.dateOfBirth.necessary && !date_of_birth) {
+ if (exists) {
throw FieldErrors({
- date_of_birth: { code: "BASE_TYPE_REQUIRED", message: req.t("common:field.BASE_TYPE_REQUIRED") }
+ email: {
+ code: "EMAIL_ALREADY_REGISTERED",
+ message: req.t("auth:register.EMAIL_ALREADY_REGISTERED")
+ }
});
- } else if (register.dateOfBirth.minimum) {
- const minimum = new Date();
- minimum.setFullYear(minimum.getFullYear() - register.dateOfBirth.minimum);
-
- // higher is younger
- if (date_of_birth > minimum) {
- throw FieldErrors({
- date_of_birth: {
- code: "DATE_OF_BIRTH_UNDERAGE",
- message: req.t("auth:register.DATE_OF_BIRTH_UNDERAGE", { years: register.dateOfBirth.minimum })
- }
- });
- }
}
+ }
- if (!register.allowMultipleAccounts) {
- // TODO: check if fingerprint was eligible generated
- const exists = await User.findOne({ where: { fingerprints: In(fingerprint) } });
-
- if (exists) {
- throw FieldErrors({
- email: {
- code: "EMAIL_ALREADY_REGISTERED",
- message: req.t("auth:register.EMAIL_ALREADY_REGISTERED")
- }
- });
- }
+ if (register.requireCaptcha && security.captcha.enabled) {
+ if (!captcha_key) {
+ const { sitekey, service } = security.captcha;
+ return res.status(400).json({
+ captcha_key: ["captcha-required"],
+ captcha_sitekey: sitekey,
+ captcha_service: service
+ });
}
- if (register.requireCaptcha && security.captcha.enabled) {
- if (!captcha_key) {
- const { sitekey, service } = security.captcha;
- return res.status(400).json({
- captcha_key: ["captcha-required"],
- captcha_sitekey: sitekey,
- captcha_service: service
- });
- }
-
- // TODO: check captcha
- }
+ // TODO: check captcha
+ }
+ if (password) {
// the salt is saved in the password refer to bcrypt docs
- adjusted_password = await bcrypt.hash(password, 12);
-
- let exists;
- // randomly generates a discriminator between 1 and 9999 and checks max five times if it already exists
- // if it all five times already exists, abort with USERNAME_TOO_MANY_USERS error
- // else just continue
- // TODO: is there any better way to generate a random discriminator only once, without checking if it already exists in the mongodb database?
- for (let tries = 0; tries < 5; tries++) {
- discriminator = Math.randomIntBetween(1, 9999).toString().padStart(4, "0");
- exists = await User.findOne({ where: { discriminator, username: adjusted_username }, select: ["id"] });
- if (!exists) break;
- }
-
- if (exists) {
- throw FieldErrors({
- username: {
- code: "USERNAME_TOO_MANY_USERS",
- message: req.t("auth:register.USERNAME_TOO_MANY_USERS")
- }
- });
- }
-
- // TODO: save date_of_birth
- // appearently discord doesn't save the date of birth and just calculate if nsfw is allowed
- // if nsfw_allowed is null/undefined it'll require date_of_birth to set it to true/false
+ password = await bcrypt.hash(password, 12);
+ } else if (register.password.required) {
+ throw FieldErrors({
+ password: { code: "BASE_TYPE_REQUIRED", message: req.t("common:field.BASE_TYPE_REQUIRED") }
+ });
+ }
- const user = await new User({
- created_at: new Date(),
- username: adjusted_username,
- discriminator,
- id: Snowflake.generate(),
- bot: false,
- system: false,
- desktop: false,
- mobile: false,
- premium: true,
- premium_type: 2,
- bio: "",
- mfa_enabled: false,
- verified: false,
- disabled: false,
- deleted: false,
- email: adjusted_email,
- nsfw_allowed: true, // TODO: depending on age
- public_flags: "0",
- flags: "0", // TODO: generate
- data: {
- hash: adjusted_password,
- valid_tokens_since: new Date()
- },
- settings: { ...defaultSettings, locale: req.language || "en-US" },
- fingerprints: []
- }).save();
+ let exists;
+ // randomly generates a discriminator between 1 and 9999 and checks max five times if it already exists
+ // if it all five times already exists, abort with USERNAME_TOO_MANY_USERS error
+ // else just continue
+ // TODO: is there any better way to generate a random discriminator only once, without checking if it already exists in the mongodb database?
+ for (let tries = 0; tries < 5; tries++) {
+ discriminator = Math.randomIntBetween(1, 9999).toString().padStart(4, "0");
+ exists = await User.findOne({ where: { discriminator, username: username }, select: ["id"] });
+ if (!exists) break;
+ }
- return res.json({ token: await generateToken(user.id) });
+ if (exists) {
+ throw FieldErrors({
+ username: {
+ code: "USERNAME_TOO_MANY_USERS",
+ message: req.t("auth:register.USERNAME_TOO_MANY_USERS")
+ }
+ });
}
-);
-export function adjustEmail(email: string): string | undefined {
- // body parser already checked if it is a valid email
- const parts = <RegExpMatchArray>email.match(EMAIL_REGEX);
- // @ts-ignore
- if (!parts || parts.length < 5) return undefined;
- const domain = parts[5];
- const user = parts[1];
+ // TODO: save date_of_birth
+ // appearently discord doesn't save the date of birth and just calculate if nsfw is allowed
+ // if nsfw_allowed is null/undefined it'll require date_of_birth to set it to true/false
- // TODO: check accounts with uncommon email domains
- if (domain === "gmail.com" || domain === "googlemail.com") {
- // replace .dots and +alternatives -> Gmail Dot Trick https://support.google.com/mail/answer/7436150 and https://generator.email/blog/gmail-generator
- return user.replace(/[.]|(\+.*)/g, "") + "@gmail.com";
+ const user = await new User({
+ created_at: new Date(),
+ username: username,
+ discriminator,
+ id: Snowflake.generate(),
+ bot: false,
+ system: false,
+ desktop: false,
+ mobile: false,
+ premium: true,
+ premium_type: 2,
+ bio: "",
+ mfa_enabled: false,
+ verified: true,
+ disabled: false,
+ deleted: false,
+ email: email,
+ nsfw_allowed: true, // TODO: depending on age
+ public_flags: "0",
+ flags: "0", // TODO: generate
+ data: {
+ hash: password,
+ valid_tokens_since: new Date()
+ },
+ settings: { ...defaultSettings, locale: req.language || "en-US" },
+ fingerprints: []
+ }).save();
+
+ if (invite) {
+ // await to fail if the invite doesn't exist (necessary for requireInvite to work properly) (username only signups are possible)
+ await Invite.joinGuild(user.id, invite);
+ } else if (register.requireInvite) {
+ // require invite to register -> e.g. for organizations to send invites to their employees
+ throw FieldErrors({
+ email: { code: "INVITE_ONLY", message: req.t("auth:register.INVITE_ONLY") }
+ });
}
- return email;
-}
+ return res.json({ token: await generateToken(user.id) });
+});
export default router;
|