UNPKG

@expressive-analytics/deep-thought-authentication

Version:

Typescript conversion of Deep Thought Authentication

76 lines (66 loc) 2.3 kB
import {DTStorage,DTStore,DTKeystore} from '@expressive-analytics/deep-thought-js' import {DTRequestor, DTVerifier, DTService, DTErr} from '@expressive-analytics/deep-thought-service' import {DTOAuthTokenModel} from './DTOAuthToken' export class DTOAuth2Verifier implements DTVerifier{ protected _db:DTStore protected access_token? protected provider?:DTService protected _token constructor(db?:DTStore){ if(db===undefined) this._db = DTStorage.defaultStore() as DTStore else this._db = db } verify(action: any, token?:DTOAuthTokenModel): boolean{ if(action=="actionAccessToken"){ //provide the access token const client_id = this.provider.params.stringParam("client_id") const client_secret = this.provider.params.stringParam("client_secret") const code = this.provider.params.stringParam("code") const redirect_uri = this.provider.params.stringParam("redirect_uri") const grant_type = this.provider.params.stringParam("grant_type") // should be "authorization code" // validate the client const api = this.lookupConsumer(client_id,client_secret) if(api){ const token = DTOAuthTokenModel.query(this._db.filter({ type: 0, token: code, status: 1 })) as DTOAuthTokenModel token.$set("consumer_id",api.$get("id")) token.updateToAccessToken(this._db) } this.provider.response.respond(`access_token=${token.$get["token"]}`) } return false } lookupConsumer(key,secret):DTRequestor{ try{ const api = DTRequestor.query(this._db.filter({consumer_key:key})) as DTRequestor if(api.$get("status")==0) this.provider.response.error(DTErr.OAUTH_CONSUMER_KEY_REFUSED) return api }catch(e){ console.log(e.message) } return undefined } token(){ try{ if(this._token===undefined){ this._token = DTKeystore.setShared(this.castToken(this._db.where(`token='${this.access_token}'`))) return this._token } }catch(e){ console.error("Could not find token: "+e.message) } } castToken(qb){ return DTOAuthTokenModel.query(qb) } userID(): () => number { const token = this.token() return token.$get("user_id") } db(){ return this._db } }