|
| 1 | +import { Controller } from "@hotwired/stimulus"; |
| 2 | + |
| 3 | +// Manages Devise session timeout warnings and keepalive behavior. |
| 4 | +export default class extends Controller { |
| 5 | + static values = { |
| 6 | + expiresAt: Number, |
| 7 | + duration: Number, |
| 8 | + warningOffset: Number, |
| 9 | + keepaliveUrl: String, |
| 10 | + warningMessage: String, |
| 11 | + staySignedInLabel: String, |
| 12 | + errorMessage: String, |
| 13 | + expiredMessage: String, |
| 14 | + }; |
| 15 | + |
| 16 | + connect() { |
| 17 | + this.flashElement = this.element; |
| 18 | + if (!this.flashElement) return; |
| 19 | + this.requestInFlight = false; |
| 20 | + this.cacheMenuElements(); |
| 21 | + this.toggleMenus(this.hasExpiresAtValue); |
| 22 | + |
| 23 | + this.resetTimers(); |
| 24 | + } |
| 25 | + |
| 26 | + disconnect() { |
| 27 | + this.clearTimers(); |
| 28 | + this.hideWarning(); |
| 29 | + } |
| 30 | + |
| 31 | + resetTimers() { |
| 32 | + this.clearTimers(); |
| 33 | + |
| 34 | + if (!this.hasExpiresAtValue || !this.hasWarningOffsetValue) return; |
| 35 | + |
| 36 | + const warningAt = (this.expiresAtValue - this.warningOffsetValue) * 1000; |
| 37 | + const expirationAt = this.expiresAtValue * 1000; |
| 38 | + const millisUntilWarning = warningAt - Date.now(); |
| 39 | + const millisUntilExpiration = expirationAt - Date.now(); |
| 40 | + |
| 41 | + if (millisUntilWarning <= 0) { |
| 42 | + this.showWarning(); |
| 43 | + } else { |
| 44 | + this.warningTimer = setTimeout(() => this.showWarning(), millisUntilWarning); |
| 45 | + } |
| 46 | + |
| 47 | + if (millisUntilExpiration <= 0) { |
| 48 | + this.handleExpiration(); |
| 49 | + } else { |
| 50 | + this.expirationTimer = setTimeout(() => this.handleExpiration(), millisUntilExpiration); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + resetSession(event) { |
| 55 | + event.preventDefault(); |
| 56 | + if (!this.hasKeepaliveUrlValue || this.requestInFlight) return; |
| 57 | + this.requestInFlight = true; |
| 58 | + |
| 59 | + fetch(this.keepaliveUrlValue, { |
| 60 | + method: "POST", |
| 61 | + headers: { |
| 62 | + "X-CSRF-Token": this.csrfToken, |
| 63 | + "Accept": "application/json", |
| 64 | + "Content-Type": "application/json", |
| 65 | + }, |
| 66 | + credentials: "same-origin", |
| 67 | + }) |
| 68 | + .then((response) => { |
| 69 | + if (!response.ok) throw new Error("Keepalive request failed"); |
| 70 | + return response.json().catch(() => ({})); |
| 71 | + }) |
| 72 | + .then((data) => { |
| 73 | + if (data.expires_at) { |
| 74 | + this.expiresAtValue = data.expires_at; |
| 75 | + } else if (this.hasDurationValue) { |
| 76 | + this.expiresAtValue = Math.floor(Date.now() / 1000) + this.durationValue; |
| 77 | + } |
| 78 | + this.hideWarning(); |
| 79 | + this.resetTimers(); |
| 80 | + this.toggleMenus(true); |
| 81 | + }) |
| 82 | + .catch(() => this.showError()) |
| 83 | + .finally(() => { |
| 84 | + this.requestInFlight = false; |
| 85 | + }); |
| 86 | + } |
| 87 | + |
| 88 | + showWarning() { |
| 89 | + if (!this.flashElement || this.warningVisible) return; |
| 90 | + |
| 91 | + const remainingMinutes = this.minutesFromSeconds(this.warningOffsetValue); |
| 92 | + const messageTemplate = this.valueOrDefault("warningMessage", "Your session will expire in %{minutes} minutes."); |
| 93 | + const messageText = messageTemplate.replace("%{minutes}", remainingMinutes); |
| 94 | + const staySignedInLabel = this.valueOrDefault("staySignedInLabel", "Stay signed in"); |
| 95 | + |
| 96 | + const alert = document.createElement("div"); |
| 97 | + alert.className = "alert alert-warning alert-dismissible fade show mt-3"; |
| 98 | + alert.setAttribute("role", "alert"); |
| 99 | + alert.innerHTML = ` |
| 100 | + <div class="d-flex flex-column flex-sm-row align-items-sm-center justify-content-between gap-2"> |
| 101 | + <span>${messageText}</span> |
| 102 | + <div class="d-flex gap-2"> |
| 103 | + <button type="button" class="btn btn-sm btn-primary" data-action="click->session-timeout#resetSession"> |
| 104 | + ${staySignedInLabel} |
| 105 | + </button> |
| 106 | + </div> |
| 107 | + </div> |
| 108 | + `; |
| 109 | + |
| 110 | + this.flashElement.prepend(alert); |
| 111 | + this.warningElement = alert; |
| 112 | + this.warningVisible = true; |
| 113 | + } |
| 114 | + |
| 115 | + hideWarning() { |
| 116 | + if (!this.warningVisible || !this.warningElement) return; |
| 117 | + this.warningElement.remove(); |
| 118 | + this.warningElement = null; |
| 119 | + this.warningVisible = false; |
| 120 | + } |
| 121 | + |
| 122 | + showError() { |
| 123 | + if (!this.flashElement) return; |
| 124 | + this.hideWarning(); |
| 125 | + this.showAlert({ |
| 126 | + level: "danger", |
| 127 | + message: this.valueOrDefault("errorMessage", "We couldn't extend your session. Please save your work and sign in again."), |
| 128 | + }); |
| 129 | + } |
| 130 | + |
| 131 | + clearTimers() { |
| 132 | + if (this.warningTimer) { |
| 133 | + clearTimeout(this.warningTimer); |
| 134 | + this.warningTimer = null; |
| 135 | + } |
| 136 | + if (this.expirationTimer) { |
| 137 | + clearTimeout(this.expirationTimer); |
| 138 | + this.expirationTimer = null; |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + get csrfToken() { |
| 143 | + const element = document.querySelector("meta[name='csrf-token']"); |
| 144 | + return element && element.getAttribute("content"); |
| 145 | + } |
| 146 | + |
| 147 | + handleExpiration() { |
| 148 | + this.clearTimers(); |
| 149 | + this.hideWarning(); |
| 150 | + if (!this.flashElement) return; |
| 151 | + this.toggleMenus(false); |
| 152 | + |
| 153 | + this.showAlert({ |
| 154 | + level: "danger", |
| 155 | + message: this.valueOrDefault("expiredMessage", "Your session has expired. Please sign in again to continue."), |
| 156 | + trackWarning: true, |
| 157 | + }); |
| 158 | + } |
| 159 | + |
| 160 | + showAlert({ level, message, trackWarning = false }) { |
| 161 | + const alert = document.createElement("div"); |
| 162 | + alert.className = `alert alert-${level} alert-dismissible fade show mt-3`; |
| 163 | + alert.setAttribute("role", "alert"); |
| 164 | + alert.innerHTML = ` |
| 165 | + <span>${message}</span> |
| 166 | + <button type="button" class="btn-close" data-action="click->session-timeout#hideAlert" aria-label="Close"></button> |
| 167 | + `; |
| 168 | + |
| 169 | + this.flashElement.prepend(alert); |
| 170 | + |
| 171 | + if (trackWarning) { |
| 172 | + this.warningElement = alert; |
| 173 | + this.warningVisible = true; |
| 174 | + } |
| 175 | + } |
| 176 | + |
| 177 | + hideAlert(event) { |
| 178 | + event.preventDefault(); |
| 179 | + const alert = event.target.closest(".alert"); |
| 180 | + if (!alert) return; |
| 181 | + if (alert === this.warningElement) { |
| 182 | + this.warningElement = null; |
| 183 | + this.warningVisible = false; |
| 184 | + } |
| 185 | + alert.remove(); |
| 186 | + } |
| 187 | + |
| 188 | + minutesFromSeconds(seconds) { |
| 189 | + const minutes = Math.ceil(seconds / 60); |
| 190 | + return Math.max(minutes, 1); |
| 191 | + } |
| 192 | + |
| 193 | + valueOrDefault(name, fallback = "") { |
| 194 | + const hasKey = this[`has${this.capitalize(name)}Value`]; |
| 195 | + if (hasKey) { |
| 196 | + return this[`${name}Value`]; |
| 197 | + } |
| 198 | + return fallback; |
| 199 | + } |
| 200 | + |
| 201 | + capitalize(value) { |
| 202 | + return value.charAt(0).toUpperCase() + value.slice(1); |
| 203 | + } |
| 204 | + |
| 205 | + cacheMenuElements() { |
| 206 | + this.signedInMenus = Array.from(document.querySelectorAll("[data-session-timeout-signed-in]")); |
| 207 | + this.signedOutMenus = Array.from(document.querySelectorAll("[data-session-timeout-signed-out]")); |
| 208 | + } |
| 209 | + |
| 210 | + toggleMenus(isSignedIn) { |
| 211 | + if (!this.signedInMenus || !this.signedOutMenus) { |
| 212 | + this.cacheMenuElements(); |
| 213 | + } |
| 214 | + |
| 215 | + this.signedInMenus?.forEach((element) => this.setVisibility(element, isSignedIn)); |
| 216 | + this.signedOutMenus?.forEach((element) => this.setVisibility(element, !isSignedIn)); |
| 217 | + } |
| 218 | + |
| 219 | + setVisibility(element, shouldShow) { |
| 220 | + if (!element) return; |
| 221 | + element.classList.toggle("d-none", !shouldShow); |
| 222 | + } |
| 223 | +} |
0 commit comments