Fetch firebase remote config values on first login - firebase

I'm trying to fetch remote config values on first login (and not only after minimumFetchIntervalMillis expires), this is what i do (pseudo):
yield firebaseConfig.setConfigSettings(15 mins)
yield firebaseConfig.setDefaults()
yield firebaseConfig.fetchAndActivate().then(print values)
But i do not get the correct config for the user, just the server default.
Is there a valid way to do that?
I was thinking about setting minimumFetchIntervalMillis to zero on first login and after config was fetched to set it to 15 mins but i'm not sure that's the best approach for this.
Any ideas?

Set the minimumFetchIntervalMillis to 0 for the initial retrieve request if you wish to fetch new configuration data immediately after logging in rather than waiting for the minimumFetchIntervalMillis duration to elapse. This can lead to more requests being sent to the server more often, which could harm the performance of app and raise server expenses.
firebaseConfig.settings.minimumFetchIntervalMillis = 0;
firebaseConfig.fetchAndActivate().then(() => {
console.log(firebaseConfig.getAll());
firebaseConfig.settings.minimumFetchIntervalMillis = 15 * 60 * 1000;
});
The above sample code retrieves the remote configuration with a minimumFetchIntervalMillis of 0, activates it, then outputs the values it has fetched. The minimumFetchIntervalMillis is 15 milliseconds after the initial fetch.

Related

Trigger a remote setTimeout Cloud Function Request

I'm using firebase and would like to update a value no matter what happens using a HttpRequest Cloud function ( connection error, tab or browser closed ).
I thought of a setTimeout but this doesn't solve the issue as if anything happens the request will fail as it is related to client side.
Then my idea was to send the request on a remote server ( a bit like a cron job ) that should perform at a certain delay ( let's say 30 minutes ) but that would cancel the previous request in queue ( based on userID and request path )
How could I achieve that and is this possible?
example:
request number 1 -> www.myrequest with { userUID:1, data:{size:1}}
request time:12:01
request number 2 -> www.myrequest with { userUID:1, data:{size:30}}
request time:12:02
request 2 cancels request 1 and gets executed 30 minutes later

Question about pymodbusTCP server implementaion

We have a simulator(client) and controller(server).
The controller sends a command signal through ModbusTCP to the simulator.
I want to emulate this controller on my computer.
What I have done
For the test, I wrote pymodbus Server script on my pc and pymodbus Client script on another PC. There was no problem to read holding and input register from client pc.
I connected my clinet pc to controller(server) to know what kind of values I have to send to actual client(simulator). I found out that 8 registers(from 0 to 7) are used to store integer values.
I tried to establish a connection between my pc(sever) and simulator computer(client).I was able to establish a connection and send a response to the client.
Problem
I have no information about this client(simulator) because we have no access to the client script.
I found out that this client sends a request not only for the reading but also for writing.
When I use the holding register, I got an error "illegal data address." But the input register does not show any error. For this reason, I am using input_register to save a specific integer number.
I stored some values on input_register, but sever input_registers are written by client(simulator) as below.
write request from client(simulator)
polling server(pc) with modpoll software
Question
why write requests from the client(simulator) overwrite my input_register? As far as I know, input_register is used for only reading. I assume that I made a mistake in storing a variable on the input_register.
When I make a connection between controller and simulator, wireshark and modpoll show that client(simulator) reads registers (from 0 to 7). But when I make a connection between my server(pc) and client(simulator), my sever response with different register numbers as below. Resister number starts from 1000. Why does simulator request different register start number? ex) from 0: controller, from 1000: PC(sever)
First response from server(pc)
Update! my server can respond with the values but with wrong register numbers. I changed starting register number(0 -->1000).
I attached picture.
response from server(pc)
Please advice me on this issue.
I will do my best effort to solve this issue.
'''
from pymodbus.server.sync import StartTcpServer
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock, ModbusSparseDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.transaction import ModbusRtuFramer, ModbusBinaryFramer
#%%
import logging
FORMAT = ('%(asctime)-15s %(threadName)-15s'
' %(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s')
logging.basicConfig(format=FORMAT)
log = logging.getLogger()
log.setLevel(logging.DEBUG)
#%%
#%%
def run_server():
store = ModbusSlaveContext(
ir=ModbusSequentialDataBlock(0, [28692,28692,28692,28692,28692,65508,65508,65508
]),zero_mode=True)
context = ModbusServerContext(slaves=store, single=True)
StartTcpServer(context, address=("192.168.1.231", 502))
identity = ModbusDeviceIdentification()
identity.VendorName = 'Pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/riptideio/pymodbus/'
identity.ProductName = 'Pymodbus Server'
identity.ModelName = 'Pymodbus Server'
identity.MajorMinorRevision = '1.0'
#%%
if __name__ == "__main__":
run_server()
'''
Dear MarcosG,
I attached screen-shots from wireshark as below.
write request from clinet(simulator)
- as you can see clinet(simulator) send a request for writing and register number start from 256.
read response from server(controller)
- Sever(controller) responds to the request of clinet for reading. And it send a respond and register number start from 256.
polling sever with modpoll software
- we can look the values on the registers of sever, as you can see, values are stored in the register from 0 to 7. These values are from controller lever. If I adjust lever, these values are changing.
requested address_exel_File
- We have one more simulator(bridge2). It shows the same register number with both controller(server) and pc(server).
problem: the actual registers of sever which store values are from 0 to 7. However, Client and server communicate with different registers (from 256) which contain "0" values. But there is no issue for adjusting parameters of ship on the simulator.
Best regards
Byeon Seongsu

How to Extend Firebase Session Cookies Beyond 2 Weeks

I'm using Firebase Auth to have users authenticate using their Google Account. I found the token returned by firebase.auth().currentUser.getIdToken is only valid for 1 hour. To allow the session to last longer I tried creating a session cookie as outlined in Manage Session Cookies:
const expiresIn = 60 * 60 * 24 * 5 * 1000;
admin.auth().createSessionCookie(idToken, {expiresIn}).then((sessionCookie) => {
const options = {maxAge: expiresIn, httpOnly: true, secure: true};
res.cookie('session', sessionCookie, options);
res.end(JSON.stringify({status: 'success'});
}
This code successfully created a session cookie and subsequent requests could be verified using admin.auth().verifySessionCookie. All was well until I tried increasing the expiresIn duration. It turns out that Firebase session cookies have a maximum expiration time of 2 weeks. From the docs:
Ability to create session cookies with custom expiration times ranging from 5 minutes to 2 weeks.
For this project I would prefer to have a user log in once and stay logged in. I tried extending the session on every interaction with the server but I didn't find any official documentation on how to do that. It seemed to make sense to call admin.auth().createSessionCookie on the server using the token returned by admin.auth().verifySessionCookie, but that failed with this error:
Failed to extend session: { Error: An internal error has occurred. Raw server response: "{"error":{"code":400,"message":"Invalid value at 'valid_duration' (TYPE_INT64), 604.8","errors":[{"message":"Invalid value at 'valid_duration' (TYPE_INT64), 604.8","domain":"global","reason":"badRequest"}],"status":"INVALID_ARGUMENT"}}"`enter code here`
at FirebaseAuthError.Error (native)
at FirebaseAuthError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:39:28)
at FirebaseAuthError.PrefixedFirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:85:28)
at new FirebaseAuthError (/user_code/node_modules/firebase-admin/lib/utils/error.js:143:16)
at Function.FirebaseAuthError.fromServerError (/user_code/node_modules/firebase-admin/lib/utils/error.js:173:16)
at /user_code/node_modules/firebase-admin/lib/auth/auth-api-request.js:726:49
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
errorInfo:
{ code: 'auth/internal-error',
message: 'An internal error has occurred. Raw server response: "{"error":{"code":400,"message":"Invalid value at \'valid_duration\' (TYPE_INT64), 604.8","errors":[{"message":"Invalid value at \'valid_duration\' (TYPE_INT64), 604.8","domain":"global","reason":"badRequest"}],"status":"INVALID_ARGUMENT"}}"' },
codePrefix: 'auth' }
Is it possible to extend Firebase sessions on the server side without requiring the client to do any work? Is it possible to use Firebase auth with tokens with a longer lifespan than 2 weeks? If not, in there a standard approach on how to achieve incredibly long lived sessions?
Extending it too long can be risky, as if the cookie is leaked, the window of attack will be quite wide. I don't recommend extending the session longer but if this is a requirement, you could try to do the following:
after verifying the session cookie on your server for the user and noticing it is about to expire.
mint a custom token for that user ID with Admin SDK
signInWithCustomToken with that custom token.
user.getIdToken() to get new ID token.
Exchange that ID token for a new session cookie.
The downside is that the claims in the session cookie will correspond to a custom token user.
Notice for client side sessions, the ID token passed around has one hour duration, even though the session is indefinite. This is because a refresh token lives on the device and is used to exchange new ID tokens. At any time, only the ID token is transmitted limiting the window of attack to one hour if that token is leaked.
I think it would be useful for Firebase Auth to offer an active duration functionality. That would be better for extending sessions continuously in short increments. This would be better than minting an indefinite or very long cookie. An active user would constantly have their session extended. This is not offered by Firebase Auth but you can file a feature request for it.

Log out a user from the server

Is there any way to log out a user (or all users) from the server? Basically I'm trying to log out all users every time the meteor server starts up or restarts.
You could clear up all the loginTokens which would force everyone to log back in
Meteor.users.update({}, {$set: { "services.resume.loginTokens" : [] }});
What this does is it clear's each users loginTokens so that they wont match up if the user tries to log in, then they would have to log back in. To alter who to target change the initial query (currently {})

How to increase Azure ACS login timeout

The Azure Training Kit includes a lab titled "IntroToACS2". In it, you create a WebRole and enable ACS so that you can login using your Google, Live, or Yahoo id. After logging in, if I wait 10 minutes or so and then refresh the page, I'm redirected back to the login page.
How can I increase the Azure ACS login timeout?
Here's what I found:
http://msdn.microsoft.com/en-us/library/gg185906.aspx#BKMK_5
Token Lifetime
The Token lifetime property allows you to specify the amount of time for a security token issued by ACS to the relying party application to remain valid. By default, in ACS, this value is set to 10 minutes (600 seconds). In ACS, this value must be greater than zero but less than or equal to 24 hours (86400 seconds).
While the maximum lifetime is 24 hours it's possible to automatically renew the ACS token by adding the following 6 lines of code in ShowSigninPage function, just before the existing loop over identityProviders:
for (var i in identityProviders) {
if (cookieName !== null && cookieName == identityProviders[i].Name) {
window.location = identityProviders[i].LoginUrl;
return null;
} }
// Loop through the identity providers for (var i in identityProviders) {
...
For more info the automatic renewal approach see: http://social.msdn.microsoft.com/Forums/en-US/windowsazuresecurity/thread/0430c4aa-ab10-4a72-b115-91b2600bfcd0
I think what you really want is to increase your application's session lifetime, and not the ACS issued token lifetime.
How do I increase session timeout with W.I.F / SAML tokens / FedAuth cookie

Resources