auth.service.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import { Hotkey, HotkeysService } from 'angular2-hotkeys'
  2. import { Observable, ReplaySubject, Subject, throwError as observableThrowError } from 'rxjs'
  3. import { catchError, map, mergeMap, share, tap } from 'rxjs/operators'
  4. import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'
  5. import { Injectable } from '@angular/core'
  6. import { Router } from '@angular/router'
  7. import { Notifier } from '@app/core/notification/notifier.service'
  8. import { objectToUrlEncoded, peertubeLocalStorage } from '@root-helpers/index'
  9. import { I18n } from '@ngx-translate/i18n-polyfill'
  10. import { MyUser as UserServerModel, OAuthClientLocal, User, UserLogin, UserRefreshToken } from '@shared/models'
  11. import { environment } from '../../../environments/environment'
  12. import { RestExtractor } from '../rest/rest-extractor.service'
  13. import { AuthStatus } from './auth-status.model'
  14. import { AuthUser } from './auth-user.model'
  15. interface UserLoginWithUsername extends UserLogin {
  16. access_token: string
  17. refresh_token: string
  18. token_type: string
  19. username: string
  20. }
  21. type UserLoginWithUserInformation = UserLoginWithUsername & User
  22. @Injectable()
  23. export class AuthService {
  24. private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
  25. private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token'
  26. private static BASE_REVOKE_TOKEN_URL = environment.apiUrl + '/api/v1/users/revoke-token'
  27. private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
  28. private static LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
  29. CLIENT_ID: 'client_id',
  30. CLIENT_SECRET: 'client_secret'
  31. }
  32. loginChangedSource: Observable<AuthStatus>
  33. userInformationLoaded = new ReplaySubject<boolean>(1)
  34. hotkeys: Hotkey[]
  35. private clientId: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
  36. private clientSecret: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
  37. private loginChanged: Subject<AuthStatus>
  38. private user: AuthUser = null
  39. private refreshingTokenObservable: Observable<any>
  40. constructor (
  41. private http: HttpClient,
  42. private notifier: Notifier,
  43. private hotkeysService: HotkeysService,
  44. private restExtractor: RestExtractor,
  45. private router: Router,
  46. private i18n: I18n
  47. ) {
  48. this.loginChanged = new Subject<AuthStatus>()
  49. this.loginChangedSource = this.loginChanged.asObservable()
  50. // Return null if there is nothing to load
  51. this.user = AuthUser.load()
  52. // Set HotKeys
  53. this.hotkeys = [
  54. new Hotkey('m s', (event: KeyboardEvent): boolean => {
  55. this.router.navigate([ '/videos/subscriptions' ])
  56. return false
  57. }, undefined, this.i18n('Go to my subscriptions')),
  58. new Hotkey('m v', (event: KeyboardEvent): boolean => {
  59. this.router.navigate([ '/my-account/videos' ])
  60. return false
  61. }, undefined, this.i18n('Go to my videos')),
  62. new Hotkey('m i', (event: KeyboardEvent): boolean => {
  63. this.router.navigate([ '/my-account/video-imports' ])
  64. return false
  65. }, undefined, this.i18n('Go to my imports')),
  66. new Hotkey('m c', (event: KeyboardEvent): boolean => {
  67. this.router.navigate([ '/my-account/video-channels' ])
  68. return false
  69. }, undefined, this.i18n('Go to my channels'))
  70. ]
  71. }
  72. loadClientCredentials () {
  73. // Fetch the client_id/client_secret
  74. this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
  75. .pipe(catchError(res => this.restExtractor.handleError(res)))
  76. .subscribe(
  77. res => {
  78. this.clientId = res.client_id
  79. this.clientSecret = res.client_secret
  80. peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID, this.clientId)
  81. peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET, this.clientSecret)
  82. console.log('Client credentials loaded.')
  83. },
  84. error => {
  85. let errorMessage = error.message
  86. if (error.status === 403) {
  87. errorMessage = this.i18n('Cannot retrieve OAuth Client credentials: {{errorText}}.\n', { errorText: error.text })
  88. errorMessage += this.i18n(
  89. 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
  90. )
  91. }
  92. // We put a bigger timeout: this is an important message
  93. this.notifier.error(errorMessage, this.i18n('Error'), 7000)
  94. }
  95. )
  96. }
  97. getRefreshToken () {
  98. if (this.user === null) return null
  99. return this.user.getRefreshToken()
  100. }
  101. getRequestHeaderValue () {
  102. const accessToken = this.getAccessToken()
  103. if (accessToken === null) return null
  104. return `${this.getTokenType()} ${accessToken}`
  105. }
  106. getAccessToken () {
  107. if (this.user === null) return null
  108. return this.user.getAccessToken()
  109. }
  110. getTokenType () {
  111. if (this.user === null) return null
  112. return this.user.getTokenType()
  113. }
  114. getUser () {
  115. return this.user
  116. }
  117. isLoggedIn () {
  118. return !!this.getAccessToken()
  119. }
  120. login (username: string, password: string, token?: string) {
  121. // Form url encoded
  122. const body = {
  123. client_id: this.clientId,
  124. client_secret: this.clientSecret,
  125. response_type: 'code',
  126. grant_type: 'password',
  127. scope: 'upload',
  128. username,
  129. password
  130. }
  131. if (token) Object.assign(body, { externalAuthToken: token })
  132. const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
  133. return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
  134. .pipe(
  135. map(res => Object.assign(res, { username })),
  136. mergeMap(res => this.mergeUserInformation(res)),
  137. map(res => this.handleLogin(res)),
  138. catchError(res => this.restExtractor.handleError(res))
  139. )
  140. }
  141. logout () {
  142. const authHeaderValue = this.getRequestHeaderValue()
  143. const headers = new HttpHeaders().set('Authorization', authHeaderValue)
  144. this.http.post<void>(AuthService.BASE_REVOKE_TOKEN_URL, {}, { headers })
  145. .subscribe(
  146. () => { /* nothing to do */ },
  147. err => console.error(err)
  148. )
  149. this.user = null
  150. AuthUser.flush()
  151. this.setStatus(AuthStatus.LoggedOut)
  152. this.hotkeysService.remove(this.hotkeys)
  153. }
  154. refreshAccessToken () {
  155. if (this.refreshingTokenObservable) return this.refreshingTokenObservable
  156. console.log('Refreshing token...')
  157. const refreshToken = this.getRefreshToken()
  158. // Form url encoded
  159. const body = new HttpParams().set('refresh_token', refreshToken)
  160. .set('client_id', this.clientId)
  161. .set('client_secret', this.clientSecret)
  162. .set('response_type', 'code')
  163. .set('grant_type', 'refresh_token')
  164. const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
  165. this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
  166. .pipe(
  167. map(res => this.handleRefreshToken(res)),
  168. tap(() => this.refreshingTokenObservable = null),
  169. catchError(err => {
  170. this.refreshingTokenObservable = null
  171. console.error(err)
  172. console.log('Cannot refresh token -> logout...')
  173. this.logout()
  174. this.router.navigate([ '/login' ])
  175. return observableThrowError({
  176. error: this.i18n('You need to reconnect.')
  177. })
  178. }),
  179. share()
  180. )
  181. return this.refreshingTokenObservable
  182. }
  183. refreshUserInformation () {
  184. const obj: UserLoginWithUsername = {
  185. access_token: this.user.getAccessToken(),
  186. refresh_token: null,
  187. token_type: this.user.getTokenType(),
  188. username: this.user.username
  189. }
  190. this.mergeUserInformation(obj)
  191. .subscribe(
  192. res => {
  193. this.user.patch(res)
  194. this.user.save()
  195. this.userInformationLoaded.next(true)
  196. }
  197. )
  198. }
  199. private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
  200. // User is not loaded yet, set manually auth header
  201. const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
  202. return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
  203. .pipe(map(res => Object.assign(obj, res)))
  204. }
  205. private handleLogin (obj: UserLoginWithUserInformation) {
  206. const hashTokens = {
  207. accessToken: obj.access_token,
  208. tokenType: obj.token_type,
  209. refreshToken: obj.refresh_token
  210. }
  211. this.user = new AuthUser(obj, hashTokens)
  212. this.user.save()
  213. this.setStatus(AuthStatus.LoggedIn)
  214. this.userInformationLoaded.next(true)
  215. this.hotkeysService.add(this.hotkeys)
  216. }
  217. private handleRefreshToken (obj: UserRefreshToken) {
  218. this.user.refreshTokens(obj.access_token, obj.refresh_token)
  219. this.user.save()
  220. }
  221. private setStatus (status: AuthStatus) {
  222. this.loginChanged.next(status)
  223. }
  224. }