275 lines
9.7 KiB
JavaScript
275 lines
9.7 KiB
JavaScript
/* DevBox · 账号与积分:登录/注册、积分扣费、CDK 兑换 */
|
|
(function () {
|
|
'use strict'
|
|
const { el, toast } = DB
|
|
|
|
const state = {
|
|
user: null,
|
|
uses: 0,
|
|
ready: false,
|
|
listeners: []
|
|
}
|
|
|
|
async function api(path, body, options = {}) {
|
|
const init = {
|
|
method: body === undefined ? 'GET' : 'POST',
|
|
headers: {},
|
|
credentials: 'same-origin'
|
|
}
|
|
if (body !== undefined) {
|
|
init.headers['content-type'] = 'application/json'
|
|
init.body = JSON.stringify(body)
|
|
}
|
|
let res
|
|
try {
|
|
res = await fetch(path, init)
|
|
} catch (e) {
|
|
throw Object.assign(new Error('连不上服务端,确认 DevBox 服务在跑'), { code: 'offline' })
|
|
}
|
|
const text = await res.text()
|
|
let data = {}
|
|
try { data = text ? JSON.parse(text) : {} } catch { data = { ok: false, error: text.slice(0, 200) } }
|
|
if (!res.ok || data.ok === false) {
|
|
const error = data.error || `HTTP ${res.status}`
|
|
const err = Object.assign(new Error(error), { status: res.status, data })
|
|
throw err
|
|
}
|
|
return data
|
|
}
|
|
|
|
function setUser(user) {
|
|
state.user = user || null
|
|
paintWho()
|
|
for (const fn of state.listeners) { try { fn(state.user) } catch {} }
|
|
}
|
|
|
|
function onChange(fn) {
|
|
state.listeners.push(fn)
|
|
return () => { state.listeners = state.listeners.filter((x) => x !== fn) }
|
|
}
|
|
|
|
/* ---------------- 顶栏账号区 ---------------- */
|
|
function paintWho() {
|
|
const u = state.user
|
|
const wrap = document.getElementById('who')
|
|
const creditNum = document.getElementById('creditNum')
|
|
const userName = document.getElementById('userName')
|
|
const adminBtn = document.getElementById('adminBtn')
|
|
if (!wrap) return
|
|
wrap.hidden = !u
|
|
document.body.classList.toggle('signed-in', Boolean(u))
|
|
if (!u) return
|
|
creditNum.textContent = String(u.credits)
|
|
creditNum.classList.toggle('low', u.credits <= 0)
|
|
userName.textContent = u.username
|
|
adminBtn.hidden = !u.admin
|
|
const dot = document.getElementById('userDot')
|
|
if (dot) dot.textContent = u.admin ? '管理员' : ''
|
|
}
|
|
|
|
/* ---------------- 登录 / 注册 ---------------- */
|
|
let authMode = 'login'
|
|
|
|
function showAuth(message) {
|
|
const auth = document.getElementById('auth')
|
|
auth.hidden = false
|
|
document.body.classList.add('authing')
|
|
if (message) setAuthMsg(message, 'bad')
|
|
setTimeout(() => document.getElementById('authUser')?.focus(), 60)
|
|
}
|
|
|
|
function hideAuth() {
|
|
document.getElementById('auth').hidden = true
|
|
document.body.classList.remove('authing')
|
|
}
|
|
|
|
function setAuthMsg(text, tone) {
|
|
const box = document.getElementById('authMsg')
|
|
box.textContent = text || ''
|
|
box.className = 'auth-msg' + (tone ? ' ' + tone : '')
|
|
}
|
|
|
|
function setMode(mode) {
|
|
authMode = mode
|
|
const isReg = mode === 'register'
|
|
document.getElementById('authSubmit').textContent = isReg ? '注册并进入' : '登录'
|
|
document.getElementById('authPass2Wrap').hidden = !isReg
|
|
document.getElementById('authHint').textContent = isReg
|
|
? '注册就送 100 积分,每次用一个工具扣 1 分。'
|
|
: '第一次来?点上面的「注册」,第一个注册的账号会自动成为管理员。'
|
|
for (const b of document.querySelectorAll('.auth-tab')) b.classList.toggle('active', b.dataset.mode === mode)
|
|
setAuthMsg('')
|
|
}
|
|
|
|
async function submitAuth(event) {
|
|
event.preventDefault()
|
|
const username = document.getElementById('authUser').value.trim()
|
|
const password = document.getElementById('authPass').value
|
|
const password2 = document.getElementById('authPass2')?.value || ''
|
|
const btn = document.getElementById('authSubmit')
|
|
if (!username || !password) return setAuthMsg('用户名和密码都要填', 'bad')
|
|
if (authMode === 'register' && password !== password2) return setAuthMsg('两次输入的密码不一样', 'bad')
|
|
btn.disabled = true
|
|
btn.textContent = '请稍等…'
|
|
try {
|
|
const path = authMode === 'register' ? '/api/register' : '/api/login'
|
|
const out = await api(path, { username, password })
|
|
setUser(out.user)
|
|
hideAuth()
|
|
toast(authMode === 'register' ? `欢迎,${out.user.username}!送了你 100 积分` : `欢迎回来,${out.user.username}`)
|
|
document.getElementById('authForm').reset()
|
|
if (out.first) toast('你是第一个账号,自动成为管理员')
|
|
} catch (e) {
|
|
setAuthMsg(e.message, 'bad')
|
|
} finally {
|
|
btn.disabled = false
|
|
setMode(authMode)
|
|
}
|
|
}
|
|
|
|
/* ---------------- 积分 ---------------- */
|
|
async function charge(toolId) {
|
|
const out = await api('/api/consume', { tool: toolId })
|
|
setUser(out.user)
|
|
return out
|
|
}
|
|
|
|
/* ---------------- 弹层:兑换 / 账号 ---------------- */
|
|
function openSheet(html) {
|
|
const sheet = document.getElementById('sheet')
|
|
document.getElementById('sheetBody').innerHTML = html
|
|
sheet.hidden = false
|
|
}
|
|
function closeSheet() {
|
|
document.getElementById('sheet').hidden = true
|
|
}
|
|
|
|
function openRedeem() {
|
|
openSheet(`
|
|
<h2>兑换积分</h2>
|
|
<p class="muted">输入管理员给你的 CDK,一个码只能用一次。</p>
|
|
<label class="field"><span>CDK</span>
|
|
<input id="redeemCode" placeholder="ABCD-EFGH-JKLM-NPQR" autocomplete="off" spellcheck="false" style="text-transform:uppercase;font-family:var(--mono)" />
|
|
</label>
|
|
<div class="auth-msg" id="redeemMsg"></div>
|
|
<div class="row">
|
|
<button class="btn primary" id="redeemGo">兑换</button>
|
|
<button class="btn" data-close>取消</button>
|
|
</div>`)
|
|
const input = document.getElementById('redeemCode')
|
|
const msg = document.getElementById('redeemMsg')
|
|
const go = async () => {
|
|
const code = input.value.trim()
|
|
if (!code) { msg.textContent = '先填 CDK'; msg.className = 'auth-msg bad'; return }
|
|
document.getElementById('redeemGo').disabled = true
|
|
try {
|
|
const out = await api('/api/redeem', { code })
|
|
setUser(out.user)
|
|
msg.className = 'auth-msg good'
|
|
msg.textContent = `兑换成功,+${out.credits} 积分`
|
|
setTimeout(() => { closeSheet(); DB.reroute && DB.reroute() }, 600)
|
|
} catch (e) {
|
|
msg.className = 'auth-msg bad'
|
|
msg.textContent = e.message
|
|
} finally {
|
|
document.getElementById('redeemGo').disabled = false
|
|
}
|
|
}
|
|
document.getElementById('redeemGo').onclick = go
|
|
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') go() })
|
|
setTimeout(() => input.focus(), 50)
|
|
}
|
|
|
|
function openAccount() {
|
|
const u = state.user
|
|
openSheet(`
|
|
<h2>账号</h2>
|
|
<p class="muted">${u.username}${u.admin ? ' · 管理员' : ''} · 剩余 <b>${u.credits}</b> 积分 · 已用 ${state.uses} 次</p>
|
|
<div class="row">
|
|
<button class="btn primary" id="accRedeem">兑换积分</button>
|
|
${u.admin ? '<button class="btn" id="accAdmin">管理后台</button>' : ''}
|
|
</div>
|
|
<details style="margin-top:14px">
|
|
<summary class="muted">改密码</summary>
|
|
<label class="field"><span>当前密码</span><input id="pwCur" type="password" /></label>
|
|
<label class="field"><span>新密码(至少 6 位)</span><input id="pwNew" type="password" /></label>
|
|
<div class="auth-msg" id="pwMsg"></div>
|
|
<button class="btn" id="pwGo">保存新密码</button>
|
|
</details>
|
|
<div class="row" style="margin-top:16px">
|
|
<button class="btn danger" id="accLogout">退出登录</button>
|
|
</div>`)
|
|
document.getElementById('accRedeem').onclick = openRedeem
|
|
const adminBtn = document.getElementById('accAdmin')
|
|
if (adminBtn) adminBtn.onclick = () => { closeSheet(); location.hash = '#/admin' }
|
|
document.getElementById('accLogout').onclick = async () => {
|
|
try { await api('/api/logout', {}) } catch {}
|
|
setUser(null)
|
|
closeSheet()
|
|
showAuth('已退出,重新登录一下')
|
|
location.hash = ''
|
|
}
|
|
document.getElementById('pwGo').onclick = async () => {
|
|
const msg = document.getElementById('pwMsg')
|
|
try {
|
|
await api('/api/me/password', {
|
|
current: document.getElementById('pwCur').value,
|
|
next: document.getElementById('pwNew').value
|
|
})
|
|
msg.className = 'auth-msg good'
|
|
msg.textContent = '改好了,其它设备已经退出'
|
|
} catch (e) {
|
|
msg.className = 'auth-msg bad'
|
|
msg.textContent = e.message
|
|
}
|
|
}
|
|
}
|
|
|
|
/* ---------------- 启动 ---------------- */
|
|
async function ready() {
|
|
if (state.ready) return state.user
|
|
try {
|
|
const out = await api('/api/me')
|
|
state.uses = out.uses || 0
|
|
setUser(out.user)
|
|
} catch (e) {
|
|
if (e.status === 401) {
|
|
showAuth()
|
|
} else {
|
|
showAuth(e.message)
|
|
}
|
|
}
|
|
state.ready = true
|
|
return state.user
|
|
}
|
|
|
|
function mount() {
|
|
document.getElementById('authForm').addEventListener('submit', submitAuth)
|
|
for (const b of document.querySelectorAll('.auth-tab')) b.addEventListener('click', () => setMode(b.dataset.mode))
|
|
document.getElementById('creditBtn').addEventListener('click', openRedeem)
|
|
document.getElementById('userBtn').addEventListener('click', openAccount)
|
|
document.getElementById('adminBtn').addEventListener('click', () => { location.hash = '#/admin' })
|
|
document.getElementById('sheet').addEventListener('click', (e) => {
|
|
if (e.target.id === 'sheet' || e.target.hasAttribute('data-close')) closeSheet()
|
|
})
|
|
document.addEventListener('keydown', (e) => {
|
|
if (e.key === 'Escape') closeSheet()
|
|
})
|
|
}
|
|
|
|
DB.api = api
|
|
DB.auth = {
|
|
state,
|
|
ready,
|
|
mount,
|
|
setUser,
|
|
onChange,
|
|
charge,
|
|
showAuth,
|
|
openRedeem,
|
|
openAccount,
|
|
get user() { return state.user },
|
|
get uses() { return state.uses }
|
|
}
|
|
})()
|