From a4ff3100d36f2fe9a4dfc00e8487c28a94433c4f Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 6 Aug 2020 15:25:19 +0200 Subject: Cleanup tokens logic in embed --- .../recommended-videos.component.ts | 12 +- client/src/app/core/auth/auth-user.model.ts | 54 ++++----- client/src/app/core/theme/theme.service.ts | 16 +-- client/src/app/core/users/user.model.ts | 3 - client/src/app/core/users/user.service.ts | 55 ++++----- client/src/root-helpers/index.ts | 3 +- client/src/root-helpers/pure-auth-user.model.ts | 123 --------------------- client/src/root-helpers/user-keys.ts | 15 --- client/src/root-helpers/users/index.ts | 3 + .../root-helpers/users/user-local-storage-keys.ts | 15 +++ .../users/user-local-storage-manager.ts | 55 +++++++++ client/src/root-helpers/users/user-tokens.ts | 61 ++++++++++ client/src/standalone/videos/embed.ts | 26 +++-- 13 files changed, 213 insertions(+), 228 deletions(-) delete mode 100644 client/src/root-helpers/pure-auth-user.model.ts delete mode 100644 client/src/root-helpers/user-keys.ts create mode 100644 client/src/root-helpers/users/index.ts create mode 100644 client/src/root-helpers/users/user-local-storage-keys.ts create mode 100644 client/src/root-helpers/users/user-local-storage-manager.ts create mode 100644 client/src/root-helpers/users/user-tokens.ts (limited to 'client') diff --git a/client/src/app/+videos/+video-watch/recommendations/recommended-videos.component.ts b/client/src/app/+videos/+video-watch/recommendations/recommended-videos.component.ts index 016975341..d2372023f 100644 --- a/client/src/app/+videos/+video-watch/recommendations/recommended-videos.component.ts +++ b/client/src/app/+videos/+video-watch/recommendations/recommended-videos.component.ts @@ -7,6 +7,7 @@ import { VideoPlaylist } from '@app/shared/shared-video-playlist' import { I18n } from '@ngx-translate/i18n-polyfill' import { RecommendationInfo } from './recommendation-info.model' import { RecommendedVideosStore } from './recommended-videos.store' +import { UserLocalStorageKeys } from '@root-helpers/users' @Component({ selector: 'my-recommended-videos', @@ -48,9 +49,12 @@ export class RecommendedVideosComponent implements OnInit, OnChanges { if (this.authService.isLoggedIn()) { this.autoPlayNextVideo = this.authService.getUser().autoPlayNextVideo } else { - this.autoPlayNextVideo = this.sessionStorageService.getItem(User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true' || false - this.sessionStorageService.watch([User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO]).subscribe( - () => this.autoPlayNextVideo = this.sessionStorageService.getItem(User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true' + this.autoPlayNextVideo = this.sessionStorageService.getItem(UserLocalStorageKeys.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true' + + this.sessionStorageService.watch([UserLocalStorageKeys.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO]).subscribe( + () => { + this.autoPlayNextVideo = this.sessionStorageService.getItem(UserLocalStorageKeys.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true' + } ) } @@ -73,7 +77,7 @@ export class RecommendedVideosComponent implements OnInit, OnChanges { } switchAutoPlayNextVideo () { - this.sessionStorageService.setItem(User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO, this.autoPlayNextVideo.toString()) + this.sessionStorageService.setItem(UserLocalStorageKeys.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO, this.autoPlayNextVideo.toString()) if (this.authService.isLoggedIn()) { const details = { diff --git a/client/src/app/core/auth/auth-user.model.ts b/client/src/app/core/auth/auth-user.model.ts index 5679d28a9..34efa24fc 100644 --- a/client/src/app/core/auth/auth-user.model.ts +++ b/client/src/app/core/auth/auth-user.model.ts @@ -1,18 +1,22 @@ import { Observable, of } from 'rxjs' import { map } from 'rxjs/operators' import { User } from '@app/core/users/user.model' -import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage' +import { + flushUserInfoFromLocalStorage, + getUserInfoFromLocalStorage, + saveUserInfoIntoLocalStorage, + TokenOptions, + Tokens +} from '@root-helpers/users' import { hasUserRight } from '@shared/core-utils/users' import { MyUser as ServerMyUserModel, MyUserSpecialPlaylist, - NSFWPolicyType, User as ServerUserModel, UserRight, UserRole, UserVideoQuota } from '@shared/models' -import { TokenOptions, Tokens } from '@root-helpers/pure-auth-user.model' export class AuthUser extends User implements ServerMyUserModel { tokens: Tokens @@ -21,31 +25,16 @@ export class AuthUser extends User implements ServerMyUserModel { canSeeVideosLink = true static load () { - const usernameLocalStorage = peertubeLocalStorage.getItem(this.KEYS.USERNAME) - if (usernameLocalStorage) { - return new AuthUser( - { - id: parseInt(peertubeLocalStorage.getItem(this.KEYS.ID), 10), - username: peertubeLocalStorage.getItem(this.KEYS.USERNAME), - email: peertubeLocalStorage.getItem(this.KEYS.EMAIL), - role: parseInt(peertubeLocalStorage.getItem(this.KEYS.ROLE), 10) as UserRole, - nsfwPolicy: peertubeLocalStorage.getItem(this.KEYS.NSFW_POLICY) as NSFWPolicyType, - webTorrentEnabled: peertubeLocalStorage.getItem(this.KEYS.WEBTORRENT_ENABLED) === 'true', - autoPlayVideo: peertubeLocalStorage.getItem(this.KEYS.AUTO_PLAY_VIDEO) === 'true', - videosHistoryEnabled: peertubeLocalStorage.getItem(this.KEYS.VIDEOS_HISTORY_ENABLED) === 'true' - }, - Tokens.load() - ) - } + const userInfo = getUserInfoFromLocalStorage() + + if (!userInfo) return null - return null + return new AuthUser(userInfo, Tokens.load()) } static flush () { - peertubeLocalStorage.removeItem(this.KEYS.USERNAME) - peertubeLocalStorage.removeItem(this.KEYS.ID) - peertubeLocalStorage.removeItem(this.KEYS.ROLE) - peertubeLocalStorage.removeItem(this.KEYS.EMAIL) + flushUserInfoFromLocalStorage() + Tokens.flush() } @@ -87,13 +76,16 @@ export class AuthUser extends User implements ServerMyUserModel { } save () { - peertubeLocalStorage.setItem(AuthUser.KEYS.ID, this.id.toString()) - peertubeLocalStorage.setItem(AuthUser.KEYS.USERNAME, this.username) - peertubeLocalStorage.setItem(AuthUser.KEYS.EMAIL, this.email) - peertubeLocalStorage.setItem(AuthUser.KEYS.ROLE, this.role.toString()) - peertubeLocalStorage.setItem(AuthUser.KEYS.NSFW_POLICY, this.nsfwPolicy.toString()) - peertubeLocalStorage.setItem(AuthUser.KEYS.WEBTORRENT_ENABLED, JSON.stringify(this.webTorrentEnabled)) - peertubeLocalStorage.setItem(AuthUser.KEYS.AUTO_PLAY_VIDEO, JSON.stringify(this.autoPlayVideo)) + saveUserInfoIntoLocalStorage({ + id: this.id, + username: this.username, + email: this.email, + role: this.role, + nsfwPolicy: this.nsfwPolicy, + webTorrentEnabled: this.webTorrentEnabled, + autoPlayVideo: this.autoPlayVideo + }) + this.tokens.save() } diff --git a/client/src/app/core/theme/theme.service.ts b/client/src/app/core/theme/theme.service.ts index 7e05fdddd..4c4611d01 100644 --- a/client/src/app/core/theme/theme.service.ts +++ b/client/src/app/core/theme/theme.service.ts @@ -1,13 +1,13 @@ import { first } from 'rxjs/operators' import { Injectable } from '@angular/core' +import { UserLocalStorageKeys } from '@root-helpers/users' +import { ServerConfig, ServerConfigTheme } from '@shared/models' +import { environment } from '../../../environments/environment' import { AuthService } from '../auth' import { PluginService } from '../plugins/plugin.service' import { ServerService } from '../server' -import { LocalStorageService } from '../wrappers/storage.service' -import { User } from '../users/user.model' import { UserService } from '../users/user.service' -import { ServerConfig, ServerConfigTheme } from '@shared/models' -import { environment } from '../../../environments/environment' +import { LocalStorageService } from '../wrappers/storage.service' @Injectable() export class ThemeService { @@ -111,9 +111,9 @@ export class ThemeService { this.pluginService.reloadLoadedScopes() - this.localStorageService.setItem(User.KEYS.LAST_ACTIVE_THEME, JSON.stringify(theme), false) + this.localStorageService.setItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, JSON.stringify(theme), false) } else { - this.localStorageService.removeItem(User.KEYS.LAST_ACTIVE_THEME, false) + this.localStorageService.removeItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, false) } this.oldThemeName = currentTheme @@ -127,7 +127,7 @@ export class ThemeService { if (!this.auth.isLoggedIn()) { this.updateCurrentTheme() - this.localStorageService.watch([ User.KEYS.THEME ]).subscribe( + this.localStorageService.watch([ UserLocalStorageKeys.THEME ]).subscribe( () => this.updateCurrentTheme() ) } @@ -138,7 +138,7 @@ export class ThemeService { } private loadAndSetFromLocalStorage () { - const lastActiveThemeString = this.localStorageService.getItem(User.KEYS.LAST_ACTIVE_THEME) + const lastActiveThemeString = this.localStorageService.getItem(UserLocalStorageKeys.LAST_ACTIVE_THEME) if (!lastActiveThemeString) return try { diff --git a/client/src/app/core/users/user.model.ts b/client/src/app/core/users/user.model.ts index f0d3a08b8..7c9569ed4 100644 --- a/client/src/app/core/users/user.model.ts +++ b/client/src/app/core/users/user.model.ts @@ -10,11 +10,8 @@ import { UserRole, VideoChannel } from '@shared/models' -import { UserKeys } from '@root-helpers/user-keys' export class User implements UserServerModel { - static KEYS = UserKeys - id: number username: string email: string diff --git a/client/src/app/core/users/user.service.ts b/client/src/app/core/users/user.service.ts index c98b3844c..aac2a0206 100644 --- a/client/src/app/core/users/user.service.ts +++ b/client/src/app/core/users/user.service.ts @@ -1,4 +1,3 @@ -import { has } from 'lodash-es' import { BytesPipe } from 'ngx-pipes' import { SortMeta } from 'primeng/api' import { from, Observable, of } from 'rxjs' @@ -7,6 +6,7 @@ import { HttpClient, HttpParams } from '@angular/common/http' import { Injectable } from '@angular/core' import { AuthService } from '@app/core/auth' import { I18n } from '@ngx-translate/i18n-polyfill' +import { UserLocalStorageKeys } from '@root-helpers/users' import { Avatar, NSFWPolicyType, @@ -81,37 +81,28 @@ export class UserService { } updateMyAnonymousProfile (profile: UserUpdateMe) { - const supportedKeys = { - // local storage keys - nsfwPolicy: (val: NSFWPolicyType) => this.localStorageService.setItem(User.KEYS.NSFW_POLICY, val), - webTorrentEnabled: (val: boolean) => this.localStorageService.setItem(User.KEYS.WEBTORRENT_ENABLED, String(val)), - autoPlayVideo: (val: boolean) => this.localStorageService.setItem(User.KEYS.AUTO_PLAY_VIDEO, String(val)), - autoPlayNextVideoPlaylist: (val: boolean) => this.localStorageService.setItem(User.KEYS.AUTO_PLAY_VIDEO_PLAYLIST, String(val)), - theme: (val: string) => this.localStorageService.setItem(User.KEYS.THEME, val), - videoLanguages: (val: string[]) => this.localStorageService.setItem(User.KEYS.VIDEO_LANGUAGES, JSON.stringify(val)), + try { + this.localStorageService.setItem(UserLocalStorageKeys.NSFW_POLICY, profile.nsfwPolicy) + this.localStorageService.setItem(UserLocalStorageKeys.WEBTORRENT_ENABLED, profile.webTorrentEnabled) - // session storage keys - autoPlayNextVideo: (val: boolean) => - this.sessionStorageService.setItem(User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO, String(val)) - } + this.localStorageService.setItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO, profile.autoPlayNextVideo) + this.localStorageService.setItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST, profile.autoPlayNextVideoPlaylist) - for (const key of Object.keys(profile)) { - try { - if (has(supportedKeys, key)) supportedKeys[key](profile[key]) - } catch (err) { - console.error(`Cannot set item ${key} in localStorage. Likely due to a value impossible to stringify.`, err) - } + this.localStorageService.setItem(UserLocalStorageKeys.THEME, profile.theme) + this.localStorageService.setItem(UserLocalStorageKeys.VIDEO_LANGUAGES, profile.videoLanguages) + } catch (err) { + console.error(`Cannot set item in localStorage. Likely due to a value impossible to stringify.`, err) } } listenAnonymousUpdate () { return this.localStorageService.watch([ - User.KEYS.NSFW_POLICY, - User.KEYS.WEBTORRENT_ENABLED, - User.KEYS.AUTO_PLAY_VIDEO, - User.KEYS.AUTO_PLAY_VIDEO_PLAYLIST, - User.KEYS.THEME, - User.KEYS.VIDEO_LANGUAGES + UserLocalStorageKeys.NSFW_POLICY, + UserLocalStorageKeys.WEBTORRENT_ENABLED, + UserLocalStorageKeys.AUTO_PLAY_VIDEO, + UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST, + UserLocalStorageKeys.THEME, + UserLocalStorageKeys.VIDEO_LANGUAGES ]).pipe( throttleTime(200), filter(() => this.authService.isLoggedIn() !== true), @@ -269,7 +260,7 @@ export class UserService { let videoLanguages: string[] try { - videoLanguages = JSON.parse(this.localStorageService.getItem(User.KEYS.VIDEO_LANGUAGES)) + videoLanguages = JSON.parse(this.localStorageService.getItem(UserLocalStorageKeys.VIDEO_LANGUAGES)) } catch (err) { videoLanguages = null console.error('Cannot parse desired video languages from localStorage.', err) @@ -277,16 +268,16 @@ export class UserService { return new User({ // local storage keys - nsfwPolicy: this.localStorageService.getItem(User.KEYS.NSFW_POLICY) as NSFWPolicyType, - webTorrentEnabled: this.localStorageService.getItem(User.KEYS.WEBTORRENT_ENABLED) !== 'false', - theme: this.localStorageService.getItem(User.KEYS.THEME) || 'instance-default', + nsfwPolicy: this.localStorageService.getItem(UserLocalStorageKeys.NSFW_POLICY) as NSFWPolicyType, + webTorrentEnabled: this.localStorageService.getItem(UserLocalStorageKeys.WEBTORRENT_ENABLED) !== 'false', + theme: this.localStorageService.getItem(UserLocalStorageKeys.THEME) || 'instance-default', videoLanguages, - autoPlayNextVideoPlaylist: this.localStorageService.getItem(User.KEYS.AUTO_PLAY_VIDEO_PLAYLIST) !== 'false', - autoPlayVideo: this.localStorageService.getItem(User.KEYS.AUTO_PLAY_VIDEO) === 'true', + autoPlayNextVideoPlaylist: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST) !== 'false', + autoPlayVideo: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO) === 'true', // session storage keys - autoPlayNextVideo: this.sessionStorageService.getItem(User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true' + autoPlayNextVideo: this.sessionStorageService.getItem(UserLocalStorageKeys.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true' }) } diff --git a/client/src/root-helpers/index.ts b/client/src/root-helpers/index.ts index 5ed4933f1..59468b31c 100644 --- a/client/src/root-helpers/index.ts +++ b/client/src/root-helpers/index.ts @@ -1,4 +1,3 @@ +export * from './users' export * from './peertube-web-storage' export * from './utils' -export * from './user-keys' -export * from './pure-auth-user.model' diff --git a/client/src/root-helpers/pure-auth-user.model.ts b/client/src/root-helpers/pure-auth-user.model.ts deleted file mode 100644 index 81226da01..000000000 --- a/client/src/root-helpers/pure-auth-user.model.ts +++ /dev/null @@ -1,123 +0,0 @@ -// pure version of auth-user, that doesn't import app packages -import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage' -import { - MyUser as ServerMyUserModel, - MyUserSpecialPlaylist, - NSFWPolicyType, - UserRole -} from '@shared/models' -import { UserKeys } from '@root-helpers/user-keys' - -export type TokenOptions = { - accessToken: string - refreshToken: string - tokenType: string -} - -// Private class only used by User -export class Tokens { - private static KEYS = { - ACCESS_TOKEN: 'access_token', - REFRESH_TOKEN: 'refresh_token', - TOKEN_TYPE: 'token_type' - } - - accessToken: string - refreshToken: string - tokenType: string - - static load () { - const accessTokenLocalStorage = peertubeLocalStorage.getItem(this.KEYS.ACCESS_TOKEN) - const refreshTokenLocalStorage = peertubeLocalStorage.getItem(this.KEYS.REFRESH_TOKEN) - const tokenTypeLocalStorage = peertubeLocalStorage.getItem(this.KEYS.TOKEN_TYPE) - - if (accessTokenLocalStorage && refreshTokenLocalStorage && tokenTypeLocalStorage) { - return new Tokens({ - accessToken: accessTokenLocalStorage, - refreshToken: refreshTokenLocalStorage, - tokenType: tokenTypeLocalStorage - }) - } - - return null - } - - static flush () { - peertubeLocalStorage.removeItem(this.KEYS.ACCESS_TOKEN) - peertubeLocalStorage.removeItem(this.KEYS.REFRESH_TOKEN) - peertubeLocalStorage.removeItem(this.KEYS.TOKEN_TYPE) - } - - constructor (hash?: TokenOptions) { - if (hash) { - this.accessToken = hash.accessToken - this.refreshToken = hash.refreshToken - - if (hash.tokenType === 'bearer') { - this.tokenType = 'Bearer' - } else { - this.tokenType = hash.tokenType - } - } - } - - save () { - peertubeLocalStorage.setItem(Tokens.KEYS.ACCESS_TOKEN, this.accessToken) - peertubeLocalStorage.setItem(Tokens.KEYS.REFRESH_TOKEN, this.refreshToken) - peertubeLocalStorage.setItem(Tokens.KEYS.TOKEN_TYPE, this.tokenType) - } -} - -export class PureAuthUser { - tokens: Tokens - specialPlaylists: MyUserSpecialPlaylist[] - - canSeeVideosLink = true - - static load () { - const usernameLocalStorage = peertubeLocalStorage.getItem(UserKeys.USERNAME) - if (usernameLocalStorage) { - return new PureAuthUser( - { - id: parseInt(peertubeLocalStorage.getItem(UserKeys.ID), 10), - username: peertubeLocalStorage.getItem(UserKeys.USERNAME), - email: peertubeLocalStorage.getItem(UserKeys.EMAIL), - role: parseInt(peertubeLocalStorage.getItem(UserKeys.ROLE), 10) as UserRole, - nsfwPolicy: peertubeLocalStorage.getItem(UserKeys.NSFW_POLICY) as NSFWPolicyType, - webTorrentEnabled: peertubeLocalStorage.getItem(UserKeys.WEBTORRENT_ENABLED) === 'true', - autoPlayVideo: peertubeLocalStorage.getItem(UserKeys.AUTO_PLAY_VIDEO) === 'true', - videosHistoryEnabled: peertubeLocalStorage.getItem(UserKeys.VIDEOS_HISTORY_ENABLED) === 'true' - }, - Tokens.load() - ) - } - - return null - } - - constructor (userHash: Partial, hashTokens: TokenOptions) { - this.tokens = new Tokens(hashTokens) - this.specialPlaylists = userHash.specialPlaylists - } - - getAccessToken () { - return this.tokens.accessToken - } - - getRefreshToken () { - return this.tokens.refreshToken - } - - getTokenType () { - return this.tokens.tokenType - } - - refreshTokens (accessToken: string, refreshToken: string) { - this.tokens.accessToken = accessToken - this.tokens.refreshToken = refreshToken - } - - save () { - this.tokens.save() - } -} diff --git a/client/src/root-helpers/user-keys.ts b/client/src/root-helpers/user-keys.ts deleted file mode 100644 index 897be8c43..000000000 --- a/client/src/root-helpers/user-keys.ts +++ /dev/null @@ -1,15 +0,0 @@ -export const UserKeys = { - ID: 'id', - ROLE: 'role', - EMAIL: 'email', - VIDEOS_HISTORY_ENABLED: 'videos-history-enabled', - USERNAME: 'username', - NSFW_POLICY: 'nsfw_policy', - WEBTORRENT_ENABLED: 'peertube-videojs-' + 'webtorrent_enabled', - AUTO_PLAY_VIDEO: 'auto_play_video', - SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO: 'auto_play_next_video', - AUTO_PLAY_VIDEO_PLAYLIST: 'auto_play_video_playlist', - THEME: 'theme', - LAST_ACTIVE_THEME: 'last_active_theme', - VIDEO_LANGUAGES: 'video_languages' -} diff --git a/client/src/root-helpers/users/index.ts b/client/src/root-helpers/users/index.ts new file mode 100644 index 000000000..8fbaca9e3 --- /dev/null +++ b/client/src/root-helpers/users/index.ts @@ -0,0 +1,3 @@ +export * from './user-local-storage-keys' +export * from './user-local-storage-manager' +export * from './user-tokens' diff --git a/client/src/root-helpers/users/user-local-storage-keys.ts b/client/src/root-helpers/users/user-local-storage-keys.ts new file mode 100644 index 000000000..5f915899c --- /dev/null +++ b/client/src/root-helpers/users/user-local-storage-keys.ts @@ -0,0 +1,15 @@ +export const UserLocalStorageKeys = { + ID: 'id', + ROLE: 'role', + EMAIL: 'email', + VIDEOS_HISTORY_ENABLED: 'videos-history-enabled', + USERNAME: 'username', + NSFW_POLICY: 'nsfw_policy', + WEBTORRENT_ENABLED: 'peertube-videojs-' + 'webtorrent_enabled', + AUTO_PLAY_VIDEO: 'auto_play_video', + SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO: 'auto_play_next_video', + AUTO_PLAY_VIDEO_PLAYLIST: 'auto_play_video_playlist', + THEME: 'theme', + LAST_ACTIVE_THEME: 'last_active_theme', + VIDEO_LANGUAGES: 'video_languages' +} diff --git a/client/src/root-helpers/users/user-local-storage-manager.ts b/client/src/root-helpers/users/user-local-storage-manager.ts new file mode 100644 index 000000000..c75cea127 --- /dev/null +++ b/client/src/root-helpers/users/user-local-storage-manager.ts @@ -0,0 +1,55 @@ +import { NSFWPolicyType, UserRole } from '@shared/models' +import { peertubeLocalStorage } from '../peertube-web-storage' +import { UserLocalStorageKeys } from './user-local-storage-keys' + +function getUserInfoFromLocalStorage () { + const usernameLocalStorage = peertubeLocalStorage.getItem(UserLocalStorageKeys.USERNAME) + + if (!usernameLocalStorage) return undefined + + return { + id: parseInt(peertubeLocalStorage.getItem(UserLocalStorageKeys.ID), 10), + username: peertubeLocalStorage.getItem(UserLocalStorageKeys.USERNAME), + email: peertubeLocalStorage.getItem(UserLocalStorageKeys.EMAIL), + role: parseInt(peertubeLocalStorage.getItem(UserLocalStorageKeys.ROLE), 10) as UserRole, + nsfwPolicy: peertubeLocalStorage.getItem(UserLocalStorageKeys.NSFW_POLICY) as NSFWPolicyType, + webTorrentEnabled: peertubeLocalStorage.getItem(UserLocalStorageKeys.WEBTORRENT_ENABLED) === 'true', + autoPlayVideo: peertubeLocalStorage.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO) === 'true', + videosHistoryEnabled: peertubeLocalStorage.getItem(UserLocalStorageKeys.VIDEOS_HISTORY_ENABLED) === 'true' + } +} + +function flushUserInfoFromLocalStorage () { + peertubeLocalStorage.removeItem(UserLocalStorageKeys.ID) + peertubeLocalStorage.removeItem(UserLocalStorageKeys.USERNAME) + peertubeLocalStorage.removeItem(UserLocalStorageKeys.EMAIL) + peertubeLocalStorage.removeItem(UserLocalStorageKeys.ROLE) + peertubeLocalStorage.removeItem(UserLocalStorageKeys.NSFW_POLICY) + peertubeLocalStorage.removeItem(UserLocalStorageKeys.WEBTORRENT_ENABLED) + peertubeLocalStorage.removeItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO) + peertubeLocalStorage.removeItem(UserLocalStorageKeys.VIDEOS_HISTORY_ENABLED) +} + +function saveUserInfoIntoLocalStorage (info: { + id: number + username: string + email: string + role: UserRole + nsfwPolicy: NSFWPolicyType + webTorrentEnabled: boolean + autoPlayVideo: boolean +}) { + peertubeLocalStorage.setItem(UserLocalStorageKeys.ID, info.id.toString()) + peertubeLocalStorage.setItem(UserLocalStorageKeys.USERNAME, info.username) + peertubeLocalStorage.setItem(UserLocalStorageKeys.EMAIL, info.email) + peertubeLocalStorage.setItem(UserLocalStorageKeys.ROLE, info.role.toString()) + peertubeLocalStorage.setItem(UserLocalStorageKeys.NSFW_POLICY, info.nsfwPolicy.toString()) + peertubeLocalStorage.setItem(UserLocalStorageKeys.WEBTORRENT_ENABLED, JSON.stringify(info.webTorrentEnabled)) + peertubeLocalStorage.setItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO, JSON.stringify(info.autoPlayVideo)) +} + +export { + getUserInfoFromLocalStorage, + saveUserInfoIntoLocalStorage, + flushUserInfoFromLocalStorage +} diff --git a/client/src/root-helpers/users/user-tokens.ts b/client/src/root-helpers/users/user-tokens.ts new file mode 100644 index 000000000..d42e1c8f3 --- /dev/null +++ b/client/src/root-helpers/users/user-tokens.ts @@ -0,0 +1,61 @@ +import { peertubeLocalStorage } from '../peertube-web-storage' + +export type TokenOptions = { + accessToken: string + refreshToken: string + tokenType: string +} + +// Private class only used by User +export class Tokens { + private static KEYS = { + ACCESS_TOKEN: 'access_token', + REFRESH_TOKEN: 'refresh_token', + TOKEN_TYPE: 'token_type' + } + + accessToken: string + refreshToken: string + tokenType: string + + static load () { + const accessTokenLocalStorage = peertubeLocalStorage.getItem(this.KEYS.ACCESS_TOKEN) + const refreshTokenLocalStorage = peertubeLocalStorage.getItem(this.KEYS.REFRESH_TOKEN) + const tokenTypeLocalStorage = peertubeLocalStorage.getItem(this.KEYS.TOKEN_TYPE) + + if (accessTokenLocalStorage && refreshTokenLocalStorage && tokenTypeLocalStorage) { + return new Tokens({ + accessToken: accessTokenLocalStorage, + refreshToken: refreshTokenLocalStorage, + tokenType: tokenTypeLocalStorage + }) + } + + return null + } + + static flush () { + peertubeLocalStorage.removeItem(this.KEYS.ACCESS_TOKEN) + peertubeLocalStorage.removeItem(this.KEYS.REFRESH_TOKEN) + peertubeLocalStorage.removeItem(this.KEYS.TOKEN_TYPE) + } + + constructor (hash?: TokenOptions) { + if (hash) { + this.accessToken = hash.accessToken + this.refreshToken = hash.refreshToken + + if (hash.tokenType === 'bearer') { + this.tokenType = 'Bearer' + } else { + this.tokenType = hash.tokenType + } + } + } + + save () { + peertubeLocalStorage.setItem(Tokens.KEYS.ACCESS_TOKEN, this.accessToken) + peertubeLocalStorage.setItem(Tokens.KEYS.REFRESH_TOKEN, this.refreshToken) + peertubeLocalStorage.setItem(Tokens.KEYS.TOKEN_TYPE, this.tokenType) + } +} diff --git a/client/src/standalone/videos/embed.ts b/client/src/standalone/videos/embed.ts index 89903aa35..8b00be790 100644 --- a/client/src/standalone/videos/embed.ts +++ b/client/src/standalone/videos/embed.ts @@ -1,6 +1,7 @@ import './embed.scss' import videojs from 'video.js' -import { objectToUrlEncoded, peertubeLocalStorage, PureAuthUser } from '@root-helpers/index' +import { objectToUrlEncoded, peertubeLocalStorage } from '@root-helpers/index' +import { Tokens } from '@root-helpers/users' import { peertubeTranslate } from '../../../../shared/core-utils/i18n' import { ResultList, @@ -39,7 +40,7 @@ export class PeerTubeEmbed { mode: PlayerMode scope = 'peertube' - user: PureAuthUser + userTokens: Tokens headers = new Headers() LOCAL_STORAGE_OAUTH_CLIENT_KEYS = { CLIENT_ID: 'client_id', @@ -74,7 +75,7 @@ export class PeerTubeEmbed { const headers = new Headers() headers.set('Content-Type', 'application/x-www-form-urlencoded') const data = { - refresh_token: this.user.getRefreshToken(), + refresh_token: this.userTokens.refreshToken, client_id: clientId, client_secret: clientSecret, response_type: 'code', @@ -88,9 +89,12 @@ export class PeerTubeEmbed { }) .then(res => res.json()) .then((obj: UserRefreshToken) => { - this.user.refreshTokens(obj.access_token, obj.refresh_token) - this.user.save() - this.headers.set('Authorization', `${this.user.getTokenType()} ${this.user.getAccessToken()}`) + this.userTokens.accessToken = obj.access_token + this.userTokens.refreshToken = obj.refresh_token + this.userTokens.save() + + this.setHeadersFromTokens() + resolve() }) .catch((refreshTokenError: any) => { @@ -165,7 +169,7 @@ export class PeerTubeEmbed { async init () { try { - this.user = PureAuthUser.load() + this.userTokens = Tokens.load() await this.initCore() } catch (e) { console.error(e) @@ -218,9 +222,7 @@ export class PeerTubeEmbed { const urlParts = window.location.pathname.split('/') const videoId = urlParts[ urlParts.length - 1 ] - if (this.user) { - this.headers.set('Authorization', `${this.user.getTokenType()} ${this.user.getAccessToken()}`) - } + if (this.userTokens) this.setHeadersFromTokens() const videoPromise = this.loadVideoInfo(videoId) const captionsPromise = this.loadVideoCaptions(videoId) @@ -381,6 +383,10 @@ export class PeerTubeEmbed { private getPlaceholderElement () { return document.getElementById('placeholder-preview') } + + private setHeadersFromTokens () { + this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`) + } } PeerTubeEmbed.main() -- cgit v1.2.3