Cleanup tokens logic in embed

This commit is contained in:
Chocobozzz 2020-08-06 15:25:19 +02:00 committed by Chocobozzz
parent a02b93ce75
commit a4ff3100d3
12 changed files with 199 additions and 214 deletions

View File

@ -7,6 +7,7 @@ import { VideoPlaylist } from '@app/shared/shared-video-playlist'
import { I18n } from '@ngx-translate/i18n-polyfill' import { I18n } from '@ngx-translate/i18n-polyfill'
import { RecommendationInfo } from './recommendation-info.model' import { RecommendationInfo } from './recommendation-info.model'
import { RecommendedVideosStore } from './recommended-videos.store' import { RecommendedVideosStore } from './recommended-videos.store'
import { UserLocalStorageKeys } from '@root-helpers/users'
@Component({ @Component({
selector: 'my-recommended-videos', selector: 'my-recommended-videos',
@ -48,9 +49,12 @@ export class RecommendedVideosComponent implements OnInit, OnChanges {
if (this.authService.isLoggedIn()) { if (this.authService.isLoggedIn()) {
this.autoPlayNextVideo = this.authService.getUser().autoPlayNextVideo this.autoPlayNextVideo = this.authService.getUser().autoPlayNextVideo
} else { } else {
this.autoPlayNextVideo = this.sessionStorageService.getItem(User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true' || false this.autoPlayNextVideo = this.sessionStorageService.getItem(UserLocalStorageKeys.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
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.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 () { 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()) { if (this.authService.isLoggedIn()) {
const details = { const details = {

View File

@ -1,18 +1,22 @@
import { Observable, of } from 'rxjs' import { Observable, of } from 'rxjs'
import { map } from 'rxjs/operators' import { map } from 'rxjs/operators'
import { User } from '@app/core/users/user.model' 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 { hasUserRight } from '@shared/core-utils/users'
import { import {
MyUser as ServerMyUserModel, MyUser as ServerMyUserModel,
MyUserSpecialPlaylist, MyUserSpecialPlaylist,
NSFWPolicyType,
User as ServerUserModel, User as ServerUserModel,
UserRight, UserRight,
UserRole, UserRole,
UserVideoQuota UserVideoQuota
} from '@shared/models' } from '@shared/models'
import { TokenOptions, Tokens } from '@root-helpers/pure-auth-user.model'
export class AuthUser extends User implements ServerMyUserModel { export class AuthUser extends User implements ServerMyUserModel {
tokens: Tokens tokens: Tokens
@ -21,31 +25,16 @@ export class AuthUser extends User implements ServerMyUserModel {
canSeeVideosLink = true canSeeVideosLink = true
static load () { static load () {
const usernameLocalStorage = peertubeLocalStorage.getItem(this.KEYS.USERNAME) const userInfo = getUserInfoFromLocalStorage()
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()
)
}
return null if (!userInfo) return null
return new AuthUser(userInfo, Tokens.load())
} }
static flush () { static flush () {
peertubeLocalStorage.removeItem(this.KEYS.USERNAME) flushUserInfoFromLocalStorage()
peertubeLocalStorage.removeItem(this.KEYS.ID)
peertubeLocalStorage.removeItem(this.KEYS.ROLE)
peertubeLocalStorage.removeItem(this.KEYS.EMAIL)
Tokens.flush() Tokens.flush()
} }
@ -87,13 +76,16 @@ export class AuthUser extends User implements ServerMyUserModel {
} }
save () { save () {
peertubeLocalStorage.setItem(AuthUser.KEYS.ID, this.id.toString()) saveUserInfoIntoLocalStorage({
peertubeLocalStorage.setItem(AuthUser.KEYS.USERNAME, this.username) id: this.id,
peertubeLocalStorage.setItem(AuthUser.KEYS.EMAIL, this.email) username: this.username,
peertubeLocalStorage.setItem(AuthUser.KEYS.ROLE, this.role.toString()) email: this.email,
peertubeLocalStorage.setItem(AuthUser.KEYS.NSFW_POLICY, this.nsfwPolicy.toString()) role: this.role,
peertubeLocalStorage.setItem(AuthUser.KEYS.WEBTORRENT_ENABLED, JSON.stringify(this.webTorrentEnabled)) nsfwPolicy: this.nsfwPolicy,
peertubeLocalStorage.setItem(AuthUser.KEYS.AUTO_PLAY_VIDEO, JSON.stringify(this.autoPlayVideo)) webTorrentEnabled: this.webTorrentEnabled,
autoPlayVideo: this.autoPlayVideo
})
this.tokens.save() this.tokens.save()
} }

View File

@ -1,13 +1,13 @@
import { first } from 'rxjs/operators' import { first } from 'rxjs/operators'
import { Injectable } from '@angular/core' 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 { AuthService } from '../auth'
import { PluginService } from '../plugins/plugin.service' import { PluginService } from '../plugins/plugin.service'
import { ServerService } from '../server' import { ServerService } from '../server'
import { LocalStorageService } from '../wrappers/storage.service'
import { User } from '../users/user.model'
import { UserService } from '../users/user.service' import { UserService } from '../users/user.service'
import { ServerConfig, ServerConfigTheme } from '@shared/models' import { LocalStorageService } from '../wrappers/storage.service'
import { environment } from '../../../environments/environment'
@Injectable() @Injectable()
export class ThemeService { export class ThemeService {
@ -111,9 +111,9 @@ export class ThemeService {
this.pluginService.reloadLoadedScopes() 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 { } else {
this.localStorageService.removeItem(User.KEYS.LAST_ACTIVE_THEME, false) this.localStorageService.removeItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, false)
} }
this.oldThemeName = currentTheme this.oldThemeName = currentTheme
@ -127,7 +127,7 @@ export class ThemeService {
if (!this.auth.isLoggedIn()) { if (!this.auth.isLoggedIn()) {
this.updateCurrentTheme() this.updateCurrentTheme()
this.localStorageService.watch([ User.KEYS.THEME ]).subscribe( this.localStorageService.watch([ UserLocalStorageKeys.THEME ]).subscribe(
() => this.updateCurrentTheme() () => this.updateCurrentTheme()
) )
} }
@ -138,7 +138,7 @@ export class ThemeService {
} }
private loadAndSetFromLocalStorage () { private loadAndSetFromLocalStorage () {
const lastActiveThemeString = this.localStorageService.getItem(User.KEYS.LAST_ACTIVE_THEME) const lastActiveThemeString = this.localStorageService.getItem(UserLocalStorageKeys.LAST_ACTIVE_THEME)
if (!lastActiveThemeString) return if (!lastActiveThemeString) return
try { try {

View File

@ -10,11 +10,8 @@ import {
UserRole, UserRole,
VideoChannel VideoChannel
} from '@shared/models' } from '@shared/models'
import { UserKeys } from '@root-helpers/user-keys'
export class User implements UserServerModel { export class User implements UserServerModel {
static KEYS = UserKeys
id: number id: number
username: string username: string
email: string email: string

View File

@ -1,4 +1,3 @@
import { has } from 'lodash-es'
import { BytesPipe } from 'ngx-pipes' import { BytesPipe } from 'ngx-pipes'
import { SortMeta } from 'primeng/api' import { SortMeta } from 'primeng/api'
import { from, Observable, of } from 'rxjs' import { from, Observable, of } from 'rxjs'
@ -7,6 +6,7 @@ import { HttpClient, HttpParams } from '@angular/common/http'
import { Injectable } from '@angular/core' import { Injectable } from '@angular/core'
import { AuthService } from '@app/core/auth' import { AuthService } from '@app/core/auth'
import { I18n } from '@ngx-translate/i18n-polyfill' import { I18n } from '@ngx-translate/i18n-polyfill'
import { UserLocalStorageKeys } from '@root-helpers/users'
import { import {
Avatar, Avatar,
NSFWPolicyType, NSFWPolicyType,
@ -81,37 +81,28 @@ export class UserService {
} }
updateMyAnonymousProfile (profile: UserUpdateMe) { 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)),
// session storage keys
autoPlayNextVideo: (val: boolean) =>
this.sessionStorageService.setItem(User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO, String(val))
}
for (const key of Object.keys(profile)) {
try { try {
if (has(supportedKeys, key)) supportedKeys[key](profile[key]) this.localStorageService.setItem(UserLocalStorageKeys.NSFW_POLICY, profile.nsfwPolicy)
this.localStorageService.setItem(UserLocalStorageKeys.WEBTORRENT_ENABLED, profile.webTorrentEnabled)
this.localStorageService.setItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO, profile.autoPlayNextVideo)
this.localStorageService.setItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST, profile.autoPlayNextVideoPlaylist)
this.localStorageService.setItem(UserLocalStorageKeys.THEME, profile.theme)
this.localStorageService.setItem(UserLocalStorageKeys.VIDEO_LANGUAGES, profile.videoLanguages)
} catch (err) { } catch (err) {
console.error(`Cannot set item ${key} in localStorage. Likely due to a value impossible to stringify.`, err) console.error(`Cannot set item in localStorage. Likely due to a value impossible to stringify.`, err)
}
} }
} }
listenAnonymousUpdate () { listenAnonymousUpdate () {
return this.localStorageService.watch([ return this.localStorageService.watch([
User.KEYS.NSFW_POLICY, UserLocalStorageKeys.NSFW_POLICY,
User.KEYS.WEBTORRENT_ENABLED, UserLocalStorageKeys.WEBTORRENT_ENABLED,
User.KEYS.AUTO_PLAY_VIDEO, UserLocalStorageKeys.AUTO_PLAY_VIDEO,
User.KEYS.AUTO_PLAY_VIDEO_PLAYLIST, UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST,
User.KEYS.THEME, UserLocalStorageKeys.THEME,
User.KEYS.VIDEO_LANGUAGES UserLocalStorageKeys.VIDEO_LANGUAGES
]).pipe( ]).pipe(
throttleTime(200), throttleTime(200),
filter(() => this.authService.isLoggedIn() !== true), filter(() => this.authService.isLoggedIn() !== true),
@ -269,7 +260,7 @@ export class UserService {
let videoLanguages: string[] let videoLanguages: string[]
try { try {
videoLanguages = JSON.parse(this.localStorageService.getItem(User.KEYS.VIDEO_LANGUAGES)) videoLanguages = JSON.parse(this.localStorageService.getItem(UserLocalStorageKeys.VIDEO_LANGUAGES))
} catch (err) { } catch (err) {
videoLanguages = null videoLanguages = null
console.error('Cannot parse desired video languages from localStorage.', err) console.error('Cannot parse desired video languages from localStorage.', err)
@ -277,16 +268,16 @@ export class UserService {
return new User({ return new User({
// local storage keys // local storage keys
nsfwPolicy: this.localStorageService.getItem(User.KEYS.NSFW_POLICY) as NSFWPolicyType, nsfwPolicy: this.localStorageService.getItem(UserLocalStorageKeys.NSFW_POLICY) as NSFWPolicyType,
webTorrentEnabled: this.localStorageService.getItem(User.KEYS.WEBTORRENT_ENABLED) !== 'false', webTorrentEnabled: this.localStorageService.getItem(UserLocalStorageKeys.WEBTORRENT_ENABLED) !== 'false',
theme: this.localStorageService.getItem(User.KEYS.THEME) || 'instance-default', theme: this.localStorageService.getItem(UserLocalStorageKeys.THEME) || 'instance-default',
videoLanguages, videoLanguages,
autoPlayNextVideoPlaylist: this.localStorageService.getItem(User.KEYS.AUTO_PLAY_VIDEO_PLAYLIST) !== 'false', autoPlayNextVideoPlaylist: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST) !== 'false',
autoPlayVideo: this.localStorageService.getItem(User.KEYS.AUTO_PLAY_VIDEO) === 'true', autoPlayVideo: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO) === 'true',
// session storage keys // 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'
}) })
} }

View File

@ -1,4 +1,3 @@
export * from './users'
export * from './peertube-web-storage' export * from './peertube-web-storage'
export * from './utils' export * from './utils'
export * from './user-keys'
export * from './pure-auth-user.model'

View File

@ -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<ServerMyUserModel>, 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()
}
}

View File

@ -0,0 +1,3 @@
export * from './user-local-storage-keys'
export * from './user-local-storage-manager'
export * from './user-tokens'

View File

@ -1,4 +1,4 @@
export const UserKeys = { export const UserLocalStorageKeys = {
ID: 'id', ID: 'id',
ROLE: 'role', ROLE: 'role',
EMAIL: 'email', EMAIL: 'email',

View File

@ -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
}

View File

@ -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)
}
}

View File

@ -1,6 +1,7 @@
import './embed.scss' import './embed.scss'
import videojs from 'video.js' 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 { peertubeTranslate } from '../../../../shared/core-utils/i18n'
import { import {
ResultList, ResultList,
@ -39,7 +40,7 @@ export class PeerTubeEmbed {
mode: PlayerMode mode: PlayerMode
scope = 'peertube' scope = 'peertube'
user: PureAuthUser userTokens: Tokens
headers = new Headers() headers = new Headers()
LOCAL_STORAGE_OAUTH_CLIENT_KEYS = { LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
CLIENT_ID: 'client_id', CLIENT_ID: 'client_id',
@ -74,7 +75,7 @@ export class PeerTubeEmbed {
const headers = new Headers() const headers = new Headers()
headers.set('Content-Type', 'application/x-www-form-urlencoded') headers.set('Content-Type', 'application/x-www-form-urlencoded')
const data = { const data = {
refresh_token: this.user.getRefreshToken(), refresh_token: this.userTokens.refreshToken,
client_id: clientId, client_id: clientId,
client_secret: clientSecret, client_secret: clientSecret,
response_type: 'code', response_type: 'code',
@ -88,9 +89,12 @@ export class PeerTubeEmbed {
}) })
.then(res => res.json()) .then(res => res.json())
.then((obj: UserRefreshToken) => { .then((obj: UserRefreshToken) => {
this.user.refreshTokens(obj.access_token, obj.refresh_token) this.userTokens.accessToken = obj.access_token
this.user.save() this.userTokens.refreshToken = obj.refresh_token
this.headers.set('Authorization', `${this.user.getTokenType()} ${this.user.getAccessToken()}`) this.userTokens.save()
this.setHeadersFromTokens()
resolve() resolve()
}) })
.catch((refreshTokenError: any) => { .catch((refreshTokenError: any) => {
@ -165,7 +169,7 @@ export class PeerTubeEmbed {
async init () { async init () {
try { try {
this.user = PureAuthUser.load() this.userTokens = Tokens.load()
await this.initCore() await this.initCore()
} catch (e) { } catch (e) {
console.error(e) console.error(e)
@ -218,9 +222,7 @@ export class PeerTubeEmbed {
const urlParts = window.location.pathname.split('/') const urlParts = window.location.pathname.split('/')
const videoId = urlParts[ urlParts.length - 1 ] const videoId = urlParts[ urlParts.length - 1 ]
if (this.user) { if (this.userTokens) this.setHeadersFromTokens()
this.headers.set('Authorization', `${this.user.getTokenType()} ${this.user.getAccessToken()}`)
}
const videoPromise = this.loadVideoInfo(videoId) const videoPromise = this.loadVideoInfo(videoId)
const captionsPromise = this.loadVideoCaptions(videoId) const captionsPromise = this.loadVideoCaptions(videoId)
@ -381,6 +383,10 @@ export class PeerTubeEmbed {
private getPlaceholderElement () { private getPlaceholderElement () {
return document.getElementById('placeholder-preview') return document.getElementById('placeholder-preview')
} }
private setHeadersFromTokens () {
this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
}
} }
PeerTubeEmbed.main() PeerTubeEmbed.main()