backend/auth: redo OAuth flow and "finish" DM auth flow

This commit is contained in:
41666 2019-03-19 20:25:38 -05:00
parent 1b8d90b24b
commit ff67bc3f1b
4 changed files with 167 additions and 12 deletions

View file

@ -3,6 +3,8 @@ import Service from './Service'
import nanoid from 'nanoid'
import moniker from 'moniker'
import type { AppContext } from '../Roleypoly'
import type { Context } from 'koa'
// import type { UserPartial } from './discord'
// import type { Models } from '../models'
export type DMChallenge = {
@ -12,6 +14,12 @@ export type DMChallenge = {
issuedAt: Date
}
export type AuthTokens = {
access_token: string,
refresh_token: string,
expires_in: string
}
export default class AuthService extends Service {
M: { AuthChallenge: any }
monikerGen = moniker.generator([ moniker.adjective, moniker.adjective, moniker.noun ], { glue: ' ' })
@ -20,6 +28,26 @@ export default class AuthService extends Service {
this.M = ctx.M
}
async isLoggedIn (ctx: Context, { refresh = false }: { refresh: boolean } = {}) {
const { userId, expiresAt, authType } = ctx.session
if (userId == null) {
return false
}
if (expiresAt < Date.now()) {
if (refresh && authType === 'oauth') {
const tokens = await this.ctx.discord.refreshOAuth(ctx.session)
this.injectSessionFromOAuth(ctx, tokens, userId)
return true
}
ctx.session = null // reset session as well
return false
}
return true
}
async createDMChallenge (userId: string): Promise<DMChallenge> {
const out: DMChallenge = {
userId,
@ -48,4 +76,27 @@ export default class AuthService extends Service {
return challenge
}
deleteDMChallenge (input: DMChallenge) {
return this.M.AuthChallenge.destroy({ where: { magic: input.magic } })
}
injectSessionFromChallenge (ctx: Context, chall: DMChallenge) {
ctx.session = {
userId: chall.userId,
authType: 'dm',
expiresAt: Date.now() + 1000 * 60 * 60 * 24
}
}
injectSessionFromOAuth (ctx: Context, tokens: AuthTokens, userId: string) {
const { expires_in: expiresIn, access_token: accessToken, refresh_token: refreshToken } = tokens
ctx.session = {
userId,
authType: 'oauth',
expiresAt: Date.now() + expiresIn,
accessToken,
refreshToken
}
}
}