import { LeanDocument , FilterQuery , UpdateQuery } from "mongoose" ; import config from "config" ; import { get } from "lodash" ; import { UserDocument } from "../model/user.model" ; import Session , { SessionDocument } from "../model/session.model" ; import { sign , decode } from "../utils/jwt.utils" ; import { findUser } from "./user.service" ; export async function createSession ( userId , userAgent ) { const session = await Session . create ( { user : userId , userAgent } ) ; return session . toJSON ( ) ; } export function createAccessToken ( { user , session , } ) { const accessToken = sign ( { ... user , session : session . _id } , { expiresIn : config . get ( "accessTokenTtl" ) } ) ; return accessToken ; } export async function reIssueAccessToken ( { refreshToken , } ) { const { decoded } = decode ( refreshToken ) ; if ( ! decoded || ! get ( decoded , "_id" ) ) return false ; const session = await Session . findById ( get ( decoded , "_id" ) ) ; if ( ! session || ! session ?. valid ) return false ; const user = await findUser ( { _id : session . user } ) ; if ( ! user ) return false ; const accessToken = createAccessToken ( { user , session } ) ; return accessToken ; } export async function updateSession ( query , update ) { return Session . updateOne ( query , update ) ; } export async function findSessions ( query ) { return Session . find ( query ) . lean ( ) ; }