You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AuthHandler.js 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /* global APP, config, JitsiMeetJS, Promise */
  2. import { openConnection } from '../../../connection';
  3. import { setJWT } from '../../../react/features/base/jwt';
  4. import {
  5. JitsiConnectionErrors
  6. } from '../../../react/features/base/lib-jitsi-meet';
  7. import UIUtil from '../util/UIUtil';
  8. import LoginDialog from './LoginDialog';
  9. const logger = require('jitsi-meet-logger').getLogger(__filename);
  10. let externalAuthWindow;
  11. let authRequiredDialog;
  12. const isTokenAuthEnabled
  13. = typeof config.tokenAuthUrl === 'string' && config.tokenAuthUrl.length;
  14. const getTokenAuthUrl
  15. = JitsiMeetJS.util.AuthUtil.getTokenAuthUrl.bind(null, config.tokenAuthUrl);
  16. /**
  17. * Authenticate using external service or just focus
  18. * external auth window if there is one already.
  19. *
  20. * @param {JitsiConference} room
  21. * @param {string} [lockPassword] password to use if the conference is locked
  22. */
  23. function doExternalAuth(room, lockPassword) {
  24. if (externalAuthWindow) {
  25. externalAuthWindow.focus();
  26. return;
  27. }
  28. if (room.isJoined()) {
  29. let getUrl;
  30. if (isTokenAuthEnabled) {
  31. getUrl = Promise.resolve(getTokenAuthUrl(room.getName(), true));
  32. initJWTTokenListener(room);
  33. } else {
  34. getUrl = room.getExternalAuthUrl(true);
  35. }
  36. getUrl.then(url => {
  37. externalAuthWindow = LoginDialog.showExternalAuthDialog(
  38. url,
  39. () => {
  40. externalAuthWindow = null;
  41. if (!isTokenAuthEnabled) {
  42. room.join(lockPassword);
  43. }
  44. }
  45. );
  46. });
  47. } else if (isTokenAuthEnabled) {
  48. redirectToTokenAuthService(room.getName());
  49. } else {
  50. room.getExternalAuthUrl().then(UIUtil.redirect);
  51. }
  52. }
  53. /**
  54. * Redirect the user to the token authentication service for the login to be
  55. * performed. Once complete it is expected that the service wil bring the user
  56. * back with "?jwt={the JWT token}" query parameter added.
  57. * @param {string} [roomName] the name of the conference room.
  58. */
  59. function redirectToTokenAuthService(roomName) {
  60. UIUtil.redirect(getTokenAuthUrl(roomName, false));
  61. }
  62. /**
  63. * Initializes 'message' listener that will wait for a JWT token to be received
  64. * from the token authentication service opened in a popup window.
  65. * @param room the name fo the conference room.
  66. */
  67. function initJWTTokenListener(room) {
  68. /**
  69. *
  70. */
  71. function listener({ data, source }) {
  72. if (externalAuthWindow !== source) {
  73. logger.warn('Ignored message not coming '
  74. + 'from external authnetication window');
  75. return;
  76. }
  77. let jwt;
  78. if (data && (jwt = data.jwtToken)) {
  79. logger.info('Received JSON Web Token (JWT):', jwt);
  80. APP.store.dispatch(setJWT(jwt));
  81. const roomName = room.getName();
  82. openConnection({
  83. retry: false,
  84. roomName
  85. }).then(connection => {
  86. // Start new connection
  87. const newRoom = connection.initJitsiConference(
  88. roomName, APP.conference._getConferenceOptions());
  89. // Authenticate from the new connection to get
  90. // the session-ID from the focus, which wil then be used
  91. // to upgrade current connection's user role
  92. newRoom.room.moderator.authenticate()
  93. .then(() => {
  94. connection.disconnect();
  95. // At this point we'll have session-ID stored in
  96. // the settings. It wil be used in the call below
  97. // to upgrade user's role
  98. room.room.moderator.authenticate()
  99. .then(() => {
  100. logger.info('User role upgrade done !');
  101. // eslint-disable-line no-use-before-define
  102. unregister();
  103. })
  104. .catch((err, errCode) => {
  105. logger.error('Authentication failed: ',
  106. err, errCode);
  107. unregister();
  108. });
  109. })
  110. .catch((error, code) => {
  111. unregister();
  112. connection.disconnect();
  113. logger.error(
  114. 'Authentication failed on the new connection',
  115. error, code);
  116. });
  117. }, err => {
  118. unregister();
  119. logger.error('Failed to open new connection', err);
  120. });
  121. }
  122. }
  123. /**
  124. *
  125. */
  126. function unregister() {
  127. window.removeEventListener('message', listener);
  128. }
  129. if (window.addEventListener) {
  130. window.addEventListener('message', listener, false);
  131. }
  132. }
  133. /**
  134. * Authenticate on the server.
  135. * @param {JitsiConference} room
  136. * @param {string} [lockPassword] password to use if the conference is locked
  137. */
  138. function doXmppAuth(room, lockPassword) {
  139. const loginDialog = LoginDialog.showAuthDialog(
  140. /* successCallback */ (id, password) => {
  141. room.authenticateAndUpgradeRole({
  142. id,
  143. password,
  144. roomPassword: lockPassword,
  145. /** Called when the XMPP login succeeds. */
  146. onLoginSuccessful() {
  147. loginDialog.displayConnectionStatus(
  148. 'connection.FETCH_SESSION_ID');
  149. }
  150. })
  151. .then(
  152. /* onFulfilled */ () => {
  153. loginDialog.displayConnectionStatus(
  154. 'connection.GOT_SESSION_ID');
  155. loginDialog.close();
  156. },
  157. /* onRejected */ error => {
  158. logger.error('authenticateAndUpgradeRole failed', error);
  159. const { authenticationError, connectionError } = error;
  160. if (authenticationError) {
  161. loginDialog.displayError(
  162. 'connection.GET_SESSION_ID_ERROR',
  163. { msg: authenticationError });
  164. } else if (connectionError) {
  165. loginDialog.displayError(connectionError);
  166. }
  167. });
  168. },
  169. /* cancelCallback */ () => loginDialog.close());
  170. }
  171. /**
  172. * Authenticate for the conference.
  173. * Uses external service for auth if conference supports that.
  174. * @param {JitsiConference} room
  175. * @param {string} [lockPassword] password to use if the conference is locked
  176. */
  177. function authenticate(room, lockPassword) {
  178. if (isTokenAuthEnabled || room.isExternalAuthEnabled()) {
  179. doExternalAuth(room, lockPassword);
  180. } else {
  181. doXmppAuth(room, lockPassword);
  182. }
  183. }
  184. /**
  185. * De-authenticate local user.
  186. *
  187. * @param {JitsiConference} room
  188. * @param {string} [lockPassword] password to use if the conference is locked
  189. * @returns {Promise}
  190. */
  191. function logout(room) {
  192. return new Promise(resolve => {
  193. room.room.moderator.logout(resolve);
  194. }).then(url => {
  195. // de-authenticate conference on the fly
  196. if (room.isJoined()) {
  197. room.join();
  198. }
  199. return url;
  200. });
  201. }
  202. /**
  203. * Notify user that authentication is required to create the conference.
  204. * @param {JitsiConference} room
  205. * @param {string} [lockPassword] password to use if the conference is locked
  206. */
  207. function requireAuth(room, lockPassword) {
  208. if (authRequiredDialog) {
  209. return;
  210. }
  211. authRequiredDialog = LoginDialog.showAuthRequiredDialog(
  212. room.getName(), authenticate.bind(null, room, lockPassword)
  213. );
  214. }
  215. /**
  216. * Close auth-related dialogs if there are any.
  217. */
  218. function closeAuth() {
  219. if (externalAuthWindow) {
  220. externalAuthWindow.close();
  221. externalAuthWindow = null;
  222. }
  223. if (authRequiredDialog) {
  224. authRequiredDialog.close();
  225. authRequiredDialog = null;
  226. }
  227. }
  228. /**
  229. *
  230. */
  231. function showXmppPasswordPrompt(roomName, connect) {
  232. return new Promise((resolve, reject) => {
  233. const authDialog = LoginDialog.showAuthDialog(
  234. (id, password) => {
  235. connect(id, password, roomName).then(connection => {
  236. authDialog.close();
  237. resolve(connection);
  238. }, err => {
  239. if (err === JitsiConnectionErrors.PASSWORD_REQUIRED) {
  240. authDialog.displayError(err);
  241. } else {
  242. authDialog.close();
  243. reject(err);
  244. }
  245. });
  246. }
  247. );
  248. });
  249. }
  250. /**
  251. * Show Authentication Dialog and try to connect with new credentials.
  252. * If failed to connect because of PASSWORD_REQUIRED error
  253. * then ask for password again.
  254. * @param {string} [roomName] name of the conference room
  255. * @param {function(id, password, roomName)} [connect] function that returns
  256. * a Promise which resolves with JitsiConnection or fails with one of
  257. * JitsiConnectionErrors.
  258. * @returns {Promise<JitsiConnection>}
  259. */
  260. function requestAuth(roomName, connect) {
  261. if (isTokenAuthEnabled) {
  262. // This Promise never resolves as user gets redirected to another URL
  263. return new Promise(() => redirectToTokenAuthService(roomName));
  264. }
  265. return showXmppPasswordPrompt(roomName, connect);
  266. }
  267. export default {
  268. authenticate,
  269. requireAuth,
  270. requestAuth,
  271. closeAuth,
  272. logout
  273. };