~cadence/Frames

65f1231b2197634e2c15a72cc14013e80ddc6c04 — Cadence Ember 6 months ago db2b160
Find an actually working login token
1 files changed, 19 insertions(+), 8 deletions(-)

M utils/auth.js
M utils/auth.js => utils/auth.js +19 -8
@@ 40,12 40,6 @@ class User {
	}

	async verify() {
		const id = db.prepare("SELECT id FROM RecentAuths WHERE token = ? AND time > ?").pluck().get(this.row.access_token, Date.now() - recentTimeout)
		if (id) {
			this.id = id
			return
		}

		const account = await this.client.verifyAccountCredentials()
		this.id = account.data.id
		const prepared = {


@@ 54,6 48,7 @@ class User {
			id: this.id
		}
		db.prepare("REPLACE INTO RecentAuths (token, time, id) VALUES (@token, @time, @id)").run(prepared)
		return account
	}

	static fromCookie(cookie) {


@@ 85,12 80,28 @@ async function doCookieAuth(req) {
	return viewer
}

async function cycleWorkingToken(handle) {
	let ok = false
	while (!ok) {
		const user = User.fromHandle(handle)
		ok = await user.verify().then(account => {
			return true
		}).catch(e => {
			if (e.response.status === 401) {
				db.prepare("DELETE FROM Users WHERE access_token = ?").run(user.row.access_token)
			}
			return false
		})
	}
}

async function doAuth(req, handle) {
	const framer = User.fromHandle(handle)
	User.fromHandle(handle)

	const viewer = await doCookieAuth(req)

	await framer.verify()
	await cycleWorkingToken(handle)
	const framer = User.fromHandle(handle)

	// Same user?
	if (framer.row.handle === viewer.row.handle) {