Skip to content

Commit

Permalink
Merge pull request #261 from ZIMkaRU/feature/add-ability-to-auto-star…
Browse files Browse the repository at this point in the history
…t-sync-after-auto-update-of-electron-app

Add ability to auto start sync after auto-update of electron app
  • Loading branch information
prdn authored Mar 22, 2023
2 parents 0a4d310 + 0552563 commit d33c94a
Show file tree
Hide file tree
Showing 17 changed files with 348 additions and 21 deletions.
28 changes: 28 additions & 0 deletions test/test-cases/api-sync-mode-sqlite-test-cases.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,35 @@ module.exports = (
assert.strictEqual(res.body.result.email, email)
assert.strictEqual(res.body.result.isSubAccount, isSubAccount)
assert.isString(res.body.result.token)
assert.isBoolean(res.body.result.shouldNotSyncOnStartupAfterUpdate)
assert.isNotOk(res.body.result.shouldNotSyncOnStartupAfterUpdate)

auth.token = res.body.result.token
})

it('it should be successfully performed by the updateUser method', async function () {
this.timeout(5000)

const res = await agent
.post(`${basePath}/json-rpc`)
.type('json')
.send({
auth,
method: 'updateUser',
params: {
shouldNotSyncOnStartupAfterUpdate: true
},
id: 5
})
.expect('Content-Type', /json/)
.expect(200)

assert.isObject(res.body)
assert.propertyVal(res.body, 'id', 5)
assert.isBoolean(res.body.result)
assert.isOk(res.body.result)
})

it('it should be successfully performed by the signIn method by token', async function () {
this.timeout(5000)

Expand All @@ -131,6 +156,8 @@ module.exports = (
assert.strictEqual(res.body.result.email, email)
assert.strictEqual(res.body.result.isSubAccount, isSubAccount)
assert.strictEqual(res.body.result.token, auth.token)
assert.isBoolean(res.body.result.shouldNotSyncOnStartupAfterUpdate)
assert.isOk(res.body.result.shouldNotSyncOnStartupAfterUpdate)
})

it('it should not be successfully performed by the signIn method', async function () {
Expand Down Expand Up @@ -328,6 +355,7 @@ module.exports = (
assert.isString(user.email)
assert.isBoolean(user.isSubAccount)
assert.isBoolean(user.isNotProtected)
assert.isBoolean(user.isRestrictedToBeAddedToSubAccount)
assert.isArray(user.subUsers)

user.subUsers.forEach((subUser) => {
Expand Down
9 changes: 9 additions & 0 deletions workers/loc.api/errors/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,14 @@ class SubAccountUpdatingError extends AuthError {
}
}

class UserUpdatingError extends AuthError {
constructor (message = 'ERR_USER_UPDATE_HAS_BEEN_FAILED') {
super(message)

this.statusMessage = 'User update has been failed'
}
}

class UserRemovingError extends AuthError {
constructor (message = 'ERR_USER_REMOVE_HAS_BEEN_FAILED') {
super(message)
Expand Down Expand Up @@ -235,6 +243,7 @@ module.exports = {
MigrationLaunchingError,
SubAccountCreatingError,
SubAccountUpdatingError,
UserUpdatingError,
UserRemovingError,
UserWasPreviouslyStoredInDbError,
SubAccountLedgersBalancesRecalcError,
Expand Down
22 changes: 22 additions & 0 deletions workers/loc.api/process.message.manager/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,28 @@ class ProcessMessageManager {
{ backupFilesMetadata }
)
}

async [PROCESS_STATES.REQUEST_UPDATE_USERS_SYNC_ON_STARTUP_REQUIRED_STATE] (err, state, data) {
if (err) {
this.logger.debug('[Users sync on startup required state has not been updated]')
this.logger.error(err)

this.sendState(
PROCESS_MESSAGES.RESPONSE_UPDATE_USERS_SYNC_ON_STARTUP_REQUIRED_STATE,
{ err }
)

return
}

const isDone = await this.dao
.updateUsersSyncOnStartupRequiredState()

this.sendState(
PROCESS_MESSAGES.RESPONSE_UPDATE_USERS_SYNC_ON_STARTUP_REQUIRED_STATE,
{ isDone }
)
}
}

decorateInjectable(ProcessMessageManager, depsTypes)
Expand Down
4 changes: 3 additions & 1 deletion workers/loc.api/process.message.manager/process.messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,7 @@ module.exports = {
REQUEST_MIGRATION_HAS_FAILED_WHAT_SHOULD_BE_DONE: 'request:migration-has-failed:what-should-be-done',
REQUEST_SHOULD_ALL_TABLES_BE_REMOVED: 'request:should-all-tables-be-removed',

RESPONSE_GET_BACKUP_FILES_METADATA: 'response:get-backup-files-metadata'
RESPONSE_GET_BACKUP_FILES_METADATA: 'response:get-backup-files-metadata',

RESPONSE_UPDATE_USERS_SYNC_ON_STARTUP_REQUIRED_STATE: 'response:update-users-sync-on-startup-required-state'
}
4 changes: 3 additions & 1 deletion workers/loc.api/process.message.manager/process.states.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,7 @@ module.exports = {

RESPONSE_MIGRATION_HAS_FAILED_WHAT_SHOULD_BE_DONE: 'response:migration-has-failed:what-should-be-done',

REQUEST_GET_BACKUP_FILES_METADATA: 'request:get-backup-files-metadata'
REQUEST_GET_BACKUP_FILES_METADATA: 'request:get-backup-files-metadata',

REQUEST_UPDATE_USERS_SYNC_ON_STARTUP_REQUIRED_STATE: 'request:update-users-sync-on-startup-required-state'
}
38 changes: 36 additions & 2 deletions workers/loc.api/service.report.framework.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,36 @@ class FrameworkReportService extends ReportService {
}

signIn (space, args, cb) {
return this._responder(() => {
return this._authenticator.signIn(args)
return this._responder(async () => {
const {
_id,
email,
isSubAccount,
token,
shouldNotSyncOnStartupAfterUpdate,
isSyncOnStartupRequired
} = await this._authenticator.signIn(
args,
{ isReturnedUser: true }
)

if (
!shouldNotSyncOnStartupAfterUpdate &&
isSyncOnStartupRequired
) {
await this._sync.start({
syncColls: this._ALLOWED_COLLS.ALL,
isSolveAfterRedirToApi: true,
ownerUserId: _id
})
}

return {
email,
isSubAccount,
token,
shouldNotSyncOnStartupAfterUpdate
}
}, 'signIn', args, cb)
}

Expand Down Expand Up @@ -161,6 +189,12 @@ class FrameworkReportService extends ReportService {
}, 'removeUser', args, cb)
}

updateUser (space, args, cb) {
return this._responder(() => {
return this._authenticator.updateUser(args)
}, 'updateUser', args, cb)
}

createSubAccount (space, args, cb) {
return this._responder(() => {
checkParams(args, 'paramsSchemaForCreateSubAccount')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ module.exports = (session, isReturnedPassword) => {
'isSubUser',
'subUsers',
'token',
'shouldNotSyncOnStartupAfterUpdate',
'isSyncOnStartupRequired',
...passwordProp
]
const { subUsers: reqSubUsers } = { ...session }
Expand Down
84 changes: 81 additions & 3 deletions workers/loc.api/sync/authenticator/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict'

const { v4: uuidv4 } = require('uuid')
const { pick } = require('lodash')
const {
AuthError
} = require('bfx-report/workers/loc.api/errors')
Expand All @@ -13,6 +14,7 @@ const {
isSubAccountApiKeys
} = require('../../helpers')
const {
UserUpdatingError,
UserRemovingError,
UserWasPreviouslyStoredInDbError,
AuthTokenGenerationError
Expand Down Expand Up @@ -187,7 +189,9 @@ class Authenticator {
isSubAccount: serializeVal(isSubAccount),
isSubUser: serializeVal(isSubUser),
passwordHash,
isNotProtected: serializeVal(isNotProtected)
isNotProtected: serializeVal(isNotProtected),
shouldNotSyncOnStartupAfterUpdate: 0,
isSyncOnStartupRequired: 0
},
{ isNotInTrans, withWorkerThreads, doNotQueueQuery }
)
Expand Down Expand Up @@ -264,7 +268,9 @@ class Authenticator {
authToken,
apiKey,
apiSecret,
password
password,
shouldNotSyncOnStartupAfterUpdate,
isSyncOnStartupRequired
} = user ?? {}

let newAuthToken = null
Expand Down Expand Up @@ -391,7 +397,9 @@ class Authenticator {
...returnedUser,
email: emailFromApi,
isSubAccount: isSubAccountFromDb,
token: createdToken
token: createdToken,
shouldNotSyncOnStartupAfterUpdate,
isSyncOnStartupRequired
}
}

Expand Down Expand Up @@ -938,6 +946,76 @@ class Authenticator {
return true
}

async updateUser (args, opts) {
const {
email,
password: userPwd,
isSubAccount,
token
} = args?.auth ?? {}
const freshUserData = pick(
args?.params,
[
'shouldNotSyncOnStartupAfterUpdate',
'isSyncOnStartupRequired'
]
)
const {
isNotInTrans = false,
doNotQueueQuery = false,
withWorkerThreads = false
} = opts ?? {}

const {
_id,
email: emailFromDb
} = await this.verifyUser(
{
auth: {
email,
password: userPwd,
isSubAccount,
token
}
},
{
isNotInTrans,
withWorkerThreads,
doNotQueueQuery
}
)

const res = await this.dao.updateCollBy(
this.TABLES_NAMES.USERS,
{ _id, email: emailFromDb },
freshUserData,
{ withWorkerThreads, doNotQueueQuery }
)

if (res && res.changes < 1) {
throw new UserUpdatingError()
}

const existedToken = (
token &&
typeof token === 'string'
)
? token
: this.getUserSessionByEmail({ email, isSubAccount })?.token

if (
!existedToken ||
typeof existedToken !== 'string'
) {
return true
}

const session = this.userSessions.get(existedToken)
Object.assign(session, freshUserData)

return true
}

setUserSession (user) {
const {
token,
Expand Down
24 changes: 24 additions & 0 deletions workers/loc.api/sync/dao/dao.better.sqlite.js
Original file line number Diff line number Diff line change
Expand Up @@ -953,6 +953,30 @@ class BetterSqliteDAO extends DAO {
}, { withWorkerThreads: true })
}

/**
* @override
*/
async updateUsersSyncOnStartupRequiredState (opts) {
const {
doNotQueueQuery = false,
withWorkerThreads = false
} = opts ?? {}

await this.updateCollBy(
this.TABLES_NAMES.USERS,
{
$or: {
$isNull: 'shouldNotSyncOnStartupAfterUpdate',
$eq: { shouldNotSyncOnStartupAfterUpdate: 0 }
}
},
{ isSyncOnStartupRequired: 1 },
{ withWorkerThreads, doNotQueueQuery }
)

return true
}

/**
* @override
*/
Expand Down
5 changes: 5 additions & 0 deletions workers/loc.api/sync/dao/dao.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,11 @@ class DAO {
*/
async getUsers () { throw new ImplementationError() }

/**
* @abstract
*/
async updateUsersSyncOnStartupRequiredState () { throw new ImplementationError() }

/**
* @abstract
*/
Expand Down
1 change: 1 addition & 0 deletions workers/loc.api/sync/dao/db-migrations/db.migrator.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ class DbMigrator {

await this.dbBackupManager.backupDb({ currVer, supportedVer })
await this.migrate(versions, isDown)
await this.dao.updateUsersSyncOnStartupRequiredState()
}
}

Expand Down
Loading

0 comments on commit d33c94a

Please sign in to comment.