2017-07-19 04:48:28 +00:00
|
|
|
// @flow
|
|
|
|
import type {BaseModel} from './index';
|
|
|
|
|
2017-03-23 22:10:42 +00:00
|
|
|
import * as db from '../common/database';
|
|
|
|
|
2017-07-19 04:48:28 +00:00
|
|
|
type BaseOAuth2Token = {
|
|
|
|
refreshToken: string,
|
|
|
|
accessToken: string,
|
|
|
|
expiresAt: number | null, // Should be Date.now() if valid
|
|
|
|
|
|
|
|
// Error handling
|
|
|
|
error: string,
|
|
|
|
errorDescription: string,
|
|
|
|
errorUri: string
|
|
|
|
};
|
|
|
|
|
|
|
|
export type OAuth2Token = BaseModel & BaseOAuth2Token;
|
|
|
|
|
2017-03-23 22:10:42 +00:00
|
|
|
export const name = 'OAuth 2.0 Token';
|
|
|
|
export const type = 'OAuth2Token';
|
|
|
|
export const prefix = 'oa2';
|
|
|
|
export const canDuplicate = false;
|
|
|
|
|
2017-07-19 04:48:28 +00:00
|
|
|
export function init (): BaseOAuth2Token {
|
2017-03-23 22:10:42 +00:00
|
|
|
return {
|
2017-07-19 04:48:28 +00:00
|
|
|
refreshToken: '',
|
|
|
|
accessToken: '',
|
2017-03-23 22:10:42 +00:00
|
|
|
expiresAt: null, // Should be Date.now() if valid
|
|
|
|
|
|
|
|
// Error handling
|
2017-07-19 04:48:28 +00:00
|
|
|
error: '',
|
|
|
|
errorDescription: '',
|
|
|
|
errorUri: ''
|
2017-03-23 22:10:42 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2017-07-19 04:48:28 +00:00
|
|
|
export function migrate<T> (doc: T): T {
|
2017-03-23 22:10:42 +00:00
|
|
|
return doc;
|
|
|
|
}
|
|
|
|
|
2017-07-19 04:48:28 +00:00
|
|
|
export function create (patch: Object = {}): Promise<OAuth2Token> {
|
2017-03-23 22:10:42 +00:00
|
|
|
if (!patch.parentId) {
|
2017-07-19 04:48:28 +00:00
|
|
|
throw new Error(`New OAuth2Token missing \`parentId\` ${JSON.stringify(patch)}`);
|
2017-03-23 22:10:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return db.docCreate(type, patch);
|
|
|
|
}
|
|
|
|
|
2017-07-19 04:48:28 +00:00
|
|
|
export function update (token: OAuth2Token, patch: Object): Promise<OAuth2Token> {
|
2017-03-23 22:10:42 +00:00
|
|
|
return db.docUpdate(token, patch);
|
|
|
|
}
|
|
|
|
|
2017-07-19 04:48:28 +00:00
|
|
|
export function remove (token: OAuth2Token): Promise<void> {
|
2017-03-23 22:10:42 +00:00
|
|
|
return db.remove(token);
|
|
|
|
}
|
|
|
|
|
2017-07-19 04:48:28 +00:00
|
|
|
export function getByParentId (parentId: string): Promise<OAuth2Token | null> {
|
2017-03-23 22:10:42 +00:00
|
|
|
return db.getWhere(type, {parentId});
|
|
|
|
}
|
|
|
|
|
2017-07-19 04:48:28 +00:00
|
|
|
export async function getOrCreateByParentId (parentId: string): Promise<OAuth2Token> {
|
2017-03-23 22:10:42 +00:00
|
|
|
let token = await db.getWhere(type, {parentId});
|
|
|
|
|
|
|
|
if (!token) {
|
2017-07-19 04:48:28 +00:00
|
|
|
token = await create({parentId});
|
2017-03-23 22:10:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return token;
|
|
|
|
}
|
|
|
|
|
2017-07-19 04:48:28 +00:00
|
|
|
export function all (): Promise<Array<OAuth2Token>> {
|
2017-03-23 22:10:42 +00:00
|
|
|
return db.all(type);
|
|
|
|
}
|