|
| 1 | +/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 | + |
| 5 | +import { SessionToken } from 'fxa-shared/connected-services/models/SessionToken'; |
| 6 | +import { Email, SecurityEvent } from 'fxa-shared/db/models/auth'; |
| 7 | +import { EVENT_NAMES } from 'fxa-shared/db/models/auth/security-event'; |
| 8 | + |
| 9 | +export type GetTokensFn<T> = (uid: string) => Promise<T[]>; |
| 10 | +export type ActiveConditionFn = ( |
| 11 | + uid: string, |
| 12 | + activeByDateTimestamp: number |
| 13 | +) => Promise<boolean> | Promise<Promise<boolean>>; |
| 14 | +export type NoTimestampActiveConditionFn = ( |
| 15 | + uid: string |
| 16 | +) => Promise<boolean> | Promise<Promise<boolean>>; |
| 17 | + |
| 18 | +// this includes the agumented last access time from redis |
| 19 | +export const hasActiveSessionToken = async ( |
| 20 | + tokensFn: GetTokensFn<SessionToken>, |
| 21 | + uid: string, |
| 22 | + activeByDateTimestamp: number |
| 23 | +) => { |
| 24 | + const sessionTokens = await tokensFn(uid); |
| 25 | + return sessionTokens.some( |
| 26 | + (token) => |
| 27 | + token.lastAccessTime && token.lastAccessTime >= activeByDateTimestamp |
| 28 | + ); |
| 29 | +}; |
| 30 | +export const hasActiveRefreshToken = async ( |
| 31 | + tokensFn: GetTokensFn<{ lastUsedAt: number }>, |
| 32 | + uid: string, |
| 33 | + activeByDateTimestamp: number |
| 34 | +) => { |
| 35 | + const refreshTokens = await tokensFn(uid); |
| 36 | + return refreshTokens.some((t) => t.lastUsedAt >= activeByDateTimestamp); |
| 37 | +}; |
| 38 | +export const hasAccessToken = async ( |
| 39 | + tokensFn: GetTokensFn<{ lastUsedAt: number }>, |
| 40 | + uid: string |
| 41 | +) => { |
| 42 | + const accessTokens = await tokensFn(uid); |
| 43 | + return accessTokens.length > 0; |
| 44 | +}; |
| 45 | + |
| 46 | +export const emailVerificationQuery = (uid, activeByDateTimestamp) => |
| 47 | + Email.query() |
| 48 | + .select('uid') |
| 49 | + .where('uid', uid) |
| 50 | + .andWhere('verifiedAt', '>=', activeByDateTimestamp) |
| 51 | + .limit(1) |
| 52 | + .first(); |
| 53 | + |
| 54 | +export const securityEventsQuery = (uid, activeByDateTimestamp) => |
| 55 | + SecurityEvent.query() |
| 56 | + .select('uid') |
| 57 | + .where('uid', uid) |
| 58 | + .andWhere('createdAt', '>=', activeByDateTimestamp) |
| 59 | + .whereIn('nameId', [ |
| 60 | + EVENT_NAMES['account.login'], |
| 61 | + EVENT_NAMES['account.password_reset_success'], |
| 62 | + EVENT_NAMES['account.password_changed'], |
| 63 | + ]) |
| 64 | + .limit(1) |
| 65 | + .first(); |
0 commit comments