From bdfd19383c254386322b99d0f520921d5ff97bf3 Mon Sep 17 00:00:00 2001 From: Sebastian Haesselbarth Date: Sat, 10 Feb 2024 10:03:46 +0100 Subject: [PATCH] Code cleanup --- build/authRepository.js | 34 +++++++++++++++++----------------- build/authRepository.js.map | 4 ++-- build/main.js | 5 ++--- src/authRepository.ts | 34 +++++++++++++++++----------------- src/main.ts | 4 ++-- 5 files changed, 40 insertions(+), 41 deletions(-) diff --git a/build/authRepository.js b/build/authRepository.js index e50c941..5e9b67a 100644 --- a/build/authRepository.js +++ b/build/authRepository.js @@ -44,35 +44,35 @@ class AuthRepository { } } } - async getAccessToken() { + async getAccessTokenAsync() { var _a; this.log.debug("Get access token"); if (!this.hasAccessToken()) { if (this.options.useAuthorizationCodeGrant) { if (this.options.authCode) { - const token = await this.getAuthorizationCodeGrantToken(this.options.authCode); - await this.setSesssion(token); + const token = await this.getAuthorizationCodeGrantTokenAsync(this.options.authCode); + await this.setSesssionAsync(token); } else { this.log.error("You need to get and set a new Auth Code. You can do this in the adapter setting."); return void 0; } } else { - const token = await this.getClientCredentialsGrantToken(); - await this.setSesssion(token); + const token = await this.getClientCredentialsGrantTokenAsync(); + await this.setSesssionAsync(token); } } if (this.isTokenExpired()) { if (this.options.useAuthorizationCodeGrant) { - const token = await this.refreshToken(); - await this.setSesssion(token); + const token = await this.refreshTokenAsync(); + await this.setSesssionAsync(token); } else { - const token = await this.getClientCredentialsGrantToken(); - await this.setSesssion(token); + const token = await this.getClientCredentialsGrantTokenAsync(); + await this.setSesssionAsync(token); } } return (_a = this.auth) == null ? void 0 : _a.access_token; } - async getAuthorizationCodeGrantToken(authCode) { + async getAuthorizationCodeGrantTokenAsync(authCode) { this.log.debug("Get token via Authorization Code Grant Flow"); const data = { grant_type: "authorization_code", @@ -82,14 +82,14 @@ class AuthRepository { redirect_uri: this.options.redirectUri, scope: this.options.scope }; - const session2 = await this.postTokenRequest(data); + const session2 = await this.postTokenRequestAsync(data); this.log.debug(`Token received. Refresh Token received: ${session2.refresh_token != void 0}. Access Token expires in: ${session2.expires_in}`); if (!session2.refresh_token) { this.log.warn("Receive Access Token without Refresh Token."); } return session2; } - async getClientCredentialsGrantToken() { + async getClientCredentialsGrantTokenAsync() { this.log.debug("Get token via Client Credentials Grant Flow"); const data = { grant_type: "client_credentials", @@ -97,11 +97,11 @@ class AuthRepository { client_secret: this.options.clientSecret, scope: this.options.scope }; - const session2 = await this.postTokenRequest(data); + const session2 = await this.postTokenRequestAsync(data); this.log.debug(`Token received. Refresh Token received: ${session2.refresh_token != void 0}. Access Token expires in: ${session2.expires_in}`); return session2; } - async refreshToken() { + async refreshTokenAsync() { var _a, _b; if (!((_a = this.auth) == null ? void 0 : _a.refresh_token)) { throw new Error("Cannot refresh the token because no refresh token is available."); @@ -113,14 +113,14 @@ class AuthRepository { client_id: this.options.clientId, client_secret: this.options.clientSecret }; - const session2 = await this.postTokenRequest(data); + const session2 = await this.postTokenRequestAsync(data); this.log.debug(`Token received. Refresh Token received: ${session2.refresh_token != void 0}. Access Token expires in: ${session2.expires_in}`); if (!session2.refresh_token) { this.log.warn("Receive Access Token without Refresh Token."); } return session2; } - async postTokenRequest(body) { + async postTokenRequestAsync(body) { var _a; const stringBody = new URLSearchParams(body).toString(); const url = "/oauth/token"; @@ -164,7 +164,7 @@ class AuthRepository { this.log.debug(`Read session from file '${this.options.sessionStoreFilePath}'`); this.auth = import_jsonfile.default.readFileSync(this.options.sessionStoreFilePath, { throws: false }); } - async setSesssion(auth) { + async setSesssionAsync(auth) { this.log.debug("Set session"); if (auth.authCode == null) { auth.authCode = this.options.authCode; diff --git a/build/authRepository.js.map b/build/authRepository.js.map index 38ba460..1ec863f 100644 --- a/build/authRepository.js.map +++ b/build/authRepository.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["../src/authRepository.ts"], - "sourcesContent": ["import axios, { AxiosError } from 'axios';\nimport * as fs from 'fs';\nimport jsonfile from 'jsonfile';\nimport * as session from './models/Session';\n\nexport default interface AuthOptions {\n clientId: string;\n clientSecret: string;\n useAuthorizationCodeGrant: boolean;\n redirectUri: string;\n authCode: string;\n sessionStoreFilePath: string;\n baseUrl: string;\n scope: string;\n timeout: number;\n userAgent: string;\n renewBeforeExpiry: number;\n}\n\ninterface Session extends session.Session {\n expires_at?: number;\n authCode?: string;\n}\n\nexport class AuthRepository {\n constructor(options: AuthOptions, log: ioBroker.Log) {\n this.log = log;\n this.options = options;\n\n axios.defaults.baseURL = options.baseUrl;\n axios.defaults.headers.common['user-agent'] = options.userAgent;\n axios.defaults.timeout = options.timeout;\n\n if (this.options.useAuthorizationCodeGrant) {\n this.readSessionFromFile();\n if (this.hasNewAuthCode()) {\n this.setEmptySession();\n }\n }\n }\n\n private log: ioBroker.Log;\n private options: AuthOptions;\n private auth: Session | undefined;\n\n async getAccessToken(): Promise {\n this.log.debug('Get access token');\n\n if (!this.hasAccessToken()) {\n if (this.options.useAuthorizationCodeGrant) {\n if (this.options.authCode) {\n const token = await this.getAuthorizationCodeGrantToken(this.options.authCode);\n await this.setSesssion(token);\n } else {\n this.log.error('You need to get and set a new Auth Code. You can do this in the adapter setting.');\n return undefined;\n }\n } else {\n const token = await this.getClientCredentialsGrantToken();\n await this.setSesssion(token);\n }\n }\n if (this.isTokenExpired()) {\n if (this.options.useAuthorizationCodeGrant) {\n const token = await this.refreshToken();\n await this.setSesssion(token);\n } else {\n const token = await this.getClientCredentialsGrantToken();\n await this.setSesssion(token);\n }\n }\n\n return this.auth?.access_token;\n }\n\n private async getAuthorizationCodeGrantToken(authCode: string): Promise {\n this.log.debug('Get token via Authorization Code Grant Flow');\n const data = {\n grant_type: 'authorization_code',\n client_id: this.options.clientId,\n client_secret: this.options.clientSecret,\n code: authCode,\n redirect_uri: this.options.redirectUri,\n scope: this.options.scope,\n };\n const session = await this.postTokenRequest(data);\n this.log.debug(`Token received. Refresh Token received: ${session.refresh_token != undefined}. Access Token expires in: ${session.expires_in}`);\n if (!session.refresh_token) {\n this.log.warn('Receive Access Token without Refresh Token.');\n }\n return session;\n }\n\n private async getClientCredentialsGrantToken(): Promise {\n this.log.debug('Get token via Client Credentials Grant Flow');\n const data = {\n grant_type: 'client_credentials',\n client_id: this.options.clientId,\n client_secret: this.options.clientSecret,\n scope: this.options.scope,\n };\n const session = await this.postTokenRequest(data);\n this.log.debug(`Token received. Refresh Token received: ${session.refresh_token != undefined}. Access Token expires in: ${session.expires_in}`);\n return session;\n }\n\n private async refreshToken(): Promise {\n if (!this.auth?.refresh_token) {\n throw new Error('Cannot refresh the token because no refresh token is available.');\n }\n\n this.log.debug('Get token via Refresh Token Grant Flow');\n const data = {\n grant_type: 'refresh_token',\n refresh_token: this.auth?.refresh_token,\n client_id: this.options.clientId,\n client_secret: this.options.clientSecret,\n };\n const session = await this.postTokenRequest(data);\n this.log.debug(`Token received. Refresh Token received: ${session.refresh_token != undefined}. Access Token expires in: ${session.expires_in}`);\n if (!session.refresh_token) {\n this.log.warn('Receive Access Token without Refresh Token.');\n }\n return session;\n }\n\n private async postTokenRequest(body: any): Promise {\n const stringBody = new URLSearchParams(body).toString();\n const url = '/oauth/token';\n try {\n const { data } = await axios.post(url, stringBody, {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n });\n const expiresIn = data.expires_in ?? 1800;\n data.expires_at = Date.now() + expiresIn * 1000;\n //this.log.silly(`TokenData: ${JSON.stringify(data, null, ' ')}`);\n return data;\n } catch (error) {\n throw this.checkError(url, error);\n }\n }\n\n private checkError(suburl: string, error: unknown): Error | unknown {\n this.log.error(`error from ${suburl}`);\n this.log.error(JSON.stringify(error, null, ' '));\n if (axios.isAxiosError(error)) {\n const axiosError = error as AxiosError;\n if (axiosError.response != null) {\n if (axiosError.response.status == 401) {\n this.setEmptySession();\n }\n if (axiosError.response.data != null) {\n const responseText = JSON.stringify(axiosError.response.data, null, ' ');\n const errorMessage = `${axiosError.response.statusText}: ${responseText}`;\n return new Error(errorMessage);\n } else {\n return new Error(axiosError.response.statusText);\n }\n }\n }\n return error;\n }\n\n private readSessionFromFile(): void {\n if (!this.options.sessionStoreFilePath || !fs.existsSync(this.options.sessionStoreFilePath)) {\n return;\n }\n this.log.debug(`Read session from file '${this.options.sessionStoreFilePath}'`);\n this.auth = jsonfile.readFileSync(this.options.sessionStoreFilePath, { throws: false });\n }\n\n private async setSesssion(auth: Session): Promise {\n this.log.debug('Set session');\n if (auth.authCode == null) {\n auth.authCode = this.options.authCode;\n }\n this.auth = auth;\n if (!this.options.sessionStoreFilePath || !this.options.useAuthorizationCodeGrant) {\n return;\n }\n this.log.debug(`Write session to file '${this.options.sessionStoreFilePath}'`);\n await jsonfile.writeFile(this.options.sessionStoreFilePath, this.auth, { spaces: 2 });\n }\n\n private hasNewAuthCode(): boolean {\n const hasNewAuthCode = this.auth?.authCode != this.options.authCode;\n this.log.debug(`Has new auth code: ${hasNewAuthCode}`);\n return hasNewAuthCode;\n }\n\n private setEmptySession(): void {\n this.log.debug('Set empty session.');\n this.auth = { authCode: this.options.authCode } as Session;\n }\n\n private isTokenExpired(): boolean {\n const expired = (this.auth?.expires_at || 0) < Date.now() + this.options.renewBeforeExpiry;\n this.log.debug('Is token expired: ' + expired);\n return expired;\n }\n\n private hasAccessToken(): boolean {\n const hasAccessToken = !!this.auth?.access_token;\n this.log.debug('Has access token: ' + hasAccessToken);\n return hasAccessToken;\n }\n}\n"], - "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkC;AAClC,SAAoB;AACpB,sBAAqB;AAsBd,MAAM,eAAe;AAAA,EACxB,YAAY,SAAsB,KAAmB;AACjD,SAAK,MAAM;AACX,SAAK,UAAU;AAEf,iBAAAA,QAAM,SAAS,UAAU,QAAQ;AACjC,iBAAAA,QAAM,SAAS,QAAQ,OAAO,gBAAgB,QAAQ;AACtD,iBAAAA,QAAM,SAAS,UAAU,QAAQ;AAEjC,QAAI,KAAK,QAAQ,2BAA2B;AACxC,WAAK,oBAAoB;AACzB,UAAI,KAA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AK,IAAI,MAAM,0BAA0B,KAAK,QAAQ,uBAAuB;AAC7E,UAAM,gBAAAA,QAAS,UAAU,KAAK,QAAQ,sBAAsB,KAAK,MAAM,EAAE,QAAQ,EAAE,CAAC;AAAA,EACxF;AAAA,EAEQ,iBAA0B;AA1LtC;AA2LQ,UAAM,mBAAiB,UAAK,SAAL,mBAAW,aAAY,KAAK,QAAQ;AAC3D,SAAK,IAAI,MAAM,sBAAsB,gBAAgB;AACrD,WAAO;AAAA,EACX;AAAA,EAEQ,kBAAwB;AAC5B,SAAK,IAAI,MAAM,oBAAoB;AACnC,SAAK,OAAO,EAAE,UAAU,KAAK,QAAQ,SAAS;AAAA,EAClD;AAAA,EAEQ,iBAA0B;AArMtC;AAsMQ,UAAM,aAAW,UAAK,SAAL,mBAAW,eAAc,KAAK,KAAK,IAAI,IAAI,KAAK,QAAQ;AACzE,SAAK,IAAI,MAAM,uBAAuB,OAAO;AAC7C,WAAO;AAAA,EACX;AAAA,EAEQ,iBAA0B;AA3MtC;AA4MQ,UAAM,iBAAiB,CAAC,GAAC,UAAK,SAAL,mBAAW;AACpC,SAAK,IAAI,MAAM,uBAAuB,cAAc;AACpD,WAAO;AAAA,EACX;AACJ;", + "sourcesContent": ["import axios, { AxiosError } from 'axios';\nimport * as fs from 'fs';\nimport jsonfile from 'jsonfile';\nimport * as session from './models/Session';\n\nexport default interface AuthOptions {\n clientId: string;\n clientSecret: string;\n useAuthorizationCodeGrant: boolean;\n redirectUri: string;\n authCode: string;\n sessionStoreFilePath: string;\n baseUrl: string;\n scope: string;\n timeout: number;\n userAgent: string;\n renewBeforeExpiry: number;\n}\n\ninterface Session extends session.Session {\n expires_at?: number;\n authCode?: string;\n}\n\nexport class AuthRepository {\n constructor(options: AuthOptions, log: ioBroker.Log) {\n this.log = log;\n this.options = options;\n\n axios.defaults.baseURL = options.baseUrl;\n axios.defaults.headers.common['user-agent'] = options.userAgent;\n axios.defaults.timeout = options.timeout;\n\n if (this.options.useAuthorizationCodeGrant) {\n this.readSessionFromFile();\n if (this.hasNewAuthCode()) {\n this.setEmptySession();\n }\n }\n }\n\n private log: ioBroker.Log;\n private options: AuthOptions;\n private auth: Session | undefined;\n\n async getAccessTokenAsync(): Promise {\n this.log.debug('Get access token');\n\n if (!this.hasAccessToken()) {\n if (this.options.useAuthorizationCodeGrant) {\n if (this.options.authCode) {\n const token = await this.getAuthorizationCodeGrantTokenAsync(this.options.authCode);\n await this.setSesssionAsync(token);\n } else {\n this.log.error('You need to get and set a new Auth Code. You can do this in the adapter setting.');\n return undefined;\n }\n } else {\n const token = await this.getClientCredentialsGrantTokenAsync();\n await this.setSesssionAsync(token);\n }\n }\n if (this.isTokenExpired()) {\n if (this.options.useAuthorizationCodeGrant) {\n const token = await this.refreshTokenAsync();\n await this.setSesssionAsync(token);\n } else {\n const token = await this.getClientCredentialsGrantTokenAsync();\n await this.setSesssionAsync(token);\n }\n }\n\n return this.auth?.access_token;\n }\n\n private async getAuthorizationCodeGrantTokenAsync(authCode: string): Promise {\n this.log.debug('Get token via Authorization Code Grant Flow');\n const data = {\n grant_type: 'authorization_code',\n client_id: this.options.clientId,\n client_secret: this.options.clientSecret,\n code: authCode,\n redirect_uri: this.options.redirectUri,\n scope: this.options.scope,\n };\n const session = await this.postTokenRequestAsync(data);\n this.log.debug(`Token received. Refresh Token received: ${session.refresh_token != undefined}. Access Token expires in: ${session.expires_in}`);\n if (!session.refresh_token) {\n this.log.warn('Receive Access Token without Refresh Token.');\n }\n return session;\n }\n\n private async getClientCredentialsGrantTokenAsync(): Promise {\n this.log.debug('Get token via Client Credentials Grant Flow');\n const data = {\n grant_type: 'client_credentials',\n client_id: this.options.clientId,\n client_secret: this.options.clientSecret,\n scope: this.options.scope,\n };\n const session = await this.postTokenRequestAsync(data);\n this.log.debug(`Token received. Refresh Token received: ${session.refresh_token != undefined}. Access Token expires in: ${session.expires_in}`);\n return session;\n }\n\n private async refreshTokenAsync(): Promise {\n if (!this.auth?.refresh_token) {\n throw new Error('Cannot refresh the token because no refresh token is available.');\n }\n\n this.log.debug('Get token via Refresh Token Grant Flow');\n const data = {\n grant_type: 'refresh_token',\n refresh_token: this.auth?.refresh_token,\n client_id: this.options.clientId,\n client_secret: this.options.clientSecret,\n };\n const session = await this.postTokenRequestAsync(data);\n this.log.debug(`Token received. Refresh Token received: ${session.refresh_token != undefined}. Access Token expires in: ${session.expires_in}`);\n if (!session.refresh_token) {\n this.log.warn('Receive Access Token without Refresh Token.');\n }\n return session;\n }\n\n private async postTokenRequestAsync(body: any): Promise {\n const stringBody = new URLSearchParams(body).toString();\n const url = '/oauth/token';\n try {\n const { data } = await axios.post(url, stringBody, {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n });\n const expiresIn = data.expires_in ?? 1800;\n data.expires_at = Date.now() + expiresIn * 1000;\n //this.log.silly(`TokenData: ${JSON.stringify(data, null, ' ')}`);\n return data;\n } catch (error) {\n throw this.checkError(url, error);\n }\n }\n\n private checkError(suburl: string, error: unknown): Error | unknown {\n this.log.error(`error from ${suburl}`);\n this.log.error(JSON.stringify(error, null, ' '));\n if (axios.isAxiosError(error)) {\n const axiosError = error as AxiosError;\n if (axiosError.response != null) {\n if (axiosError.response.status == 401) {\n this.setEmptySession();\n }\n if (axiosError.response.data != null) {\n const responseText = JSON.stringify(axiosError.response.data, null, ' ');\n const errorMessage = `${axiosError.response.statusText}: ${responseText}`;\n return new Error(errorMessage);\n } else {\n return new Error(axiosError.response.statusText);\n }\n }\n }\n return error;\n }\n\n private readSessionFromFile(): void {\n if (!this.options.sessionStoreFilePath || !fs.existsSync(this.options.sessionStoreFilePath)) {\n return;\n }\n this.log.debug(`Read session from file '${this.options.sessionStoreFilePath}'`);\n this.auth = jsonfile.readFileSync(this.options.sessionStoreFilePath, { throws: false });\n }\n\n private async setSesssionAsync(auth: Session): Promise {\n this.log.debug('Set session');\n if (auth.authCode == null) {\n auth.authCode = this.options.authCode;\n }\n this.auth = auth;\n if (!this.options.sessionStoreFilePath || !this.options.useAuthorizationCodeGrant) {\n return;\n }\n this.log.debug(`Write session to file '${this.options.sessionStoreFilePath}'`);\n await jsonfile.writeFile(this.options.sessionStoreFilePath, this.auth, { spaces: 2 });\n }\n\n private hasNewAuthCode(): boolean {\n const hasNewAuthCode = this.auth?.authCode != this.options.authCode;\n this.log.debug(`Has new auth code: ${hasNewAuthCode}`);\n return hasNewAuthCode;\n }\n\n private setEmptySession(): void {\n this.log.debug('Set empty session.');\n this.auth = { authCode: this.options.authCode } as Session;\n }\n\n private isTokenExpired(): boolean {\n const expired = (this.auth?.expires_at || 0) < Date.now() + this.options.renewBeforeExpiry;\n this.log.debug('Is token expired: ' + expired);\n return expired;\n }\n\n private hasAccessToken(): boolean {\n const hasAccessToken = !!this.auth?.access_token;\n this.log.debug('Has access token: ' + hasAccessToken);\n return hasAccessToken;\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkC;AAClC,SAAoB;AACpB,sBAAqB;AAsBd,MAAM,eAAe;AAAA,EACxB,YAAY,SAAsB,KAAmB;AACjD,SAAK,MAAM;AACX,SAAK,UAAU;AAEf,iBAAAA,QAAM,SAAS,UAAU,QAAQ;AACjC,iBAAAA,QAAM,SAAS,QAAQ,OAAO,gBAAgB,QAAQ;AACtD,iBAAAA,QAAM,SAAS,UAAU,QAAQ;AAEjC,QAAI,KAAK,QAAQ,2BAA2B;AACxC,WAAK,oBAAoB;AACzB,UAAI,KAAK,eAAe,GAAG;AACvB,aAAK,gBAAgB;AAAA,MACzB;AAAA,IACJ;AAAA,EACJ;AAAA,EAMA,MAAM,sBAAmD;AA7C7D;AA8CQ,SAAK,IAAI,MAAM,kBAAkB;AAEjC,QAAI,CAAC,KAAK,eAAe,GAAG;AACxB,UAAI,KAAK,QAAQ,2BAA2B;AACxC,YAAI,KAAK,QAAQ,UAAU;AACvB,gBAAM,QAAQ,MAAM,KAAK,oCAAoC,KAAK,QAAQ,QAAQ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rD,WAAO;AAAA,EACX;AAAA,EAEQ,kBAAwB;AAC5B,SAAK,IAAI,MAAM,oBAAoB;AACnC,SAAK,OAAO,EAAE,UAAU,KAAK,QAAQ,SAAS;AAAA,EAClD;AAAA,EAEQ,iBAA0B;AArMtC;AAsMQ,UAAM,aAAW,UAAK,SAAL,mBAAW,eAAc,KAAK,KAAK,IAAI,IAAI,KAAK,QAAQ;AACzE,SAAK,IAAI,MAAM,uBAAuB,OAAO;AAC7C,WAAO;AAAA,EACX;AAAA,EAEQ,iBAA0B;AA3MtC;AA4MQ,UAAM,iBAAiB,CAAC,GAAC,UAAK,SAAL,mBAAW;AACpC,SAAK,IAAI,MAAM,uBAAuB,cAAc;AACpD,WAAO;AAAA,EACX;AACJ;", "names": ["axios", "session", "jsonfile"] } diff --git a/build/main.js b/build/main.js index 9ac36b7..622f7ba 100644 --- a/build/main.js +++ b/build/main.js @@ -152,10 +152,9 @@ class Myuplink extends utils.Adapter { await this.getDataAsync(); } async getDataAsync() { - var _a; try { if (this.authRepository) { - const accessToken = await this.authRepository.getAccessToken(); + const accessToken = await this.authRepository.getAccessTokenAsync(); if (accessToken && this.myUplinkRepository) { const systems = await this.myUplinkRepository.getSystemsAndDevicesAsync(accessToken); this.setState("info.connection", { val: true, expire: this.refreshInterval + 30, ack: true }); @@ -541,7 +540,7 @@ class Myuplink extends utils.Adapter { const obj = await this.getObjectAsync(id); if (obj != null && obj.native != null && obj.native.writable == true && obj.native.deviceId != null && obj.native.deviceId != "") { try { - const accessToken = await this.authRepository.getAccessToken(); + const accessToken = await this.authRepository.getAccessTokenAsync(); if (accessToken) { const deviceId = obj.native.deviceId; const value = state.val.toString(); diff --git a/src/authRepository.ts b/src/authRepository.ts index ad49fc6..0b2835b 100644 --- a/src/authRepository.ts +++ b/src/authRepository.ts @@ -43,37 +43,37 @@ export class AuthRepository { private options: AuthOptions; private auth: Session | undefined; - async getAccessToken(): Promise { + async getAccessTokenAsync(): Promise { this.log.debug('Get access token'); if (!this.hasAccessToken()) { if (this.options.useAuthorizationCodeGrant) { if (this.options.authCode) { - const token = await this.getAuthorizationCodeGrantToken(this.options.authCode); - await this.setSesssion(token); + const token = await this.getAuthorizationCodeGrantTokenAsync(this.options.authCode); + await this.setSesssionAsync(token); } else { this.log.error('You need to get and set a new Auth Code. You can do this in the adapter setting.'); return undefined; } } else { - const token = await this.getClientCredentialsGrantToken(); - await this.setSesssion(token); + const token = await this.getClientCredentialsGrantTokenAsync(); + await this.setSesssionAsync(token); } } if (this.isTokenExpired()) { if (this.options.useAuthorizationCodeGrant) { - const token = await this.refreshToken(); - await this.setSesssion(token); + const token = await this.refreshTokenAsync(); + await this.setSesssionAsync(token); } else { - const token = await this.getClientCredentialsGrantToken(); - await this.setSesssion(token); + const token = await this.getClientCredentialsGrantTokenAsync(); + await this.setSesssionAsync(token); } } return this.auth?.access_token; } - private async getAuthorizationCodeGrantToken(authCode: string): Promise { + private async getAuthorizationCodeGrantTokenAsync(authCode: string): Promise { this.log.debug('Get token via Authorization Code Grant Flow'); const data = { grant_type: 'authorization_code', @@ -83,7 +83,7 @@ export class AuthRepository { redirect_uri: this.options.redirectUri, scope: this.options.scope, }; - const session = await this.postTokenRequest(data); + const session = await this.postTokenRequestAsync(data); this.log.debug(`Token received. Refresh Token received: ${session.refresh_token != undefined}. Access Token expires in: ${session.expires_in}`); if (!session.refresh_token) { this.log.warn('Receive Access Token without Refresh Token.'); @@ -91,7 +91,7 @@ export class AuthRepository { return session; } - private async getClientCredentialsGrantToken(): Promise { + private async getClientCredentialsGrantTokenAsync(): Promise { this.log.debug('Get token via Client Credentials Grant Flow'); const data = { grant_type: 'client_credentials', @@ -99,12 +99,12 @@ export class AuthRepository { client_secret: this.options.clientSecret, scope: this.options.scope, }; - const session = await this.postTokenRequest(data); + const session = await this.postTokenRequestAsync(data); this.log.debug(`Token received. Refresh Token received: ${session.refresh_token != undefined}. Access Token expires in: ${session.expires_in}`); return session; } - private async refreshToken(): Promise { + private async refreshTokenAsync(): Promise { if (!this.auth?.refresh_token) { throw new Error('Cannot refresh the token because no refresh token is available.'); } @@ -116,7 +116,7 @@ export class AuthRepository { client_id: this.options.clientId, client_secret: this.options.clientSecret, }; - const session = await this.postTokenRequest(data); + const session = await this.postTokenRequestAsync(data); this.log.debug(`Token received. Refresh Token received: ${session.refresh_token != undefined}. Access Token expires in: ${session.expires_in}`); if (!session.refresh_token) { this.log.warn('Receive Access Token without Refresh Token.'); @@ -124,7 +124,7 @@ export class AuthRepository { return session; } - private async postTokenRequest(body: any): Promise { + private async postTokenRequestAsync(body: any): Promise { const stringBody = new URLSearchParams(body).toString(); const url = '/oauth/token'; try { @@ -171,7 +171,7 @@ export class AuthRepository { this.auth = jsonfile.readFileSync(this.options.sessionStoreFilePath, { throws: false }); } - private async setSesssion(auth: Session): Promise { + private async setSesssionAsync(auth: Session): Promise { this.log.debug('Set session'); if (auth.authCode == null) { auth.authCode = this.options.authCode; diff --git a/src/main.ts b/src/main.ts index 42d4847..c5d9f80 100644 --- a/src/main.ts +++ b/src/main.ts @@ -187,7 +187,7 @@ class Myuplink extends utils.Adapter { private async getDataAsync(): Promise { try { if (this.authRepository) { - const accessToken = await this.authRepository.getAccessToken(); + const accessToken = await this.authRepository.getAccessTokenAsync(); if (accessToken && this.myUplinkRepository) { const systems = await this.myUplinkRepository.getSystemsAndDevicesAsync(accessToken); this.setState('info.connection', { val: true, expire: this.refreshInterval + 30, ack: true }); @@ -591,7 +591,7 @@ class Myuplink extends utils.Adapter { const obj = await this.getObjectAsync(id); if (obj != null && obj.native != null && obj.native.writable == true && obj.native.deviceId != null && obj.native.deviceId != '') { try { - const accessToken = await this.authRepository.getAccessToken(); + const accessToken = await this.authRepository.getAccessTokenAsync(); if (accessToken) { const deviceId = obj.native.deviceId; const value = state.val.toString();