import { eventChannel, END, EventChannel } from 'redux-saga'; import { put, call, take, select, all, takeLatest } from 'redux-saga/effects'; import { ApiResponse } from 'apisauce'; import randomString from 'random-string'; import CONFIG from '../config/env'; import { apiInstance } from '../services/api'; import { EncryptionManager } from '../services/encryption'; import { Keychain } from '../services/keychain'; import { usersActionCreators, usersActionTypes, UsersSelectors } from '../redux/users'; import { authActionCreators, authActionTypes, IGetSessionAction, IVerifyUserSessionAction, } from '../redux/auth'; import { IService, IServiceAccounts } from '../utils/types'; function initSocketClient() { return new Promise((resolve, reject) => { const client = new WebSocket(CONFIG.WS_URL); client.onopen = () => resolve(client); client.onerror = (error) => reject(error); }); } function initSocketEventChannel(client: WebSocket) { return eventChannel((emit) => { client.onmessage = (event) => emit(event.data); client.onclose = () => emit(END); return () => client.close(); }); } function* listenAuthSocketEvent(socket: WebSocket) { const channel: EventChannel = yield call(initSocketEventChannel, socket); const payload: string = yield take(channel); return JSON.parse(payload); } function* watchGetSession({ sessionId }: IGetSessionAction) { // TODO: typing const response: ApiResponse = yield call(apiInstance.getSession, sessionId); if (response.ok && response.data) { const { isNewUser, username, service } = response.data; const users: IServiceAccounts = yield select(UsersSelectors.selectUsers) || {}; const userKeys: string[] = yield call(Object.keys, users[service._id] || {}); if (isNewUser) { // isNewUser: sign up flow yield put(authActionCreators.getSessionSuccess(isNewUser, service)); yield put(usersActionCreators.getServiceSuccess(service)); yield put(usersActionCreators.createServiceUser(service._id, username)); const { user } = yield take(usersActionTypes.CREATE_SERVICE_USER_SUCCESS); yield put(authActionCreators.verifyUserSession(user.userId, sessionId)); } else { // !isNewUser: sign in flow // We have at least one saved user if (userKeys.length) { yield put(authActionCreators.getSessionSuccess(isNewUser, service)); yield put(usersActionCreators.getServiceSuccess(service)); // Automatic choise if (userKeys.length === 1) { yield put(authActionCreators.verifyUserSession(userKeys[0], sessionId)); } } else { yield put( authActionCreators.getSessionFailure( `Please register with ${(service as IService).name || 'the service'} and try again`, ), ); } } } else { yield put(authActionCreators.getSessionFailure('Invalid or expired session')); } } function* watchVerifyUserSession({ userId, sessionId }: IVerifyUserSessionAction) { const privateKey: string = yield call(Keychain.getPrivateKey); const someRandomString: string = yield call(randomString, { length: 32 }); const secret: string = yield call(EncryptionManager.encryptAES, someRandomString, privateKey); const socket: WebSocket = yield call(initSocketClient); // TODO: typing const crypto: { sk: any; pk: any } = yield call(EncryptionManager.generateCryptoBox); socket.send( JSON.stringify({ sessionId, sessionKey: secret, // TODO: move to constants action: 'SESSION_VALIDATE', }), ); const event: { publicKey: string } = yield call(listenAuthSocketEvent, socket); if (event) { const decryptedUserId: string = yield call(EncryptionManager.decryptAES, userId, privateKey); if (event.publicKey) { const encrypt: { cipher: any; nonce: any } = yield call( EncryptionManager.encryptSodium, decryptedUserId, event.publicKey, crypto.sk, ); const { cipher, nonce } = encrypt; const aproveAction = { cipher, nonce, publicKey: crypto.pk, // TODO: move to constants action: 'SESSION_VERIFY_APPROVE', }; socket.send(JSON.stringify(aproveAction)); } else { const aproveAction = { userId: decryptedUserId, action: 'SESSION_VERIFY_APPROVE' }; socket.send(JSON.stringify(aproveAction)); } yield put(authActionCreators.verifyUserSessionSuccess()); } else { yield put(authActionCreators.verifyUserSessionFailure('Something went wrong')); } } export function* authSaga() { yield all([ takeLatest(authActionTypes.GET_SESSION, watchGetSession), takeLatest( authActionTypes.VERIFY_USER_SESSION, watchVerifyUserSession, ), ]); }