Try to fix video duplication
[oweals/peertube.git] / server / lib / oauth-model.ts
1 import * as Bluebird from 'bluebird'
2 import { AccessDeniedError } from 'oauth2-server'
3 import { logger } from '../helpers/logger'
4 import { UserModel } from '../models/account/user'
5 import { OAuthClientModel } from '../models/oauth/oauth-client'
6 import { OAuthTokenModel } from '../models/oauth/oauth-token'
7 import { LRU_CACHE } from '../initializers/constants'
8 import { Transaction } from 'sequelize'
9 import { CONFIG } from '../initializers/config'
10 import * as LRUCache from 'lru-cache'
11
12 type TokenInfo = { accessToken: string, refreshToken: string, accessTokenExpiresAt: Date, refreshTokenExpiresAt: Date }
13
14 const accessTokenCache = new LRUCache<string, OAuthTokenModel>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE })
15 const userHavingToken = new LRUCache<number, string>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE })
16
17 // ---------------------------------------------------------------------------
18
19 function deleteUserToken (userId: number, t?: Transaction) {
20   clearCacheByUserId(userId)
21
22   return OAuthTokenModel.deleteUserToken(userId, t)
23 }
24
25 function clearCacheByUserId (userId: number) {
26   const token = userHavingToken.get(userId)
27
28   if (token !== undefined) {
29     accessTokenCache.del(token)
30     userHavingToken.del(userId)
31   }
32 }
33
34 function clearCacheByToken (token: string) {
35   const tokenModel = accessTokenCache.get(token)
36
37   if (tokenModel !== undefined) {
38     userHavingToken.del(tokenModel.userId)
39     accessTokenCache.del(token)
40   }
41 }
42
43 function getAccessToken (bearerToken: string) {
44   logger.debug('Getting access token (bearerToken: ' + bearerToken + ').')
45
46   if (!bearerToken) return Bluebird.resolve(undefined)
47
48   if (accessTokenCache.has(bearerToken)) return Bluebird.resolve(accessTokenCache.get(bearerToken))
49
50   return OAuthTokenModel.getByTokenAndPopulateUser(bearerToken)
51     .then(tokenModel => {
52       if (tokenModel) {
53         accessTokenCache.set(bearerToken, tokenModel)
54         userHavingToken.set(tokenModel.userId, tokenModel.accessToken)
55       }
56
57       return tokenModel
58     })
59 }
60
61 function getClient (clientId: string, clientSecret: string) {
62   logger.debug('Getting Client (clientId: ' + clientId + ', clientSecret: ' + clientSecret + ').')
63
64   return OAuthClientModel.getByIdAndSecret(clientId, clientSecret)
65 }
66
67 function getRefreshToken (refreshToken: string) {
68   logger.debug('Getting RefreshToken (refreshToken: ' + refreshToken + ').')
69
70   return OAuthTokenModel.getByRefreshTokenAndPopulateClient(refreshToken)
71 }
72
73 async function getUser (usernameOrEmail: string, password: string) {
74   logger.debug('Getting User (username/email: ' + usernameOrEmail + ', password: ******).')
75
76   const user = await UserModel.loadByUsernameOrEmail(usernameOrEmail)
77   if (!user) return null
78
79   const passwordMatch = await user.isPasswordMatch(password)
80   if (passwordMatch === false) return null
81
82   if (user.blocked) throw new AccessDeniedError('User is blocked.')
83
84   if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) {
85     throw new AccessDeniedError('User email is not verified.')
86   }
87
88   return user
89 }
90
91 async function revokeToken (tokenInfo: TokenInfo) {
92   const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken)
93   if (token) {
94     clearCacheByToken(token.accessToken)
95
96     token.destroy()
97          .catch(err => logger.error('Cannot destroy token when revoking token.', { err }))
98   }
99
100   /*
101     * Thanks to https://github.com/manjeshpv/node-oauth2-server-implementation/blob/master/components/oauth/mongo-models.js
102     * "As per the discussion we need set older date
103     * revokeToken will expected return a boolean in future version
104     * https://github.com/oauthjs/node-oauth2-server/pull/274
105     * https://github.com/oauthjs/node-oauth2-server/issues/290"
106   */
107   const expiredToken = token
108   expiredToken.refreshTokenExpiresAt = new Date('2015-05-28T06:59:53.000Z')
109
110   return expiredToken
111 }
112
113 async function saveToken (token: TokenInfo, client: OAuthClientModel, user: UserModel) {
114   logger.debug('Saving token ' + token.accessToken + ' for client ' + client.id + ' and user ' + user.id + '.')
115
116   const tokenToCreate = {
117     accessToken: token.accessToken,
118     accessTokenExpiresAt: token.accessTokenExpiresAt,
119     refreshToken: token.refreshToken,
120     refreshTokenExpiresAt: token.refreshTokenExpiresAt,
121     oAuthClientId: client.id,
122     userId: user.id
123   }
124
125   const tokenCreated = await OAuthTokenModel.create(tokenToCreate)
126   return Object.assign(tokenCreated, { client, user })
127 }
128
129 // ---------------------------------------------------------------------------
130
131 // See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications
132 export {
133   deleteUserToken,
134   clearCacheByUserId,
135   clearCacheByToken,
136   getAccessToken,
137   getClient,
138   getRefreshToken,
139   getUser,
140   revokeToken,
141   saveToken
142 }