summaryrefslogtreecommitdiff
path: root/src/models/auth-session.ts
blob: 428c707470d1bd812024ca9828d110a9f293ca7d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import * as mongo from 'mongodb';
import * as deepcopy from 'deepcopy';
import db from '../db/mongodb';
import isObjectId from '../misc/is-objectid';
import { pack as packApp } from './app';

const AuthSession = db.get<IAuthSession>('authSessions');
export default AuthSession;

export interface IAuthSession {
	_id: mongo.ObjectID;
	createdAt: Date;
	appId: mongo.ObjectID;
	userId: mongo.ObjectID;
	token: string;
}

/**
 * Pack an auth session for API response
 *
 * @param {any} session
 * @param {any} me?
 * @return {Promise<any>}
 */
export const pack = (
	session: any,
	me?: any
) => new Promise<any>(async (resolve, reject) => {
	let _session: any;

	// TODO: Populate session if it ID
	_session = deepcopy(session);

	// Me
	if (me && !isObjectId(me)) {
		if (typeof me === 'string') {
			me = new mongo.ObjectID(me);
		} else {
			me = me._id;
		}
	}

	delete _session._id;

	// Populate app
	_session.app = await packApp(_session.appId, me);

	resolve(_session);
});