Advertisement
GuylianBollon

Login code

Nov 21st, 2019
493
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 15.87 KB | None | 0 0
  1. Main Application code
  2.  
  3. Resource file activity_login
  4.  
  5. <?xml version="1.0" encoding="utf-8"?>
  6. <layout xmlns:android="http://schemas.android.com/apk/res/android"
  7.     xmlns:app="http://schemas.android.com/apk/res-auto"
  8.     xmlns:tools="http://schemas.android.com/tools">
  9. <data>
  10.     <variable
  11.         name="loginViewModel"
  12.         type="be.ysebie.multimedlembeke_app.login.LoginViewModel" />
  13. </data>
  14.     <FrameLayout
  15.         android:layout_width="match_parent"
  16.         android:layout_height="match_parent">
  17.  
  18.         <androidx.constraintlayout.widget.ConstraintLayout
  19.             android:layout_width="match_parent"
  20.             android:layout_height="match_parent">
  21.  
  22.             <TextView
  23.                 android:id="@+id/emailLabel"
  24.                 android:layout_width="0dp"
  25.                 android:layout_height="wrap_content"
  26.                 android:layout_marginStart="24dp"
  27.                 android:layout_marginEnd="24dp"
  28.                 android:text="@string/email"
  29.                 android:textAlignment="center"
  30.                 app:layout_constraintBottom_toTopOf="@+id/emailtextbox"
  31.                 app:layout_constraintEnd_toEndOf="parent"
  32.                 app:layout_constraintHorizontal_bias="0.0"
  33.                 app:layout_constraintStart_toStartOf="parent"
  34.                 app:layout_constraintTop_toTopOf="parent"
  35.                 app:layout_constraintVertical_bias="0.921" />
  36.  
  37.             <EditText
  38.                 android:id="@+id/emailtextbox"
  39.                 android:layout_width="0dp"
  40.                 android:layout_height="wrap_content"
  41.                 android:layout_marginStart="24dp"
  42.                 android:layout_marginEnd="24dp"
  43.                 android:layout_marginBottom="44dp"
  44.                 android:autofillHints="@string/emailhints"
  45.                 android:ems="10"
  46.                 android:gravity="center"
  47.                 android:hint="@string/emailhints"
  48.                 android:inputType="textEmailAddress"
  49.                 app:layout_constraintBottom_toTopOf="@+id/passwordlabel"
  50.                 app:layout_constraintEnd_toEndOf="parent"
  51.                 app:layout_constraintHorizontal_bias="0.0"
  52.                 app:layout_constraintStart_toStartOf="parent"
  53.                 tools:targetApi="o" />
  54.  
  55.             <TextView
  56.                 android:id="@+id/passwordlabel"
  57.                 android:layout_width="0dp"
  58.                 android:layout_height="wrap_content"
  59.                 android:layout_marginStart="24dp"
  60.                 android:layout_marginEnd="24dp"
  61.                 android:layout_marginBottom="24dp"
  62.                 android:text="@string/wachtwoord"
  63.                 android:textAlignment="center"
  64.                 app:layout_constraintBottom_toTopOf="@+id/passwordTextBox"
  65.                 app:layout_constraintEnd_toEndOf="parent"
  66.                 app:layout_constraintHorizontal_bias="0.0"
  67.                 app:layout_constraintStart_toStartOf="parent" />
  68.  
  69.             <EditText
  70.                 android:id="@+id/passwordTextBox"
  71.                 android:layout_width="0dp"
  72.                 android:layout_height="wrap_content"
  73.                 android:layout_marginStart="24dp"
  74.                 android:layout_marginEnd="24dp"
  75.                 android:layout_marginBottom="56dp"
  76.                 android:autofillHints="@string/wachtwoordhints"
  77.                 android:ems="10"
  78.                 android:gravity="center"
  79.                 android:hint="@string/wachtwoordhints"
  80.                 android:inputType="textPassword"
  81.                 app:layout_constraintBottom_toTopOf="@+id/loginbutton"
  82.                 app:layout_constraintEnd_toEndOf="parent"
  83.                 app:layout_constraintHorizontal_bias="1.0"
  84.                 app:layout_constraintStart_toStartOf="parent"
  85.                 tools:targetApi="o" />
  86.  
  87.             <Button
  88.                 android:id="@+id/loginbutton"
  89.                 android:layout_width="wrap_content"
  90.                 android:layout_height="wrap_content"
  91.                 android:layout_marginBottom="22dp"
  92.                 android:autofillHints="Druk op die knop om u in te loggen."
  93.                 android:text="@string/login"
  94.                 android:textAlignment="center"
  95.                 android:textColor="#FFFFFF"
  96.                 app:layout_constraintBottom_toBottomOf="parent"
  97.                 app:layout_constraintEnd_toEndOf="parent"
  98.                 app:layout_constraintHorizontal_bias="0.499"
  99.                 app:layout_constraintStart_toStartOf="parent"
  100.                 tools:targetApi="o" />
  101.  
  102.             <TextView
  103.                 android:id="@+id/errorTextLogin"
  104.                 android:layout_width="wrap_content"
  105.                 android:layout_height="wrap_content"
  106.                 android:layout_marginStart="24dp"
  107.                 android:layout_marginTop="80dp"
  108.                 android:layout_marginEnd="24dp"
  109.                 android:layout_marginBottom="6dp"
  110.                 android:gravity="center"
  111.                 android:text="@string/ongeldigheidsstring"
  112.                 android:textColor="#FF0000"
  113.                 android:visibility="invisible"
  114.                 app:layout_constraintBottom_toTopOf="@+id/loginbutton"
  115.                 app:layout_constraintEnd_toEndOf="parent"
  116.                 app:layout_constraintHorizontal_bias="0.492"
  117.                 app:layout_constraintStart_toStartOf="parent"
  118.                 app:layout_constraintTop_toTopOf="@+id/passwordTextBox"
  119.                 app:layout_constraintVertical_bias="0.0" />
  120.  
  121.             <TextView
  122.                 android:id="@+id/Welkomtekst"
  123.                 android:layout_width="match_parent"
  124.                 android:layout_height="wrap_content"
  125.                 android:layout_marginStart="24dp"
  126.                 android:layout_marginEnd="24dp"
  127.                 android:text="@string/welkom"
  128.                 android:textAlignment="center"
  129.                 android:textSize="30sp"
  130.                 app:layout_constraintBottom_toTopOf="@+id/emailLabel"
  131.                 app:layout_constraintEnd_toEndOf="parent"
  132.                 app:layout_constraintStart_toStartOf="parent"
  133.                 app:layout_constraintTop_toTopOf="parent" />
  134.         </androidx.constraintlayout.widget.ConstraintLayout>
  135.  
  136.         <ImageView
  137.         android:id="@+id/imageView"
  138.         android:layout_width="match_parent"
  139.         android:layout_height="wrap_content"
  140.         android:contentDescription="@string/multimedtext"
  141.         app:srcCompat="@drawable/custom_progress" />
  142.     </FrameLayout>
  143. </layout>
  144.  
  145. LoginLocator.kt
  146. package be.ysebie.multimedlembeke_app
  147.  
  148. import android.content.Context
  149. import androidx.annotation.VisibleForTesting
  150. import be.ysebie.multimedlembeke_app.repositories.ILoginRepository
  151. import be.ysebie.multimedlembeke_app.repositories.LoginRepository
  152.  
  153. object LoginLocator {
  154.     @Volatile
  155.     var loginRepository: ILoginRepository?=null
  156.     @VisibleForTesting set
  157.  
  158.     fun provideLoginRepository(context: Context):ILoginRepository{
  159.         synchronized(this) {
  160.             return loginRepository ?: createLoginRepository()
  161.         }
  162.     }
  163.  
  164.     private fun createLoginRepository(): ILoginRepository {
  165.         return LoginRepository()
  166.     }
  167. }
  168.  
  169. Activity MainActivity changes to be added to OnCreate:
  170. //ophalen informatie van de gebruiker
  171.         val sharedPreferences = this.getSharedPreferences("User", Context.MODE_PRIVATE)
  172.         if(sharedPreferences.contains("currentUser")){
  173.             val encodeduser : String = sharedPreferences.getString("currentUser", "") ?: ""
  174.             try{
  175.                 expirationDate = JWTUtils.getExpiracyDate(encodeduser)
  176.                 if(expirationDate.after(Date())){
  177.                     val mEditor = sharedPreferences.edit()
  178.                     val userValue = "currentUser"
  179.                     mEditor.remove(userValue)
  180.                     val email = sharedPreferences.getString("email",null)
  181.                     val password = sharedPreferences.getString("password",null)
  182.                     if(!email.isNullOrEmpty() || !password.isNullOrEmpty()){
  183.                         val givenEmail = email ?: ""
  184.                         val givenPassword = password ?: ""
  185.                         val loginRepository = LoginRepository()
  186.                         val loginViewModel = LoginViewModel(loginRepository)
  187.                         loginViewModel.login(givenEmail, givenPassword)
  188.                         mEditor.putString(userValue, loginViewModel.authenticationKey.toString())
  189.                     } else{
  190.                         switchToLogin()
  191.                     }
  192.                     switchToLogin()
  193.                 }
  194.             }catch(e: UnsupportedEncodingException){
  195.  
  196.             }
  197.         }else{
  198.             switchToLogin()
  199.         }
  200. Activity MainActivity added method:
  201. fun switchToLogin(){
  202.         val intent = Intent(this, LoginActivity::class.java)
  203.         intent.putExtra("hi", "HI")
  204.         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
  205.         startActivity(intent)
  206.     }
  207.  
  208. Login/LoginViewModel.kt
  209. package be.ysebie.multimedlembeke_app.login
  210.  
  211. import android.app.Application
  212. import android.util.Log
  213. import androidx.lifecycle.LiveData
  214. import androidx.lifecycle.MutableLiveData
  215. import androidx.lifecycle.ViewModel
  216. import be.ysebie.multimedlembeke_app.database.LocalDb
  217. import be.ysebie.multimedlembeke_app.database.getDatabase
  218. import be.ysebie.multimedlembeke_app.repositories.ILoginRepository
  219. import be.ysebie.multimedlembeke_app.repositories.LoginRepository
  220. import kotlinx.coroutines.*
  221. import retrofit2.Response
  222. import java.io.Console
  223.  
  224. class LoginViewModel(private val loginRepository: ILoginRepository) : ViewModel() {
  225.  
  226.     private var _authenticationKey = MutableLiveData<Any?>()
  227.  
  228.     val authenticationKey: LiveData<Any?>
  229.         get() = _authenticationKey
  230.  
  231.     fun login(email: String, password: String) = runBlocking{
  232.        _authenticationKey.value = loginRepository.login(email,password)
  233.     }
  234. }
  235.  
  236. login/LoginViewModelFactory.kt
  237. package be.ysebie.multimedlembeke_app.login
  238.  
  239. import androidx.lifecycle.ViewModel
  240. import androidx.lifecycle.ViewModelProvider
  241. import be.ysebie.multimedlembeke_app.repositories.ILoginRepository
  242. import be.ysebie.multimedlembeke_app.repositories.LoginRepository
  243. import java.lang.IllegalArgumentException
  244.  
  245. @Suppress("UNCHECKED CAST")
  246. class LoginViewModelFactory(private val loginRepository: ILoginRepository): ViewModelProvider.Factory {
  247.     override fun <T : ViewModel?> create(modelClass: Class<T>): T {
  248.         if(modelClass.isAssignableFrom(LoginViewModel::class.java)){
  249.             return LoginViewModel(loginRepository) as T
  250.         }
  251.         throw IllegalArgumentException("Unknown ViewModelClass")
  252.     }
  253. }
  254.  
  255. login/LoginRepository.kt
  256. package be.ysebie.multimedlembeke_app.repositories
  257.  
  258. import androidx.lifecycle.LiveData
  259. import androidx.lifecycle.MutableLiveData
  260. import be.ysebie.multimedlembeke_app.network.LoginUser
  261. import be.ysebie.multimedlembeke_app.network.Web
  262. import kotlinx.coroutines.*
  263. import retrofit2.Response
  264.  
  265.  
  266. interface ILoginRepository {
  267.     suspend fun login(email: String, password: String): Any?
  268. }
  269.  
  270. class LoginRepository : ILoginRepository {
  271.  
  272.     override suspend fun login(email: String, password: String):Any?{
  273.         return withContext(Dispatchers.IO){
  274.             val accountDealer = Web.retrofitService.getAccount(LoginUser(email, password))
  275.             val result = accountDealer.execute()
  276.             result.body()
  277.         }
  278.     }
  279. }
  280.  
  281. network/WebService.kt
  282. import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
  283. import com.squareup.moshi.Moshi
  284. import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
  285. import be.ysebie.multimedlembeke_app.domain.Challenge
  286. import retrofit2.Call
  287. import retrofit2.Retrofit
  288. import retrofit2.converter.moshi.MoshiConverterFactory
  289. import retrofit2.http.Body
  290. import retrofit2.http.GET
  291. import retrofit2.http.POST
  292. import retrofit2.http.Query
  293.  
  294. private const val BASE_URL="https://api.ysebie.be/api/"
  295.  
  296. private val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
  297.  
  298. private val retrofit = Retrofit.Builder().addConverterFactory(MoshiConverterFactory.create(moshi)).addCallAdapterFactory(CoroutineCallAdapterFactory()).baseUrl(BASE_URL).build()
  299.  
  300. interface WebService{
  301.     //TODO Logic om te communiceren met de API
  302.     @GET("Challenge")
  303.     fun getTaken(@Query("employeeId") employeeId: String) : Call<Challenge>
  304.     @POST("Account")
  305.     fun getAccount(@Body user:LoginUser): Call<Any>
  306. }
  307.  
  308. object Web{
  309.     val retrofitService: WebService by lazy{
  310.         retrofit.create(WebService::class.java)
  311.     }
  312.  
  313. androidTest code
  314.  
  315. data/FakeLoginRepository.kt
  316. package be.ysebie.multimedlembeke_app.data
  317.  
  318. import be.ysebie.multimedlembeke_app.repositories.ILoginRepository
  319.  
  320. class FakeLoginRepository(var datasource: Any?) : ILoginRepository {
  321.     override suspend fun login(email: String, password: String): Any? {
  322.         return datasource
  323.     }
  324.  
  325. }
  326.  
  327. LoginActivityFalseTest.kt
  328. import be.ysebie.multimedlembeke_app.data.FakeLoginRepository
  329. import org.junit.Before
  330. import org.junit.Test
  331.  
  332. class LoginActivityFalseTest {
  333.     private lateinit var badrepository: FakeLoginRepository
  334.  
  335.     @Before
  336.     fun initRepositories(){
  337.         badrepository = FakeLoginRepository(null)
  338.         LoginLocator.loginRepository = badrepository
  339.     }
  340.  
  341.     @Test
  342.     fun falseTestAssertsSavingsAndNewActivity() {
  343.         ActivityScenario.launch<LoginActivity>(LoginActivity::class.java)
  344.         Espresso.onView(ViewMatchers.withId(R.id.errorTextLogin)).check(matches(
  345.             withEffectiveVisibility(ViewMatchers.Visibility.INVISIBLE)))
  346.         Espresso.onView(ViewMatchers.withId(R.id.emailtextbox))
  347.             .perform(ViewActions.replaceText("abc@aol.com"))
  348.         Espresso.onView(ViewMatchers.withId(R.id.passwordTextBox))
  349.             .perform(ViewActions.replaceText("Nederland1-"))
  350.         Espresso.onView(ViewMatchers.withId(R.id.loginbutton)).perform(ViewActions.click())
  351.         Espresso.onView(ViewMatchers.withId(R.id.errorTextLogin)).check(matches(
  352.             withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)))
  353.     }
  354. }
  355.  
  356. LoginActivityTrueTest.kt
  357.  
  358. package be.ysebie.multimedlembeke_app
  359.  
  360. import android.app.Activity
  361. import android.content.Context
  362. import android.content.Intent
  363. import android.content.SharedPreferences
  364. import android.os.Bundle
  365. import android.os.Looper
  366. import androidx.test.core.app.ActivityScenario
  367. import androidx.test.espresso.Espresso
  368. import androidx.test.espresso.Espresso.onData
  369. import androidx.test.espresso.Espresso.onView
  370. import androidx.test.espresso.action.ViewActions.click
  371. import androidx.test.espresso.action.ViewActions.replaceText
  372. import androidx.test.espresso.matcher.ViewMatchers.withId
  373. import androidx.test.ext.junit.runners.AndroidJUnit4
  374. import androidx.test.filters.MediumTest
  375. import be.ysebie.multimedlembeke_app.data.FakeLoginRepository
  376. import be.ysebie.multimedlembeke_app.repositories.LoginRepository
  377. import com.google.common.truth.Truth.assertThat
  378. import kotlinx.coroutines.ExperimentalCoroutinesApi
  379. import org.junit.Before
  380. import org.junit.Test
  381. import org.junit.runner.RunWith
  382. import java.security.AccessController.getContext
  383.  
  384. @MediumTest
  385. class LoginActivityTrueTest{
  386.  
  387.     private lateinit var goodrepository: FakeLoginRepository
  388.  
  389.     @Before
  390.     fun initRepositories(){
  391.         goodrepository = FakeLoginRepository(mutableListOf("token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiZXhwIjoxNTE2MjM5MDIyfQ.E9bQ6QAil4HpH825QC5PtjNGEDQTtMpcj0SO2W8vmag"))
  392.         LoginLocator.loginRepository = goodrepository
  393.     }
  394.  
  395.     @Test
  396.     fun trueTestAssertsSavingsAndNewActivity() {
  397.         ActivityScenario.launch<LoginActivity>(LoginActivity::class.java)
  398.         onView(withId(R.id.emailtextbox)).perform(replaceText("rpullerjt@edublogs.org"))
  399.         onView(withId(R.id.passwordTextBox)).perform(replaceText("Test123!"))
  400.         onView(withId(R.id.loginbutton)).perform(click())
  401.         onView(withId(R.layout.fragment_challenge_details_overview_fragment))
  402.     }
  403. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement