import constants from '../constants' ; import { imageDB } from '../image-db' ; import pubsub from '../pubsub' ; class User { id : string = '' ; name : string = '' ; imageURL : string = '' ; token : string = '' ; tokenExpiry : number = 0 ; } export const user = new User ( ) ; export async function resume ( ) { const storedToken = await imageDB . getMeta ( 'token' ) ; const storedExpiry = await imageDB . getMeta ( 'tokenExpiry' ) ; if ( storedToken && ( storedExpiry * 1000 ) > Date . now ( ) ) { return validate ( storedToken ) ; } } export function login ( ) { const url = new URL ( 'https://accounts.google.com/o/oauth2/v2/auth' ) ; url . searchParams . append ( 'client_id' , constants . CLIENT_ID ) ; url . searchParams . append ( 'redirect_uri' , `${ location . origin }/oauth` ) ; url . searchParams . append ( 'response_type' , 'token' ) ; url . searchParams . append ( 'scope' , 'profile https://www.googleapis.com/auth/drive' ) ; window . location . replace ( url . toString ( ) ) ; } export function logout ( ) { user . token = '' ; pubsub . publish ( { channel : 'logout' } ) ; imageDB . setMeta ( 'token' , '' ) ; imageDB . setMeta ( 'tokenExpiry' , 0 ) ; } export async function validate ( accessToken ) { if ( accessToken === '' ) { return ; } const response = await fetch ( `https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=${ accessToken }` ) ; if ( ! response . ok ) { return logout ( ) ; } const json = await response . json ( ) ; if ( json . aud === constants . CLIENT_ID ) { const profileResponse = await fetch ( `https://www.googleapis.com/plus/v1/people/me?access_token=${ accessToken }` ) ; const profile = await profileResponse . json ( ) ; user . id = profile . id ; user . name = profile . displayName ; user . imageURL = profile . image . url ; user . token = accessToken ; user . tokenExpiry = json . exp ; pubsub . publish ( { channel : 'login' } ) ; await imageDB . setMeta ( 'token' , accessToken ) ; await imageDB . setMeta ( 'tokenExpiry' , json . exp ) ; } }