1
0
mirror of https://github.com/hrfee/jfa-go.git synced 2024-12-22 17:10:10 +00:00

userpage: add/edit discord

works identically to on the form, would like to eventually factor out
the discord/telegram/matrix verif stuff so it can be shared between the
two pages though.
This commit is contained in:
Harvey Tindall 2023-06-18 21:38:12 +01:00
parent 609039baeb
commit cf7983ca11
Signed by: hrfee
GPG Key ID: BBC65952848FB1A2
9 changed files with 246 additions and 19 deletions

View File

@ -207,7 +207,7 @@ func (app *appContext) confirmMyAction(gc *gin.Context, key string) {
// @Failure 500 {object} stringResponse // @Failure 500 {object} stringResponse
// @Router /my/email [post] // @Router /my/email [post]
// @Security Bearer // @Security Bearer
// @tags Users // @tags User Page
func (app *appContext) ModifyMyEmail(gc *gin.Context) { func (app *appContext) ModifyMyEmail(gc *gin.Context) {
var req ModifyMyEmailDTO var req ModifyMyEmailDTO
gc.BindJSON(&req) gc.BindJSON(&req)
@ -258,3 +258,79 @@ func (app *appContext) ModifyMyEmail(gc *gin.Context) {
app.confirmMyAction(gc, key) app.confirmMyAction(gc, key)
return return
} }
// @Summary Returns a 10-minute, one-use Discord server invite
// @Produce json
// @Success 200 {object} DiscordInviteDTO
// @Failure 400 {object} boolResponse
// @Failure 401 {object} boolResponse
// @Failure 500 {object} boolResponse
// @Param invCode path string true "invite Code"
// @Router /my/discord/invite [get]
// @tags User Page
func (app *appContext) MyDiscordServerInvite(gc *gin.Context) {
if app.discord.inviteChannelName == "" {
respondBool(400, false, gc)
return
}
invURL, iconURL := app.discord.NewTempInvite(10*60, 1)
if invURL == "" {
respondBool(500, false, gc)
return
}
gc.JSON(200, DiscordInviteDTO{invURL, iconURL})
}
// @Summary Returns a linking PIN for discord/telegram
// @Produce json
// @Success 200 {object} GetMyPINDTO
// @Failure 400 {object} stringResponse
// Param service path string true "discord/telegram"
// @Router /my/pin/{service} [get]
// @tags User Page
func (app *appContext) GetMyPIN(gc *gin.Context) {
service := gc.Param("service")
resp := GetMyPINDTO{}
switch service {
case "discord":
resp.PIN = app.discord.NewAuthToken()
break
case "telegram":
resp.PIN = app.telegram.NewAuthToken()
break
default:
respond(400, "invalid service", gc)
return
}
gc.JSON(200, resp)
}
// @Summary Returns true/false on whether or not your discord PIN was verified, and assigns the discord user to you.
// @Produce json
// @Success 200 {object} boolResponse
// @Failure 401 {object} boolResponse
// @Param pin path string true "PIN code to check"
// @Router /my/discord/verified/{pin} [get]
// @tags User Page
func (app *appContext) MyDiscordVerifiedInvite(gc *gin.Context) {
pin := gc.Param("pin")
dcUser, ok := app.discord.verifiedTokens[pin]
if !ok {
respondBool(200, false, gc)
return
}
if app.config.Section("discord").Key("require_unique").MustBool(false) {
for _, u := range app.storage.discord {
if app.discord.verifiedTokens[pin].ID == u.ID {
delete(app.discord.verifiedTokens, pin)
respondBool(400, false, gc)
return
}
}
}
dc := app.storage.discord
dc[gc.GetString("jfId")] = dcUser
app.storage.discord = dc
app.storage.storeDiscordUsers()
respondBool(200, true, gc)
}

View File

@ -4,14 +4,22 @@
<script> <script>
window.URLBase = "{{ .urlBase }}"; window.URLBase = "{{ .urlBase }}";
window.notificationsEnabled = {{ .notifications }}; window.notificationsEnabled = {{ .notifications }};
window.emailEnabled = {{ .emailEnabled }};
window.telegramEnabled = {{ .telegramEnabled }};
window.discordEnabled = {{ .discordEnabled }};
window.matrixEnabled = {{ .matrixEnabled }};
window.ombiEnabled = {{ .ombiEnabled }}; window.ombiEnabled = {{ .ombiEnabled }};
window.langFile = JSON.parse({{ .language }}); window.langFile = JSON.parse({{ .language }});
window.linkResetEnabled = {{ .linkResetEnabled }}; window.linkResetEnabled = {{ .linkResetEnabled }};
window.language = "{{ .langName }}"; window.language = "{{ .langName }}";
window.telegramEnabled = {{ .telegramEnabled }};
window.telegramRequired = {{ .telegramRequired }};
window.emailEnabled = {{ .emailEnabled }};
window.emailRequired = {{ .emailRequired }};
window.discordEnabled = {{ .discordEnabled }};
window.discordRequired = {{ .discordRequired }};
window.discordServerName = "{{ .discordServerName }}";
window.discordInviteLink = {{ .discordInviteLink }};
window.discordSendPINMessage = "{{ .discordSendPINMessage }}";
window.matrixEnabled = {{ .matrixEnabled }};
window.matrixRequired = {{ .matrixRequired }};
window.matrixUserID = "{{ .matrixUser }}";
</script> </script>
{{ template "header.html" . }} {{ template "header.html" . }}
<title>{{ .lang.Strings.pageTitle }}</title> <title>{{ .lang.Strings.pageTitle }}</title>
@ -33,6 +41,47 @@
</div> </div>
</div> </div>
</div> </div>
<div id="modal-discord" class="modal">
<div class="card relative mx-auto my-[10%] w-4/5 lg:w-1/3">
<span class="heading mb-4">{{ .strings.linkDiscord }}</span>
<p class="content mb-4"> {{ .discordSendPINMessage }}</p>
<h1 class="text-center text-2xl mb-2 pin"></h1>
<a id="discord-invite"></a>
<span class="button ~info @low full-width center mt-4" id="discord-waiting">{{ .strings.success }}</span>
</div>
</div>
<div id="modal-telegram" class="modal">
<div class="card relative mx-auto my-[10%] w-4/5 lg:w-1/3">
<span class="heading mb-4">{{ .strings.linkTelegram }}</span>
<p class="content mb-4">{{ .strings.sendPIN }}</p>
<p class="text-center text-2xl mb-2">{{ .telegramPIN }}</p>
<a class="subheading link-center" href="{{ .telegramURL }}" target="_blank">
<span class="shield ~info mr-4">
<span class="icon">
<i class="ri-telegram-line"></i>
</span>
</span>
&#64;{{ .telegramUsername }}
</a>
<span class="button ~info @low full-width center mt-4" id="telegram-waiting">{{ .strings.success }}</span>
</div>
</div>
<div id="modal-matrix" class="modal">
<div class="card relative mx-auto my-[10%] w-4/5 lg:w-1/3">
<span class="heading mb-4">{{ .strings.linkMatrix }}</span>
<p class="content mb-4"> {{ .strings.matrixEnterUser }}</p>
<input type="text" class="input ~neutral @high" placeholder="@user:riot.im" id="matrix-userid">
<div class="subheading link-center mt-4">
<span class="shield ~info mr-4">
<span class="icon">
<i class="ri-chat-3-line"></i>
</span>
</span>
{{ .matrixUser }}
</div>
<span class="button ~info @low full-width center mt-4" id="matrix-send">{{ .strings.submit }}</span>
</div>
</div>
<div id="notification-box"></div> <div id="notification-box"></div>
<div class="top-4 left-4 absolute"> <div class="top-4 left-4 absolute">
<span class="dropdown" tabindex="0" id="lang-dropdown"> <span class="dropdown" tabindex="0" id="lang-dropdown">

View File

@ -402,3 +402,7 @@ const (
UserEmailChange ConfirmationTarget = iota UserEmailChange ConfirmationTarget = iota
NoOp NoOp
) )
type GetMyPINDTO struct {
PIN string `json:"pin"`
}

View File

@ -231,6 +231,9 @@ func (app *appContext) loadRoutes(router *gin.Engine) {
user.POST(p+"/contact", app.SetMyContactMethods) user.POST(p+"/contact", app.SetMyContactMethods)
user.POST(p+"/logout", app.LogoutUser) user.POST(p+"/logout", app.LogoutUser)
user.POST(p+"/email", app.ModifyMyEmail) user.POST(p+"/email", app.ModifyMyEmail)
user.GET(p+"/discord/invite", app.MyDiscordServerInvite)
user.GET(p+"/pin/:service", app.GetMyPIN)
user.GET(p+"/discord/verified/:pin", app.MyDiscordVerifiedInvite)
} }
} }
} }

View File

@ -1,6 +1,6 @@
import { Modal } from "./modules/modal.js"; import { Modal } from "./modules/modal.js";
import { notificationBox, whichAnimationEvent } from "./modules/common.js"; import { notificationBox, whichAnimationEvent } from "./modules/common.js";
import { _get, _post, toggleLoader, addLoader, removeLoader, toDateString } from "./modules/common.js"; import { _get, _post, toggleLoader, addLoader, removeLoader, toDateString, DiscordInvite } from "./modules/common.js";
import { loadLangSelector } from "./modules/lang.js"; import { loadLangSelector } from "./modules/lang.js";
import { initValidator } from "./modules/validator.js"; import { initValidator } from "./modules/validator.js";
@ -91,11 +91,6 @@ if (window.telegramEnabled) {
}; };
} }
interface DiscordInvite {
invite: string;
icon: string;
}
var discordVerified = false; var discordVerified = false;
if (window.discordEnabled) { if (window.discordEnabled) {
window.discordModal = new Modal(document.getElementById("modal-discord"), window.discordRequired); window.discordModal = new Modal(document.getElementById("modal-discord"), window.discordRequired);

View File

@ -221,3 +221,8 @@ export function insertText(textarea: HTMLTextAreaElement, text: string) {
textarea.focus(); textarea.focus();
} }
} }
export interface DiscordInvite {
invite: string;
icon: string;
}

View File

@ -1,12 +1,20 @@
import { ThemeManager } from "./modules/theme.js"; import { ThemeManager } from "./modules/theme.js";
import { lang, LangFile, loadLangSelector } from "./modules/lang.js"; import { lang, LangFile, loadLangSelector } from "./modules/lang.js";
import { Modal } from "./modules/modal.js"; import { Modal } from "./modules/modal.js";
import { _get, _post, notificationBox, whichAnimationEvent, toDateString, toggleLoader } from "./modules/common.js"; import { _get, _post, notificationBox, whichAnimationEvent, toDateString, toggleLoader, DiscordInvite } from "./modules/common.js";
import { Login } from "./modules/login.js"; import { Login } from "./modules/login.js";
interface userWindow extends Window { interface userWindow extends Window {
jellyfinID: string; jellyfinID: string;
username: string; username: string;
emailRequired: boolean;
discordRequired: boolean;
telegramRequired: boolean;
matrixRequired: boolean;
discordServerName: string;
discordInviteLink: boolean;
matrixUserID: string;
discordSendPINMessage: string;
} }
declare var window: userWindow; declare var window: userWindow;
@ -26,6 +34,9 @@ window.modals = {} as Modals;
(() => { (() => {
window.modals.login = new Modal(document.getElementById("modal-login"), true); window.modals.login = new Modal(document.getElementById("modal-login"), true);
window.modals.email = new Modal(document.getElementById("modal-email"), false); window.modals.email = new Modal(document.getElementById("modal-email"), false);
window.modals.discord = new Modal(document.getElementById("modal-discord"), false);
window.modals.telegram = new Modal(document.getElementById("modal-telegram"), false);
window.modals.matrix = new Modal(document.getElementById("modal-matrix"), false);
})(); })();
window.notifications = new notificationBox(document.getElementById('notification-box') as HTMLDivElement, 5); window.notifications = new notificationBox(document.getElementById('notification-box') as HTMLDivElement, 5);
@ -87,8 +98,8 @@ class ContactMethods {
<span class="ml-2 font-bold">${(details.value == "") ? window.lang.strings("notSet") : details.value}</span> <span class="ml-2 font-bold">${(details.value == "") ? window.lang.strings("notSet") : details.value}</span>
</div> </div>
<div class="flex items-center"> <div class="flex items-center">
<button class="user-contact-enabled-disabled button ~neutral" ${details.value =="" ? "disabled" : ""}> <button class="user-contact-enabled-disabled button ~neutral" ${details.value == "" ? "disabled" : ""}>
<input type="checkbox" class="mr-2"> <input type="checkbox" class="mr-2" ${details.value == "" ? "disabled" : ""}>
<span>${window.lang.strings("enabled")}</span> <span>${window.lang.strings("enabled")}</span>
</button> </button>
`; `;
@ -239,7 +250,6 @@ var expiryCard = new ExpiryCard(statusCard);
var contactMethodList = new ContactMethods(contactCard); var contactMethodList = new ContactMethods(contactCard);
const addEditEmail = (add: boolean): void => { const addEditEmail = (add: boolean): void => {
console.log("call");
const heading = window.modals.email.modal.querySelector(".heading"); const heading = window.modals.email.modal.querySelector(".heading");
heading.innerHTML = (add ? window.lang.strings("addContactMethod") : window.lang.strings("editContactMethod")) + `<span class="modal-close">&times;</span>`; heading.innerHTML = (add ? window.lang.strings("addContactMethod") : window.lang.strings("editContactMethod")) + `<span class="modal-close">&times;</span>`;
const input = document.getElementById("modal-email-input") as HTMLInputElement; const input = document.getElementById("modal-email-input") as HTMLInputElement;
@ -268,6 +278,70 @@ const addEditEmail = (add: boolean): void => {
window.modals.email.show(); window.modals.email.show();
} }
let discordModalClosed = false;
let discordPIN = "";
const addEditDiscord = (add: boolean): void => {
if (window.discordInviteLink) {
_get("/my/discord/invite", null, (req: XMLHttpRequest) => {
if (req.readyState == 4) {
if (req.status != 200) return;
const inv = req.response as DiscordInvite;
const link = document.getElementById("discord-invite") as HTMLAnchorElement;
link.href = inv.invite;
link.target = "_blank";
link.innerHTML = `<span class="img-circle lg mr-4"><img class="img-circle" src="${inv.icon}" width="64" height="64"></span>${window.discordServerName}`;
}
});
}
_get("/my/pin/discord", null, (req: XMLHttpRequest) => {
if (req.readyState == 4 && req.status == 200) {
discordPIN = req.response["pin"];
window.modals.discord.modal.querySelector(".pin").textContent = discordPIN;
}
});
const waiting = document.getElementById("discord-waiting") as HTMLSpanElement;
toggleLoader(waiting);
window.modals.discord.show();
discordModalClosed = false;
window.modals.discord.onclose = () => {
discordModalClosed = true;
toggleLoader(waiting);
}
const checkVerified = () => {
if (discordPIN == "") {
setTimeout(checkVerified, 1500);
}
if (discordModalClosed) return;
_get("/my/discord/verified/" + discordPIN, null, (req: XMLHttpRequest) => {
if (req.readyState != 4) return;
if (req.status == 401) {
window.modals.discord.close();
window.notifications.customError("invalidCodeError", window.lang.notif("errorInvalidCode"));
return;
} else if (req.status == 400) {
window.modals.discord.close();
window.notifications.customError("accountLinkedError", window.lang.notif("errorAccountLinked"));
} else if (req.status == 200) {
if (req.response["success"] as boolean) {
waiting.classList.add("~positive");
waiting.classList.remove("~info");
window.notifications.customPositive("discordVerified", "", window.lang.notif("verified"));
setTimeout(() => {
window.modals.discord.close;
window.location.reload();
}, 2000);
} else if (!discordModalClosed) {
setTimeout(checkVerified, 1500);
}
}
});
};
checkVerified();
};
document.addEventListener("details-reload", () => { document.addEventListener("details-reload", () => {
_get("/my/details", null, (req: XMLHttpRequest) => { _get("/my/details", null, (req: XMLHttpRequest) => {
if (req.readyState == 4) { if (req.readyState == 4) {
@ -294,7 +368,7 @@ document.addEventListener("details-reload", () => {
const contactMethods: { name: string, icon: string, f: (add: boolean) => void }[] = [ const contactMethods: { name: string, icon: string, f: (add: boolean) => void }[] = [
{name: "email", icon: `<i class="ri-mail-fill ri-lg"></i>`, f: addEditEmail}, {name: "email", icon: `<i class="ri-mail-fill ri-lg"></i>`, f: addEditEmail},
{name: "discord", icon: `<i class="ri-discord-fill ri-lg"></i>`, f: null}, {name: "discord", icon: `<i class="ri-discord-fill ri-lg"></i>`, f: addEditDiscord},
{name: "telegram", icon: `<i class="ri-telegram-fill ri-lg"></i>`, f: null}, {name: "telegram", icon: `<i class="ri-telegram-fill ri-lg"></i>`, f: null},
{name: "matrix", icon: `<span class="font-bold">[m]</span>`, f: null} {name: "matrix", icon: `<span class="font-bold">[m]</span>`, f: null}
]; ];

View File

@ -165,12 +165,13 @@ func (app *appContext) MyUserPage(gc *gin.Context) {
emailEnabled, _ := app.config.Section("invite_emails").Key("enabled").Bool() emailEnabled, _ := app.config.Section("invite_emails").Key("enabled").Bool()
notificationsEnabled, _ := app.config.Section("notifications").Key("enabled").Bool() notificationsEnabled, _ := app.config.Section("notifications").Key("enabled").Bool()
ombiEnabled := app.config.Section("ombi").Key("enabled").MustBool(false) ombiEnabled := app.config.Section("ombi").Key("enabled").MustBool(false)
gcHTML(gc, http.StatusOK, "user.html", gin.H{ data := gin.H{
"urlBase": app.getURLBase(gc), "urlBase": app.getURLBase(gc),
"cssClass": app.cssClass, "cssClass": app.cssClass,
"cssVersion": cssVersion, "cssVersion": cssVersion,
"contactMessage": app.config.Section("ui").Key("contact_message").String(), "contactMessage": app.config.Section("ui").Key("contact_message").String(),
"emailEnabled": emailEnabled, "emailEnabled": emailEnabled,
"emailRequired": app.config.Section("email").Key("required").MustBool(false),
"telegramEnabled": telegramEnabled, "telegramEnabled": telegramEnabled,
"discordEnabled": discordEnabled, "discordEnabled": discordEnabled,
"matrixEnabled": matrixEnabled, "matrixEnabled": matrixEnabled,
@ -182,7 +183,27 @@ func (app *appContext) MyUserPage(gc *gin.Context) {
"validationStrings": app.storage.lang.User[lang].ValidationStrings, "validationStrings": app.storage.lang.User[lang].ValidationStrings,
"language": app.storage.lang.User[lang].JSON, "language": app.storage.lang.User[lang].JSON,
"langName": lang, "langName": lang,
}) }
if telegramEnabled {
data["telegramUser"] = app.telegram.username
data["telegramURL"] = app.telegram.link
data["telegramRequired"] = app.config.Section("telegram").Key("required").MustBool(false)
}
if matrixEnabled {
data["matrixRequired"] = app.config.Section("matrix").Key("required").MustBool(false)
data["matrixUser"] = app.matrix.userID
}
if discordEnabled {
data["discordUsername"] = app.discord.username
data["discordRequired"] = app.config.Section("discord").Key("required").MustBool(false)
data["discordSendPINMessage"] = template.HTML(app.storage.lang.User[lang].Strings.template("sendPINDiscord", tmpl{
"command": `<span class="text-black dark:text-white font-mono">/` + app.config.Section("discord").Key("start_command").MustString("start") + `</span>`,
"server_channel": app.discord.serverChannelName,
}))
data["discordServerName"] = app.discord.serverName
data["discordInviteLink"] = app.discord.inviteChannelName != ""
}
gcHTML(gc, http.StatusOK, "user.html", data)
} }
func (app *appContext) ResetPassword(gc *gin.Context) { func (app *appContext) ResetPassword(gc *gin.Context) {