|
| 1 | +import * as oauthServer from "oauth2-server"; |
| 2 | +import * as winston from "winston"; |
| 3 | +import * as express from "express"; |
| 4 | +export class OAuthProvider { |
| 5 | + private _logger: winston.Logger; |
| 6 | + private app: express.Express; |
| 7 | + private clients = [{ clientId: 'thom', clientSecret: 'nightworld', redirectUris: [''] }]; |
| 8 | + private tokens = []; |
| 9 | + private users = [{ id: '123', username: 'thomseddon', password: 'nightworld' }]; |
| 10 | + static configure(logger: winston.Logger, app: express.Express): OAuthProvider { |
| 11 | + var instance = new OAuthProvider(); |
| 12 | + instance._logger = logger; |
| 13 | + instance.app = app; |
| 14 | + |
| 15 | + (app as any).oauth = oauthServer({ |
| 16 | + model: instance |
| 17 | + }); |
| 18 | + app.post('/oauth/token', (app as any).oauth.token()); |
| 19 | + return instance; |
| 20 | + } |
| 21 | + public getAccessToken(bearerToken) { |
| 22 | + var tokens = this.tokens.filter(function (token) { |
| 23 | + return token.accessToken === bearerToken; |
| 24 | + }); |
| 25 | + return tokens.length ? tokens[0] : false; |
| 26 | + } |
| 27 | + public getRefreshToken(bearerToken) { |
| 28 | + var tokens = this.tokens.filter(function (token) { |
| 29 | + return token.refreshToken === bearerToken; |
| 30 | + }); |
| 31 | + return tokens.length ? tokens[0] : false; |
| 32 | + } |
| 33 | + public getClient(clientId, clientSecret) { |
| 34 | + var clients = this.clients.filter(function (client) { |
| 35 | + return client.clientId === clientId && client.clientSecret === clientSecret; |
| 36 | + }); |
| 37 | + return clients.length ? clients[0] : false; |
| 38 | + } |
| 39 | + public saveToken(token, client, user) { |
| 40 | + this.tokens.push({ |
| 41 | + accessToken: token.accessToken, |
| 42 | + accessTokenExpiresAt: token.accessTokenExpiresAt, |
| 43 | + clientId: client.clientId, |
| 44 | + refreshToken: token.refreshToken, |
| 45 | + refreshTokenExpiresAt: token.refreshTokenExpiresAt, |
| 46 | + userId: user.id |
| 47 | + }); |
| 48 | + } |
| 49 | + public getUser(username, password) { |
| 50 | + var users = this.users.filter(function (user) { |
| 51 | + return user.username === username && user.password === password; |
| 52 | + }); |
| 53 | + return users.length ? users[0] : false; |
| 54 | + }; |
| 55 | +} |
0 commit comments