B4J Tutorial [Server] Login System & Filters Tutorial

upload_2014-3-19_16-8-41.png

Try it online: https://www.b4x.com:51042/login_example/
Note that it is not connected to the forum database. Feel free to test it and register new users. Its only purpose is to demonstrate this solution.

Login Example

A typical web solution consists of several folders. In this case the structure is:

42fm.png


We want to restrict access to files and handlers under the 'members' folder to registered members only.

This is done with a Filter.

Filters

Each request is handled by a single handler or if no handler matches the URL then a file is returned (or 404 error if there is no matching file).

Filters are similar to handlers. However the request can go through any number of filters before it reaches its final destination. Filters can change the request destination or block the request.

A Filter class should include a sub named Filter with the following signature:
B4X:
Public Sub Filter(req As ServletRequest, resp As ServletResponse) As Boolean
If the filter sub returns True then the request will continue to the next filter or final destination, otherwise the request completes and the response is committed.

Adding filters is done with Server.AddFilter. In our example we want to apply the filter to all files and handlers under the 'members' folder (notice the wildcard in the path):
B4X:
srvr.AddFilter("/login_example/members/*", "MembersFilter", False)

The filter code:
B4X:
Public Sub Filter(req As ServletRequest, resp As ServletResponse) As Boolean
   If req.GetSession.GetAttribute2("registered", "") = True Then
     'check that no more than 30 minutes passed since last activity
     If req.GetSession.LastAccessedTime + DateTime.TicksPerMinute * 30 > DateTime.Now Then
       Return True 'allow request to continue
     End If
   End If
   resp.SendRedirect("/login_example/")
   Return False
End Sub
In this code we check whether the user session includes an attribute named 'registered' with the value of True. If not then the response is redirected to the login page.

This attribute is set when the user registers to the forum or signs in. Remember that user sessions are stored in the server memory. This means that they are safe to use (a cookie will not work here). However this also means that the user will need to sign in again (no need to register again) if the server is restarted.

Passwords

When a user registers we need to save it in the database. For security reasons we do not save the password. Instead we save a hash of the password combined with a "salt" value. When the user signs in we do the same process and check whether the current hash equals to the stored hash.

Captcha

Google ReCaptcha service is used to make sure that a human is registering and not a bot. In order to use this service you need to create a key: https://www.google.com/recaptcha/admin/create
You will receive two keys. The public key should be set in the JavaScript code (in login_example/index.html) and the private key should be set in the settings file.

Note the usage of StartMessageLoop / StopMessageLoop in LoginHelper. These methods block the thread while it waits for the JobDone event.

Log out

The Logout handler is quite simple. It invalidates the user session. This means that the next time the user tries access a resource under 'members' folder they will be redirected to the login page.

Tips

- All the settings are saved in a file named settings.txt. This makes it simple to test the project locally and then update it on the server without overwriting the server settings file. I'm using Wamp to test it locally with MySQL database.
- Use #MergeLibraries: False. This way you can update the server jar without uploading a large jar file each time. You will need to manually upload the libraries once.
- I'm using this command to run it on the Linux server
B4X:
nohup ../jre1.7.0_51/bin/java -jar ServerExample.jar > nohup.out &
- The project depends on the following B4A libraries: ByteConverter and Encryption
 

Attachments

  • LoginExample.zip
    11.7 KB · Views: 2,184
Last edited:

tuicemen

Member
Licensed User
Longtime User
to be honest I only tried looking for one in the b4a libraries and it was the byteconverter I came up with xbyeconverter or something like that but never dug any deeper:rolleyes:
Thanks:)
 

tuicemen

Member
Licensed User
Longtime User
Ok new issue says can't find mysql-connector-java-5.1.27-bin.jar in the libraries folder however it is there
 

tuicemen

Member
Licensed User
Longtime User
yes I even opened the folder to make sure it was there.
maybe the sample download got corrupt.
I'll attempt a new download.
I redownloaded the mysql-connector-java-5.1.27-bin.jar and over wrote the other without success.
 

tuicemen

Member
Licensed User
Longtime User
I did a refresh of the libraries and I notice it doesn't appear to the right
I've redownloaded the sample and still the same results.
is there another file that should be copied to the libraries folder too?(other then the jar)
 

Attachments

  • error.png
    error.png
    106.8 KB · Views: 445

tuicemen

Member
Licensed User
Longtime User
Ok that makes sense
I got the same error even with the path change. so I moved all B4j files.
and now the error point to C\anywhere software\b4j\libraries :confused:
 

tuicemen

Member
Licensed User
Longtime User
I've removed B4J and reinstalled to C:|anywhere software\b4j with the same results:confused:
I think the issue is the mysql-connector-java-5.1.22-bin.jar file
Originally I had read the manifest needed to be edited somewhere using 7zip (can't find that now):(
Since I've redownloaded and over wrote the file those entries no longer exist so expect that is the issue.
 

BarryW

Active Member
Licensed User
Longtime User
View attachment 23642
Try it online: https://www.b4x.com:51042/login_example/
Note that it is not connected to the forum database. Feel free to test it and register new users. Its only purpose is to demonstrate this solution.

Login Example

A typical web solution consists of several folders. In this case the structure is:

42fm.png


We want to restrict access to files and handlers under the 'members' folder to registered members only.

This is done with a Filter.

Filters

Each request is handled by a single handler or if no handler matches the URL then a file is returned (or 404 error if there is no matching file).

Filters are similar to handlers. However the request can go through any number of filters before it reaches its final destination. Filters can change the request destination or block the request.

A Filter class should include a sub named Filter with the following signature:
B4X:
Public Sub Filter(req As ServletRequest, resp As ServletResponse) As Boolean
If the filter sub returns True then the request will continue to the next filter or final destination, otherwise the request completes and the response is committed.

Adding filters is done with Server.AddFilter. In our example we want to apply the filter to all files and handlers under the 'members' folder (notice the wildcard in the path):
B4X:
srvr.AddFilter("/login_example/members/*", "MembersFilter", False)

The filter code:
B4X:
Public Sub Filter(req As ServletRequest, resp As ServletResponse) As Boolean
   If req.GetSession.GetAttribute2("registered", "") = True Then
     'check that no more than 30 minutes passed since last activity
     If req.GetSession.LastAccessedTime + DateTime.TicksPerMinute * 30 > DateTime.Now Then
       Return True 'allow request to continue
     End If
   End If
   resp.SendRedirect("/login_example/")
   Return False
End Sub
In this code we check whether the user session includes an attribute named 'registered' with the value of True. If not then the response is redirected to the login page.

This attribute is set when the user registers to the forum or signs in. Remember that user sessions are stored in the server memory. This means that they are safe to use (a cookie will not work here). However this also means that the user will need to sign in again (no need to register again) if the server is restarted.

Passwords

When a user registers we need to save it in the database. For security reasons we do not save the password. Instead we save a hash of the password combined with a "salt" value. When the user signs in we do the same process and check whether the current hash equals to the stored hash.

Captcha

Google ReCaptcha service is used to make sure that a human is registering and not a bot. In order to use this service you need to create a key: https://www.google.com/recaptcha/admin/create
You will receive two keys. The public key should be set in the JavaScript code (in login_example/index.html) and the private key should be set in the settings file.

Note the usage of StartMessageLoop / StopMessageLoop in LoginHelper. These methods block the thread while it waits for the JobDone event.

Log out

The Logout handler is quite simple. It invalidates the user session. This means that the next time the user tries access a resource under 'members' folder they will be redirected to the login page.

Tips

- All the settings are saved in a file named settings.txt. This makes it simple to test the project locally and then update it on the server without overwriting the server settings file. I'm using Wamp to test it locally with MySQL database.
- Use #MergeLibraries: False. This way you can update the server jar without uploading a large jar file each time. You will need to manually upload the libraries once.
- I'm using this command to run it on the Linux server
B4X:
nohup ../jre1.7.0_51/bin/java -jar ServerExample.jar > nohup.out &
- The project depends on the following B4A libraries: ByteConverter and Encryption

Hi.

I tried to register and it works fine.

Then i try to login and logout and it works fine.

But, when i try to login then logout and i type this link: http://127.0.0.1:51042/login_example/members/index.html (link of members only)
or pressed the browsers back button it opens the member page. Then after of some refresh it catches that i am already logout and i cant open the members page.

Is this delay for page protection (filtering)? Somehow when i already logout and try to back on members page and i press the link (Example of a members only handler) it is not working.

How to prevent this. Hope some will help. Tnx.
 

JanPRO

Well-Known Member
Licensed User
Longtime User
Hi,

I have a little question: Why you are using ajax POST requests for registering and sign in?

For example for the sign in:
Isn't it easier to read the values of the username and password inputs in the btnSign_Click event and check with the database?

Jan
 
Top