Monday, February 20, 2017

Адройд app дээр логин хэсэг хийж security session - нд хадгалах. /Session Management and User Authentication on Android/





Энэ демо дээр Android Studio ашигласан болно. Шинэ project үүсгэж дотор нь шинэ Activity үүсгэхдээ Empty Activity сонгож үүсгэнэ.


1) Үндсэн xml дэлгэцэн дээр дараах байдлаар компонентуудаа өрнө.
activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
 xmlns:tools="http://schemas.android.com/tools"  
 android:layout_width="match_parent"  
 android:layout_height="match_parent"  
 android:orientation="vertical"  
 android:padding="10dip"  
 tools:context="com.example.start.MainActivity">  
   <TextView  
     android:text="TextView"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:id="@+id/textView5" />  
 </LinearLayout>  


2) Системд ашиглах Menu үүсгэнэ. "res" дээр /mouse right click/ -> New -> Android resouce file. Гарч ирсэн цонхон дээр дараах утгуудыг бөглөнө. File Name: menu_main, Resource type: Menu, Directory name: menu
menu_main.xml



 <?xml version="1.0" encoding="utf-8"?>  
 <menu xmlns:android="http://schemas.android.com/apk/res/android">  
   <item  
     android:id="@+id/itemId"  
     android:title="@string/userInfo" />  
   <item android:title="@string/logout"  
     android:id="@+id/logoutItem" />  
 </menu>  


3) Session - тэй ажиллах java class үүсгэнэ.
UserSessionManager.java



 package com.example.start;  
 import java.util.HashMap;  
 import android.content.Context;  
 import android.content.Intent;  
 import android.content.SharedPreferences;  
 import android.content.SharedPreferences.Editor;  
 public class UserSessionManager {  
   SharedPreferences pref;  
   Editor editor;  
   Context _context;  
   int PRIVATE_MODE = 0;  
   private static final String PREFER_NAME = "AndroidExamplePref";  
   private static final String IS_USER_LOGIN = "IsUserLoggedIn";  
   public static final String KEY_NAME = "name";  
   public static final String KEY_EMAIL = "email";  
   public static final String KEY_PHONE = "phone";  
   public UserSessionManager(Context context){  
     this._context = context;  
     pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);  
     editor = pref.edit();  
   }  
   public void createUserLoginSession(String name, String phone, String email){  
     editor.putBoolean(IS_USER_LOGIN, true);  
     editor.putString(KEY_NAME, name);  
     editor.putString(KEY_EMAIL, email);  
     editor.putString(KEY_PHONE, phone);  
     editor.commit();  
   }  
   public boolean checkLogin(){  
     // login төлөвийг шалгах
     if(!this.isUserLoggedIn()){  
       // user is not logged in redirect him to Login Activity  
       Intent i = new Intent(_context, Login.class);  
        // бүх Activities хаах
       i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
        // шинэ Activity үүсгэх
       i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
      // Login Activity дуудах
       _context.startActivity(i);  
       return true;  
     }  
     return false;  
   }  

   public HashMap<String, String> getUserDetails(){  

     HashMap<String, String> user = new HashMap<String, String>();  
     user.put(KEY_NAME, pref.getString(KEY_NAME, null));  
     user.put(KEY_PHONE, pref.getString(KEY_PHONE, null));  
     user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));  

     return user;  
   }  

   public void logoutUser(){  
     // Clearing all user data from Shared Preferences  
     editor.clear();  
     editor.commit();  

     Intent i = new Intent(_context, Login.class);  
     // бүх Activities хаах
     i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
     // шинэ Activity үүсгэх
     i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
     // Login Activity дуудах
     _context.startActivity(i);  
   }  

   public boolean isUserLoggedIn(){  
     return pref.getBoolean(IS_USER_LOGIN, false);  
   }  
 }  


4) Хэрэглэгчийн мэдээллийг popup dialog component дээр харуулах view үүсгэх. Project->res->layout-> (mouse + right click) -> New -> Layout resource file
layout_dialog.xml



 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout  
 xmlns:android="http://schemas.android.com/apk/res/android"  
 xmlns:app="http://schemas.android.com/apk/res-auto"  
 android:layout_width="match_parent"  
 android:layout_height="match_parent"  
   android:layout_centerHorizontal="false">  
   <LinearLayout  
     android:orientation="vertical"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content">  
     <ImageView  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content"  
       app:srcCompat="@android:drawable/ic_menu_myplaces"  
       android:id="@+id/imageView"  
       android:layout_margin="30dp" />  
     <LinearLayout  
     android:orientation="horizontal"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
       android:gravity="center_horizontal"  
       android:layout_marginBottom="50dp">  
     <LinearLayout  
       android:orientation="vertical"  
       android:layout_height="match_parent"  
       android:gravity="end"  
       android:layout_marginRight="5dp"  
       android:layout_width="100dp">  
       <TextView  
         android:text="Нэр"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:id="@+id/textView" />  
       <TextView  
         android:text="Утас"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:id="@+id/textView4"  
         android:layout_marginTop="10dp" />  
       <TextView  
         android:text="Имэйл"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:id="@+id/textView3"  
         android:layout_marginTop="10dp" />  
     </LinearLayout>  
     <LinearLayout  
       android:orientation="vertical"  
       android:layout_height="match_parent"  
       android:layout_marginLeft="5dp"  
       android:layout_width="100dp">  
       <TextView  
         android:layout_width="match_parent"  
         android:layout_height="wrap_content"  
         android:id="@+id/dialogName" />  
       <TextView  
         android:layout_width="match_parent"  
         android:layout_height="wrap_content"  
         android:id="@+id/dialogPhone"  
         android:layout_marginTop="10dp" />  
       <TextView  
         android:layout_width="match_parent"  
         android:layout_height="wrap_content"  
         android:id="@+id/dialogEmail"  
         android:layout_marginTop="10dp" />  
     </LinearLayout>  
   </LinearLayout>  
   </LinearLayout>  
   <ImageButton  
   android:layout_width="wrap_content"  
   android:layout_height="wrap_content"  
   app:srcCompat="@android:drawable/btn_dialog"  
   android:id="@+id/closeBtn"  
   android:layout_alignParentTop="true"  
   android:layout_alignParentEnd="true"  
   android:background="@android:color/transparent" />  
 </RelativeLayout>  


5) Хэрэглэгчийн мэдээллийг popup dialog component дээр харуулах мөн өөр бусад туслах үүрэгтэй method агуулах зорилготой java class үүсгэнэ.
Utils.java



 import android.content.Context;  
 import android.content.DialogInterface;  
 import android.support.v7.app.AlertDialog;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.widget.ImageButton;  
 import android.widget.ImageView;  
 import android.widget.LinearLayout;  
 import android.widget.TextView;  
 import android.widget.Toast;  
 import java.util.HashMap;  
 /**  
  * Created by Tsogoo on 2/21/2017.  
  */  
 public class Utils {  
   Context ctx;  
   public Utils(Context ctx){  
     super();  
     this.ctx = ctx;  
   }  
   public void showDialog(HashMap<String, String> user) {  
     LayoutInflater myLayout = LayoutInflater.from(ctx);  
     final View dialogView = myLayout.inflate(R.layout.layout_dialog, null);  
     final AlertDialog dialog = new AlertDialog.Builder(ctx).create();  
     TextView tv = (TextView) dialogView.findViewById(R.id.dialogName);  
     tv.setText(user.get(UserSessionManager.KEY_NAME));  
     TextView tvPhone = (TextView) dialogView.findViewById(R.id.dialogPhone);  
     tvPhone.setText(user.get(UserSessionManager.KEY_PHONE));  
     TextView tvEmail = (TextView) dialogView.findViewById(R.id.dialogEmail);  
     tvEmail.setText(user.get(UserSessionManager.KEY_EMAIL));  
     dialog.setView(dialogView);  
     ImageButton btn = (ImageButton) dialogView.findViewById(R.id.closeBtn);  
     btn.setOnClickListener(new View.OnClickListener()  
     {  
       // @Override  
       public void onClick(View v) {  
         dialog.dismiss();  
       }  
     });  
     //AlertDialog dl = dialog.create();  
     dialog.show();  
   }  
 }  


6) Системийн кодыг үндсэн Activity үүсгэхэд хамт үүсдэг default class дээр дараах кодыг бичнэ.
MainActivity.java



 import android.support.v7.app.AppCompatActivity;  
 import android.os.Bundle;  
 import java.util.HashMap;  
 import android.app.Activity;  
 import android.os.Bundle;  
 import android.support.v7.widget.Toolbar;  
 import android.text.Html;  
 import android.view.Menu;  
 import android.view.MenuItem;  
 import android.view.View;  
 import android.widget.Button;  
 import android.widget.TextView;  
 import android.widget.Toast;  
 public class MainActivity extends AppCompatActivity {  
   UserSessionManager session;  
   HashMap<String, String> user;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     startSession();  
   }  
   @Override  
   public boolean onCreateOptionsMenu(Menu menu) {  
     getMenuInflater().inflate(R.menu.menu_main, menu);  
     return true;  
   }  
   @Override  
   public boolean onOptionsItemSelected(MenuItem item) {  
     switch (item.getItemId()) {  
       case R.id.itemId:  
         Utils d = new Utils(this);  
         d.showDialog(user);  
         return true;  
       case R.id.logoutItem:  
         session.logoutUser();  
         return true;  
       default:  
         return super.onOptionsItemSelected(item);  
     }  
   }  
   public void startSession(){  
     session = new UserSessionManager(getApplicationContext());  
     /*Toast.makeText(getApplicationContext(), "Төлөв: " + session.isUserLoggedIn(),  
         Toast.LENGTH_SHORT).show();*/  
     if(session.checkLogin())  
       finish();  
     user = session.getUserDetails();  
   }  
 }  


7) Шинэ Login нэртэй activity үүсгэнэ үүсгэхдээ Empty Activity сонгож үүсгэнэ. activity_login.xml



8) Login activity-г үүсгэхэд хамт үүсдэг default class дээр дараах кодыг бичнэ. Login.java



 import android.support.v7.app.AppCompatActivity;  
 import android.os.Bundle;  
 import android.app.Activity;  
 import android.content.Intent;  
 import android.os.Bundle;  
 import android.support.v7.widget.Toolbar;  
 import android.view.Menu;  
 import android.view.MenuItem;  
 import android.view.View;  
 import android.widget.Button;  
 import android.widget.EditText;  
 import android.widget.Toast;  
 public class Login extends AppCompatActivity {  
   Button btnLogin;  
   EditText txtUsername, txtPassword;  

   UserSessionManager session;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_login);  
     session = new UserSessionManager(getApplicationContext());  
     // Email, Password input text дээр авах
     txtUsername = (EditText) findViewById(R.id.txtUsername);  
     txtPassword = (EditText) findViewById(R.id.txtPassword);  
     /*  
     Toast.makeText(getApplicationContext(),  
         "Төлөв: " + session.isUserLoggedIn(),  
         Toast.LENGTH_SHORT).show();*/  
     // User Login button  
     btnLogin = (Button) findViewById(R.id.btnLogin);  
     // Login button click event  
     btnLogin.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View arg0) {  
         // Get username, password from EditText  
         String username = txtUsername.getText().toString();  
         String password = txtPassword.getText().toString();  
         // Validate if username, password is filled  
         if(username.trim().length() > 0 && password.trim().length() > 0){  
           if(username.equals("Test") && password.equals("Test")){  

             session.createUserLoginSession("Test","00000000",  
                 "test@test.edu");  

             Intent i = new Intent(getApplicationContext(), MainActivity.class);  
             i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  

             i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
             startActivity(i);  
             finish();  
           }else{  
             // username / password 
             Toast.makeText(getApplicationContext(),  
                 "Нэр/Нууц үг буруу байна.",  
                 Toast.LENGTH_LONG).show();  
           }  
         }else{  

           Toast.makeText(getApplicationContext(),  
               "Нэвтрэх нэр болон нууц үг оруулна уу.",  
               Toast.LENGTH_LONG).show();  
         }  
       }  
     });  
   }  
 }  


9) Доорх хэсэгт Login.java доторх кодын хэсэг харагдаж байна. Энэ хэсэгт username, password болон user profile - н мэдээллийг хатуугаар session-нд хадгалж байгаа бөгөөд хөгжүүлэгч өөрийн хүссэн байдлаар username болон password - г өгөгдлийн сангаас эсвэл rest service - с дуудаж session - д хадгалах боломжтой.



     if(username.equals("Test") && password.equals("Test")){  
             // Creating user login session  
             session.createUserLoginSession("Test","00000000",  
                 "test@test.edu");  


No comments:

Post a Comment