Przeglądaj źródła

refactor: Continued configuration consolidation

Owen Diffey 1 rok temu
rodzic
commit
12a93e7f71

+ 2 - 2
backend/config/custom-environment-variables.json

@@ -1,11 +1,11 @@
 {
 	"sitename": "MUSARE_SITENAME",
 	"redis": {
-		"url": "REDIS_URL",
 		"password": "REDIS_PASSWORD"
 	},
 	"mongo": {
-		"url": "MONGO_URL"
+		"user": "MONGO_USER_USERNAME",
+		"password": "MONGO_USER_PASSWORD"
 	},
 	"debug": {
 		"git": {

+ 8 - 4
backend/config/default.json

@@ -64,12 +64,12 @@
 		}
 	},
 	"cors": {
-		"origin": ["http://localhost"]
+		"origin": []
 	},
 	"mail": {
-		"from": "Musare <noreply@localhost>",
+		"enabled": false,
+		"from": "",
 		"smtp": {
-			"enabled": false,
 			"host": "smtp.mailgun.org",
 			"port": 587,
 			"auth": {
@@ -84,7 +84,11 @@
 		"password": "PASSWORD"
 	},
 	"mongo": {
-		"url": "mongodb://musare:OTHER_PASSWORD_HERE@mongo:27017/musare"
+		"user": "musare",
+		"password": "OTHER_PASSWORD_HERE",
+		"host": "mongo",
+		"port": 27017,
+		"database": "musare"
 	},
 	"blacklistedCommunityStationNames": ["musare"],
 	"featuredPlaylists": [],

+ 31 - 0
backend/config/template.json

@@ -0,0 +1,31 @@
+{
+	"migration": false,
+	"secret": "CHANGE_ME",
+	"url": {
+		"host": "my.domain",
+		"secure": true
+	},
+	"apis": {
+		"youtube": {
+			"key": "CHANGE_ME"
+		},
+		"discogs": {
+			"enabled": true,
+			"client": "CHANGE_ME",
+			"secret": "CHANGE_ME"
+		}
+	},
+	"mail": {
+		"enabled": true,
+		"smtp": {
+			"host": "smtp.eu.mailgun.org",
+			"port": 587,
+			"auth": {
+				"user": "CHANGE_ME",
+				"pass": "CHANGE_ME"
+			},
+			"secure": true
+		}
+	},
+	"configVersion": 12
+}

+ 15 - 22
backend/logic/app.js

@@ -57,7 +57,11 @@ class _AppModule extends CoreClass {
 				})
 				.catch(console.error);
 
-			const corsOptions = { ...config.get("cors"), credentials: true };
+			const appUrl = `${config.get("url.secure") ? "https" : "http"}://${config.get("url.host")}`;
+
+			const corsOptions = JSON.parse(JSON.stringify(config.get("cors")));
+			corsOptions.origin.push(appUrl);
+			corsOptions.credentials = true;
 
 			app.use(cors(corsOptions));
 			app.options("*", cors(corsOptions));
@@ -67,11 +71,7 @@ class _AppModule extends CoreClass {
 			 * @param {string} err - custom error message
 			 */
 			function redirectOnErr(res, err) {
-				res.redirect(
-					`${config.get("url.secure") ? "https" : "http"}://${config.get(
-						"url.host"
-					)}?err=${encodeURIComponent(err)}`
-				);
+				res.redirect(`${appUrl}?err=${encodeURIComponent(err)}`);
 			}
 
 			if (config.get("apis.github.enabled")) {
@@ -84,7 +84,10 @@ class _AppModule extends CoreClass {
 					null
 				);
 
-				const redirectUri = `${config.get("apis.github.redirect_uri")}`;
+				const redirectUri =
+					config.get("apis.github.redirect_uri").length > 0
+						? config.get("apis.github.redirect_uri")
+						: `${appUrl}/backend/auth/github/authorize/callback`;
 
 				app.get("/auth/github/authorize", async (req, res) => {
 					if (this.getStatus() !== "READY") {
@@ -98,7 +101,7 @@ class _AppModule extends CoreClass {
 
 					const params = [
 						`client_id=${config.get("apis.github.client")}`,
-						`redirect_uri=${config.get("apis.github.redirect_uri")}`,
+						`redirect_uri=${redirectUri}`,
 						`scope=user:email`
 					].join("&");
 					return res.redirect(`https://github.com/login/oauth/authorize?${params}`);
@@ -116,7 +119,7 @@ class _AppModule extends CoreClass {
 
 					const params = [
 						`client_id=${config.get("apis.github.client")}`,
-						`redirect_uri=${config.get("apis.github.redirect_uri")}`,
+						`redirect_uri=${redirectUri}`,
 						`scope=user:email`,
 						`state=${req.cookies[SIDname]}`
 					].join("&");
@@ -226,11 +229,7 @@ class _AppModule extends CoreClass {
 													value: { userId: user._id }
 												});
 
-												res.redirect(
-													`${config.get("url.secure") ? "https" : "http"}://${config.get(
-														"url.host"
-													)}/settings?tab=security`
-												);
+												res.redirect(`${appUrl}/settings?tab=security`);
 											}
 										],
 										next
@@ -447,9 +446,7 @@ class _AppModule extends CoreClass {
 										`User "${userId}" successfully authorized with GitHub.`
 									);
 
-									res.redirect(
-										`${config.get("url.secure") ? "https" : "http"}://${config.get("url.host")}/`
-									);
+									res.redirect(appUrl);
 								})
 								.catch(err => redirectOnErr(res, err.message));
 						}
@@ -512,11 +509,7 @@ class _AppModule extends CoreClass {
 
 						this.log("INFO", "VERIFY_EMAIL", `Successfully verified email.`);
 
-						return res.redirect(
-							`${config.get("url.secure") ? "https" : "http"}://${config.get(
-								"url.host"
-							)}?toast=Thank you for verifying your email`
-						);
+						return res.redirect(`${appUrl}?toast=Thank you for verifying your email`);
 					}
 				);
 			});

+ 2 - 9
backend/logic/cache/index.js

@@ -43,14 +43,10 @@ class _CacheModule extends CoreClass {
 		};
 
 		return new Promise((resolve, reject) => {
-			this.url = config.get("redis").url;
-			this.password = config.get("redis").password;
-
 			this.log("INFO", "Connecting...");
 
 			this.client = redis.createClient({
-				url: this.url,
-				password: this.password,
+				...config.get("redis"),
 				reconnectStrategy: retries => {
 					if (this.getStatus() !== "LOCKDOWN") {
 						if (this.getStatus() !== "RECONNECTING") this.setStatus("RECONNECTING");
@@ -388,10 +384,7 @@ class _CacheModule extends CoreClass {
 
 			if (subs[payload.channel] === undefined) {
 				subs[payload.channel] = {
-					client: redis.createClient({
-						url: CacheModule.url,
-						password: CacheModule.password
-					}),
+					client: redis.createClient(config.get("redis")),
 					cbs: []
 				};
 				subs[payload.channel].client.connect().then(() => {

+ 2 - 2
backend/logic/db/index.js

@@ -61,10 +61,10 @@ class _DBModule extends CoreClass {
 			this.schemas = {};
 			this.models = {};
 
-			const mongoUrl = config.get("mongo").url;
+			const { user, password, host, port, database } = config.get("mongo");
 
 			mongoose
-				.connect(mongoUrl, {
+				.connect(`mongodb://${user}:${password}@${host}:${port}/${database}`, {
 					useNewUrlParser: true,
 					useUnifiedTopology: true
 				})

+ 8 - 11
backend/logic/mail/index.js

@@ -32,18 +32,9 @@ class _MailModule extends CoreClass {
 			dataRequest: await importSchema("dataRequest")
 		};
 
-		this.enabled = config.get("mail.smtp.enabled");
+		this.enabled = config.get("mail.enabled");
 
-		if (this.enabled)
-			this.transporter = nodemailer.createTransport({
-				host: config.get("mail.smtp.host"),
-				port: config.get("mail.smtp.port"),
-				secure: config.get("mail.smtp.secure"),
-				auth: {
-					user: config.get("mail.smtp.auth.user"),
-					pass: config.get("mail.smtp.auth.pass")
-				}
-			});
+		if (this.enabled) this.transporter = nodemailer.createTransport(config.get("mail.smtp"));
 
 		return new Promise(resolve => {
 			resolve();
@@ -60,6 +51,12 @@ class _MailModule extends CoreClass {
 	SEND_MAIL(payload) {
 		return new Promise((resolve, reject) => {
 			if (MailModule.enabled) {
+				const { data } = payload;
+				if (!data.from)
+					data.from =
+						config.get("mail.from").length > 0
+							? config.get("mail.from")
+							: `${config.get("sitename")} <noreply@${config.get("url.host")}>`;
 				MailModule.transporter
 					.sendMail(payload.data)
 					.then(info => {

+ 0 - 1
backend/logic/mail/schemas/dataRequest.js

@@ -12,7 +12,6 @@ import mail from "../index";
  */
 export default (to, userId, type, cb) => {
 	const data = {
-		from: config.get("mail.from"),
 		to,
 		subject: `Data Request - ${type}`,
 		html: `

+ 0 - 2
backend/logic/mail/schemas/passwordRequest.js

@@ -1,4 +1,3 @@
-import config from "config";
 import mail from "../index";
 
 /**
@@ -11,7 +10,6 @@ import mail from "../index";
  */
 export default (to, username, code, cb) => {
 	const data = {
-		from: config.get("mail.from"),
 		to,
 		subject: "Password request",
 		html: `

+ 0 - 2
backend/logic/mail/schemas/resetPasswordRequest.js

@@ -1,4 +1,3 @@
-import config from "config";
 import mail from "../index";
 
 /**
@@ -11,7 +10,6 @@ import mail from "../index";
  */
 export default (to, username, code, cb) => {
 	const data = {
-		from: config.get("mail.from"),
 		to,
 		subject: "Password reset request",
 		html: `

+ 0 - 1
backend/logic/mail/schemas/verifyEmail.js

@@ -12,7 +12,6 @@ import mail from "../index";
 export default (to, username, code, cb) => {
 	const url = `${config.get("url.secure") ? "https" : "http"}://${config.get("url.host")}/backend`;
 	const data = {
-		from: config.get("mail.from"),
 		to,
 		subject: "Please verify your email",
 		html: `

+ 2 - 2
backend/logic/migration/index.js

@@ -33,10 +33,10 @@ class _MigrationModule extends CoreClass {
 		return new Promise((resolve, reject) => {
 			this.models = {};
 
-			const mongoUrl = config.get("mongo").url;
+			const { user, password, host, port, database } = config.get("mongo");
 
 			mongoose
-				.connect(mongoUrl, {
+				.connect(`mongodb://${user}:${password}@${host}:${port}/${database}`, {
 					useNewUrlParser: true,
 					useUnifiedTopology: true
 				})

+ 1 - 5
backend/logic/notifications.js

@@ -24,12 +24,8 @@ class _NotificationsModule extends CoreClass {
 	 */
 	initialize() {
 		return new Promise((resolve, reject) => {
-			const url = (this.url = config.get("redis").url);
-			const password = (this.password = config.get("redis").password);
-
 			this.pub = redis.createClient({
-				url,
-				password,
+				...config.get("redis"),
 				reconnectStrategy: retries => {
 					if (this.getStatus() !== "LOCKDOWN") {
 						if (this.getStatus() !== "RECONNECTING") this.setStatus("RECONNECTING");

+ 3 - 0
docker-compose.yml

@@ -20,6 +20,9 @@ services:
       - MUSARE_DEBUG_GIT_BRANCH=${MUSARE_DEBUG_GIT_BRANCH:-true}
       - MUSARE_DEBUG_GIT_LATEST_COMMIT=${MUSARE_DEBUG_GIT_LATEST_COMMIT:-true}
       - MUSARE_DEBUG_GIT_LATEST_COMMIT_SHORT=${MUSARE_DEBUG_GIT_LATEST_COMMIT_SHORT:-true}
+      - MONGO_USER_USERNAME=${MONGO_USER_USERNAME}
+      - MONGO_USER_PASSWORD=${MONGO_USER_PASSWORD}
+      - REDIS_PASSWORD=${REDIS_PASSWORD}
     links:
       - mongo
       - redis

+ 10 - 7
frontend/src/App.vue

@@ -39,9 +39,9 @@ const broadcastChannel = ref({
 	user_login: null,
 	nightmode: null
 });
-const christmas = ref(false);
 const disconnectedMessage = ref();
 
+const { christmas } = storeToRefs(configStore);
 const { loggedIn, banned } = storeToRefs(userAuthStore);
 const { nightmode, activityWatch } = storeToRefs(userPreferencesStore);
 const {
@@ -80,6 +80,10 @@ const enableChristmasMode = () => {
 	document.getElementsByTagName("html")[0].classList.add("christmas-mode");
 };
 
+const disableChristmasMode = () => {
+	document.getElementsByTagName("html")[0].classList.remove("christmas-mode");
+};
+
 watch(socketConnected, connected => {
 	if (!connected && !userAuthStore.banned) disconnectedMessage.value.show();
 	else disconnectedMessage.value.hide();
@@ -95,6 +99,10 @@ watch(activityWatch, enabled => {
 	if (enabled) aw.enable();
 	else aw.disable();
 });
+watch(christmas, enabled => {
+	if (enabled) enableChristmasMode();
+	else disableChristmasMode();
+});
 
 onMounted(async () => {
 	window
@@ -237,15 +245,10 @@ onMounted(async () => {
 				configStore.githubAuthentication &&
 				localStorage.getItem("github_redirect")
 			) {
-				router.push(localStorage.getItem("github_redirect") as string);
+				router.push(localStorage.getItem("github_redirect"));
 				localStorage.removeItem("github_redirect");
 			}
 		});
-
-		if (configStore.christmas) {
-			christmas.value = true;
-			enableChristmasMode();
-		}
 	}, true);
 
 	socket.onDisconnect(() => {

+ 2 - 2
frontend/src/main.ts

@@ -347,6 +347,8 @@ createSocket().then(async socket => {
 			email,
 			userId
 		});
+
+		if (configStore.experimental.media_session) ms.init();
 	});
 
 	socket.on("keep.event:user.banned", res =>
@@ -403,7 +405,5 @@ createSocket().then(async socket => {
 		});
 	});
 
-	if (configStore.experimental.media_session) ms.init();
-
 	app.mount("#root");
 });

+ 1 - 1
frontend/src/stores/config.ts

@@ -24,7 +24,7 @@ export const useConfigStore = defineStore("config", {
 		};
 	} => ({
 		cookie: "musareSID",
-		sitename: "Musare",
+		sitename: MUSARE_SITENAME,
 		recaptcha: {
 			enabled: false,
 			key: ""

+ 1 - 0
frontend/src/types/vite-env.d.ts

@@ -0,0 +1 @@
+declare const MUSARE_SITENAME: string;

+ 3 - 0
frontend/vite.config.js

@@ -161,6 +161,9 @@ export default {
 	},
 	define: {
 		__VUE_PROD_DEVTOOLS__: process.env.FRONTEND_PROD_DEVTOOLS === "true",
+		MUSARE_SITENAME: JSON.stringify(
+			process.env.MUSARE_SITENAME ?? "Musare"
+		),
 		MUSARE_VERSION: JSON.stringify(debug.version),
 		MUSARE_GIT_REMOTE: JSON.stringify(debug.git.remote),
 		MUSARE_GIT_REMOTE_URL: JSON.stringify(debug.git.remoteUrl),