Skip to content

Firefly III: a personal finances manager

9.8 KB
Raw Blame
/*
 * oauth.js
 * Copyright (c) 2026 [email protected]
 *
 * This file is part of Firefly III (https://github.com/firefly-iii).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

import "../../boot/bootstrap.js";
import sidebar from "../../pages/shared/sidebar.js";
import dates from "../shared/dates.js";
import i18next from "i18next";
import { api } from "../../boot/axios";
import { Modal } from "bootstrap";
import Alpine from "@alpinejs/csp";
import formatDate from "../../util/format-date.js";

let index = function () {
    return {
        clients: [],
        i18next: null,

        clientSecret: null,

        createForm: {
            errors: [],
            name: "",
            redirect_uris: "",
            confidential: true,
        },

        editForm: {
            errors: [],
            name: "",
            redirect_uris: "",
        },

        accessToken: null,

        tokens: [],
        scopes: [],

        form: {
            name: "",
            scopes: [],
            errors: [],
        },
        // showCreateTokenForm

        init() {
            this.i18next = i18next;
            this.getClients();
            this.getTokens();
            document.getElementById("modal-create-token").addEventListener("shown.bs.modal", () => {
                document.getElementById("create-token-name").focus();
            });
            document.getElementById("modal-create-client").addEventListener("shown.bs.modal", () => {
                document.getElementById("create-client-name").focus();
            });
            document.getElementById("modal-client-secret").addEventListener("shown.bs.modal", () => {
                setTimeout(() => {
                    document.getElementById("secret_box").focus();
                }, 100);
            });

            document.getElementById("modal-edit-client").addEventListener("shown.bs.modal", () => {
                document.getElementById("edit-client-name").focus();
            });
            const textBox = document.getElementById("secret_box");
            textBox.onfocus = function () {
                textBox.select();

                // Work around Chrome's little problem
                textBox.onmouseup = function () {
                    // Prevent further mouseup intervention
                    textBox.onmouseup = null;
                    return false;
                };
            };

            const tokenBox = document.getElementById("token_box");
            tokenBox.onfocus = function () {
                tokenBox.select();

                // Work around Chrome's little problem
                tokenBox.onmouseup = function () {
                    // Prevent further mouseup intervention
                    tokenBox.onmouseup = null;
                    return false;
                };
            };
        },
        /**
         * Get all of the personal access tokens for the user.
         */
        getTokens() {
            const locale = window.store.get("locale");
            // console.log("getTokens()");
            api.get("./oauth/personal-access-tokens").then((response) => {
                // console.log(response.data);
                for (let i = 0; i < response.data.length; i++) {
                    if (Object.hasOwn(response.data, i)) {
                        let token = response.data[i];
                        console.log(i18next.t("config.date_time_fns", { lng: locale }));
                        token.expires_at = formatDate(
                            new Date(token.expires_at),
                            i18next.t("config.date_time_fns", { lng: locale }),
                            locale,
                        );
                        this.tokens.push(token);
                    }
                }
            });
        },

        /**
         * Show the form for creating new tokens.
         */
        showCreateTokenForm() {
            new Modal(document.getElementById("modal-create-token"), {}).show();
        },

        /**
         * Create a new personal access token.
         */
        storePat() {
            this.accessToken = null;
            this.form.errors = [];

            api.post("./oauth/personal-access-tokens", this.form)
                .then((response) => {
                    //console.log("Successful POST new token, reset form content.",);
                    this.form.name = "";
                    this.form.scopes = [];
                    this.form.errors = [];

                    Modal.getInstance(document.getElementById("modal-create-token")).hide();

                    this.getTokens();
                    this.showAccessToken(response.data.accessToken);
                })
                .catch((error) => {
                    console.warn("Bad POST new token, show error.", error);
                    this.form.errors = [];
                    if (typeof error.response.data === "object") {
                        for (let i in error.response.data.errors) {
                            if (Object.hasOwn(error.response.data.errors, i)) {
                                this.form.errors.push(error.response.data.errors[i]);
                            }
                        }
                    } else {
                        this.form.errors = ["Something went wrong. Please try again."];
                    }
                });
        },

        /**
         * Show the given access token to the user.
         */
        showAccessToken(accessToken) {
            this.accessToken = accessToken;
            new Modal(document.getElementById("modal-access-token"), {}).show();
        },
        getClients() {
            api.get("./oauth/clients").then((response) => {
                // console.log(response.data);
                this.clients = response.data;
            });
        },

        /**
         * Persist the client to storage using the given form.
         */
        persistClient(method, uri, form, modal) {
            form.errors = [];

            api[method](uri, form)
                .then((response) => {
                    this.getClients();

                    form.name = "";
                    form.redirect_uris = "";
                    form.errors = [];
                    Modal.getInstance(document.getElementById(modal)).hide();

                    if (response.data.plainSecret) {
                        this.showClientSecret(response.data.plainSecret);
                    }
                })
                .catch((error) => {
                    console.error(error);
                    if (typeof error.response === "object" && typeof error.response.data === "object") {
                        for (const value of Object.entries(error.response.data.errors)) {
                            form.errors.push(value);
                        }
                    } else {
                        form.errors = ["Something went wrong. Please try again."];
                    }
                });
        },
        /**
         * Revoke the given token.
         */
        revoke(token) {
            api.delete("./oauth/personal-access-tokens/" + token.id).then(() => {
                this.getTokens();
            });
        },

        /**
         * Show the given client secret to the user.
         */
        showClientSecret(clientSecret) {
            this.clientSecret = clientSecret;
            new Modal(document.getElementById("modal-client-secret"), {}).show();
        },
        regenerateSecret(client) {
            api.post("./oauth/clients/regenerate/" + client.id).then((response) => {
                this.clientSecret = response.data.plainSecret;
                Modal.getInstance(document.getElementById("modal-client-secret"), {}).show();
            });
        },

        /**
         * Destroy the given client.
         */
        destroy(client) {
            api.delete("./oauth/clients/" + client.id).then(() => {
                this.getClients();
            });
        },
        /**
         * Create a new OAuth client for the user.
         */
        store() {
            this.persistClient("post", "./oauth/clients", this.createForm, "modal-create-client");
        },
        /**
         * Edit the given client.
         */
        edit(client) {
            this.editForm.id = client.id;
            this.editForm.name = client.name;
            this.editForm.redirect_uris = client.redirect_uris.join(",");

            new Modal(document.getElementById("modal-edit-client"), {}).show();
        },

        /**
         * Update the client being edited.
         */
        update() {
            this.persistClient("put", "./oauth/clients/" + this.editForm.id, this.editForm, "modal-edit-client");
        },
    };
};

const comps = {
    index,
    sidebar,
    dates,
};

function loadPage(comps) {
    // console.log("loadPage");
    Object.keys(comps).forEach((comp) => {
        let data = comps[comp]();
        Alpine.data(comp, () => data);
        // console.log(comp);
    });
    Alpine.start();
}

// wait for load until bootstrapped event is received.
document.addEventListener("firefly-iii-bootstrapped", () => {
    console.log("Loaded through event listener.");
    loadPage(comps);
});
// or is bootstrapped before event is triggered.
if (window.bootstrapped) {
    console.log("Loaded through window variable.");
    loadPage(comps);
}