Need an example of code for a password protected application pls

Joel Fonseca

Member
Licensed User
Longtime User
Hi everyone,

Can anyone post here an example with code for a password protecting application example ?.

The idea is:

When the user press the application icon on the phone, a password box would pop up and asking for username and password, or just a password, if the password is correct it goes to the main program activity, if fails the password it will end the activity, and if he knows the password he goes to his main program activity that has a button there where he can change te password to one of his own, and then he will be using that password for now on.

hope i make myself clear with this idea, i searched the forums but only found little about this, i would appreacite if someone posted a good example of how to do it, i guess this would be appreaciated for other forum users that like me know little about programming :(.

Thanks in advance,

Joel
 

Kamac

Active Member
Licensed User
Longtime User
Use designer to place two EditTexts and one Button. Name one Username and second Password, the button can be named Button1.

Now, save that layout as main.bal. Add this in Sub Activity_Created:

B4X:
Activity.LoadLayout("main.bal")

And in:

B4X:
Sub Button1_Click

add:

B4X:
if(Username.text == "Username") then
    if(Password.text == "Password") then
        removeviews
        Activity.LoadLayout("Some second layout here")
    else
        ExitApplication
    end if
else
    ExitApplication
end if

also, add this on the end of the code:

B4X:
Sub RemoveViews
   Dim i As Int
   
   For i=Activity.NumberOfViews-1 To 0 Step -1
      Activity.RemoveViewAt(i)
   Next
End Sub


That's it.


@Tip

You can use Tools -> Generate Members in your Designer to generate variables and subs.
 
Upvote 0

admac231

Active Member
Licensed User
Longtime User
The way I would suggest is to have the initial password as simply a string in your program. Once the user has logged in successfully the first time allow them to enter a new password. Save this password to a file on the device.

When the app is opened again check to see if this file exists. If it does, make the password string equal to the text in the password file.

I don't know how clear that is but it made sense to me :) anyway, I've written some code that should at least give you somewhere to start:

B4X:
Sub Globals
   Dim strPassword As String
   Dim tr As TextReader
   Dim tw As TextWriter
   Dim inputText As InputDialog
   Dim cmdChangePass As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
   If FirstTime Then
      If File.Exists(File.DirDefaultExternal, "password_file.txt") = True Then 'Check to see if there is already a password file saved and therefore a custom password
         tr.Initialize(File.OpenInput(File.DirDefaultExternal, "password_file.txt")) 
         strPassword = tr.ReadLine
         tr.Close ' Load the password into strPassword
      Else
         strPassword = "default_password" ' If there is no password file then set strPassword to default
      End If
      
      Do While inputText.Input <> strPassword ' Keep displaying the input password input dialog until the correct password has been entered
         If inputText.Show("Please enter your password","Password","Submit","","Exit",Null) = DialogResponse.NEGATIVE Then ' If the user selects exit then close the activity
            Activity.Finish 
         End If
         If inputText.Input <> strPassword Then ' Display wrong password message if wrong password entered
            ToastMessageShow("Wrong password. Try Again", False)
         End If
      Loop
   End If
   
   cmdChangePass.Initialize("cmdChangePass") 
   cmdChangePass.Text = "Change Password"
   Activity.AddView(cmdChangePass,0,0,100%x,50dip)' Display button cmdChangePass
End Sub

Sub cmdChangePass_Click
   If inputText.Show("Please enter your new password","Password","Submit","","Exit",Null) = DialogResponse.POSITIVE Then ' Store the contents of the new password textbox, overwriting anything else already there
      tw.Initialize(File.OpenOutput(File.DirDefaultExternal, "password_file.txt", False))
      tw.WriteLine(inputText.Input)
      tw.Close
      ToastMessageShow("Password updated", False)
   Else ' If the user selects exit then close the activity
      Activity.Finish
   End If
End Sub

Any questions, just ask.
 
Upvote 0

Cableguy

Expert
Licensed User
Longtime User
Olá Joel

Existem muitas maneiras de esfolar um gato, ja diz o ditado....
Dependendo do nivel de segurança que queiras para essa password, podes ir por varios meios.

1 - Facil - Usar uma password hardcoded no codigo, ou seja cada distrinuiçao teria a sua propia password.
Vantagens - Facil de implementar, basta uma textbox e comparar a string com a password...
Desvantagens - a principal é ter de mudar a password no codigo para cada utilizador, é segura q.b.

2- Média - Utilizar um ficheiro para guardar a password e o user name, no inicio da aplicaçao ler esses valores e comparar com o que o utilizador entrou, para alterar, bastaria guardar e substituir o ficheiro.
Vantagens - Podes ter uma password base para 1º iniciaçao da aplicaçao e depois o utilizador defenir uma nova.
Desvantagens - Com um explorador de ficheiro, consegue-se ver o conteudo do ficheiro onde estao guardados os valores.

3 - Dificil -parecida com a numero 2 mas em vez de guardares os valores simples, codificas usando por exemplo o MD5, com uma chave fixa ou variavel, e no arranque descodificas usando essa mesma chave.
Vantagens - Como no nº2, mas desta vez, muito mais segura.
Desvantagens - apenas a dificuldade normal de implementaçao.

Espero ter ajudado


In English :D

HI Joel

There are several ways to skin a cat, as they say...
Depending of how secure you want that password to be, yu can choose several ways...

1-Easy - Use a harcoded password, being that each distribution would have its own password.
Advantages - Easy to implement, just use a textbox and compare the entered string with the hardcoded password.
Disadvantages - The main one is to have to change the password in the code itself for each new user...The password is safe enough.

2- Medium - Use a file containing the password and the username, in app start read those from the file and compare with the entered ones, to alter them would just be overwriting the file.
Advantages - You can use a base user and password set for first run, and then have the user alter them.
Disadvantages - With a file explorer, we can see the file and it's contents, wich makes its not very safe.

3 - Hard - Just like Nº2, but with encoding, i.e. with MD5, either with a fixer decoder key, or a variable one. on appstart you read and decode the values from the file.
Advantages - Like Nº2, but MUCH safer.
Disadvantages - Just the normal dificulties of implement.

Hope to have helped you
 
Upvote 0

Joel Fonseca

Member
Licensed User
Longtime User
Many thanks to all that helped with this question, lots of us are more happy now with all this explanation :) will try to implement this one :)

Cheerz :sign0142:

Joel
 
Upvote 0
Top