9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google {
4 | content {
5 | includeGroupByRegex("com\\.android.*")
6 | includeGroupByRegex("com\\.google.*")
7 | includeGroupByRegex("androidx.*")
8 | }
9 | }
10 | mavenCentral()
11 | gradlePluginPortal()
12 | }
13 | }
14 | dependencyResolutionManagement {
15 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
16 | repositories {
17 | google()
18 | mavenCentral()
19 | }
20 | }
21 |
22 | rootProject.name = "Descope Android Demo"
23 | include(":app")
24 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Descope Android Demo
3 | Main Screen
4 | Getting Started
5 | close button
6 | Log Out
7 | Log In
8 | Let\'s get started
9 | Perform API Call
10 | The button below will simulate a protected API call. That means that a session JWT will be sent to the server to validate using the Descope SDK.
11 |
--------------------------------------------------------------------------------
/app/src/main/java/com/descope/androiddemo/DemoApplication.kt:
--------------------------------------------------------------------------------
1 | package com.descope.androiddemo
2 |
3 | import android.app.Application
4 | import android.content.pm.ApplicationInfo
5 | import com.descope.Descope
6 | import com.descope.sdk.DescopeLogger
7 |
8 | internal const val descopeProjectId = "" // set your project ID here
9 |
10 | class DemoApplication: Application() {
11 | override fun onCreate() {
12 | super.onCreate()
13 |
14 | // Descope Setup
15 | Descope.setup(context = this, projectId = descopeProjectId) {
16 | // baseUrl = "myBaseUrl"
17 | val isDebuggable = 0 != applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE
18 | if (isDebuggable) {
19 | logger = DescopeLogger()
20 | }
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
17 |
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | agp = "8.8.1"
3 | appcompat = "1.7.0"
4 | constraintlayout = "2.2.0"
5 | descopeKotlin = "0.13.0"
6 | kotlin = "2.0.0"
7 | coreKtx = "1.15.0"
8 | material = "1.12.0"
9 |
10 | [libraries]
11 | androidx-appcompat = { module = "androidx.appcompat:appcompat", version.ref = "appcompat" }
12 | androidx-constraintlayout = { module = "androidx.constraintlayout:constraintlayout", version.ref = "constraintlayout" }
13 | androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
14 | descope-kotlin = { module = "com.descope:descope-kotlin", version.ref = "descopeKotlin" }
15 | material = { module = "com.google.android.material:material", version.ref = "material" }
16 |
17 | [plugins]
18 | android-application = { id = "com.android.application", version.ref = "agp" }
19 | kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
17 |
--------------------------------------------------------------------------------
/app/src/main/res/values-night-v35/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/values-v35/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
19 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/app/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | alias(libs.plugins.android.application)
3 | alias(libs.plugins.kotlin.android)
4 | }
5 |
6 | android {
7 | namespace = "com.descope.androiddemo"
8 | compileSdk = 35
9 |
10 | defaultConfig {
11 | applicationId = "com.descope.androiddemo"
12 | minSdk = 28
13 | targetSdk = 35
14 | versionCode = 1
15 | versionName = "1.0"
16 | }
17 |
18 | buildTypes {
19 | release {
20 | isMinifyEnabled = false
21 | proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
22 | }
23 | }
24 | compileOptions {
25 | sourceCompatibility = JavaVersion.VERSION_11
26 | targetCompatibility = JavaVersion.VERSION_11
27 | }
28 | kotlinOptions {
29 | jvmTarget = "11"
30 | }
31 | }
32 |
33 | dependencies {
34 | implementation(libs.androidx.core.ktx)
35 | implementation(libs.androidx.appcompat)
36 | implementation(libs.androidx.constraintlayout)
37 | implementation(libs.material)
38 | implementation(libs.descope.kotlin)
39 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Descope
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
18 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. For more details, visit
12 | # https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
18 |
19 |
24 |
25 |
34 |
35 |
41 |
42 |
43 |
44 |
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # Descope's Native Flows Kotlin Sample App
4 |
5 | [](https://opensource.org/licenses/MIT)
6 |
7 | Welcome to Descope's Native Flows Kotlin Sample App, a demonstration of how to integrate Descope native flows for user authentication within a Kotlin application. By exploring this project, you can understand how Descope works with Kotlin to manage native flows. For an example with all authentication methods, refer to the [Kotlin Sample App](https://github.com/descope-sample-apps/kotlin-sample-app).
8 |
9 | ## Features
10 | This sample app includes:
11 |
12 | - **App Client**: An example of how the client communicates with Descope.
13 |
14 | ## Getting Started
15 | Follow these steps to run the sample app and explore Descope's capabilities with Kotlin:
16 |
17 | ### Prerequisites
18 | Make sure you have the following installed:
19 |
20 | - Android Studio
21 | - Your Project ID which you can get in the [Project Settings](https://app.descope.com/settings/project)
22 |
23 | ### Run the app
24 |
25 | 1. Clone this repo
26 | 2. Open the project within Android Studio
27 | 3. Within the `DemoApplication.kt` file of the project, change the `descopeProjectId` (If in a non-US region, or using a custom domain with CNAME, uncomment `baseUrl` and replace `myBaseURL` with your specific localized base URL)
28 |
29 | 4. **(Optional) Self-Host Your Flow**: Your Descope authentication flow is automatically hosted by Descope at `https://api.descope.com/login/` but you can use your own website or domain to host your flow. You can modify the value for the flow Url in the `LoginActivity.kt` file to include your own hosted page with our Descope Web Component, as well as alter the `?flow=sign-up-or-in` parameter to run a different flow.
30 |
31 | ```
32 | val descopeFlow = DescopeFlow("https://api.descope.com/login/$descopeProjectId?flow=sign-up-or-in&shadow=false")
33 | ```
34 |
35 | > For more information about Auth Hosting, visit our docs on it [here](https://docs.descope.com/auth-hosting-app)
36 |
37 | 5. Run the simulator within Android Studio - The play button located in the top right
38 |
39 |
40 | ## Learn More
41 | To learn more please see the [Descope Documentation and API reference page](https://docs.descope.com/).
42 |
43 | ## Contact Us
44 | If you need help you can [contact us](https://docs.descope.com/support/)
45 |
46 | ## License
47 | Descope's Native Flows Kotlin Sample App is licensed for use under the terms and conditions of the MIT license Agreement.
48 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_login.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
17 |
18 |
27 |
28 |
36 |
37 |
46 |
47 |
51 |
52 |
63 |
64 |
65 |
66 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/app/src/main/java/com/descope/androiddemo/LoginActivity.kt:
--------------------------------------------------------------------------------
1 | package com.descope.androiddemo
2 |
3 | import android.content.Intent
4 | import android.net.Uri
5 | import android.os.Bundle
6 | import android.view.View
7 | import android.view.View.GONE
8 | import android.view.View.VISIBLE
9 | import android.widget.Toast
10 | import androidx.appcompat.app.AppCompatActivity
11 | import com.descope.Descope
12 | import com.descope.android.DescopeFlow
13 | import com.descope.android.DescopeFlowView
14 | import com.descope.session.DescopeSession
15 | import com.descope.types.AuthenticationResponse
16 | import com.descope.types.DescopeException
17 |
18 | class LoginActivity : AppCompatActivity(), DescopeFlowView.Listener {
19 |
20 | private lateinit var flowContainer: View
21 | private lateinit var loadingIndicator: View
22 |
23 | override fun onCreate(savedInstanceState: Bundle?) {
24 | super.onCreate(savedInstanceState)
25 | setContentView(R.layout.activity_login)
26 |
27 | flowContainer = findViewById(R.id.flow_container)
28 | loadingIndicator = findViewById(R.id.loading)
29 | val flowView: DescopeFlowView = findViewById(R.id.flow_view)
30 | val loginButton: View = findViewById(R.id.login_button)
31 | val closeFlowButton: View = findViewById(R.id.close_button)
32 |
33 | hideFlowContainer()
34 |
35 | flowView.listener = this
36 | val descopeFlow = DescopeFlow("https://api.descope.com/login/$descopeProjectId?flow=sign-up-or-in&shadow=false") // This should be wherever you host your flow
37 | loginButton.setOnClickListener {
38 | loadingIndicator.visibility = VISIBLE
39 | flowView.run(descopeFlow)
40 | }
41 |
42 | closeFlowButton.setOnClickListener {
43 | hideFlowContainer(animated = true)
44 | }
45 | }
46 |
47 | // DescopeFlowView.Listener
48 |
49 | override fun onReady() {
50 | loadingIndicator.visibility = GONE
51 | showFlowContainer()
52 | }
53 |
54 | override fun onSuccess(response: AuthenticationResponse) {
55 | // Manage the session
56 | Descope.sessionManager.manageSession(DescopeSession(response))
57 | launchMainActivity()
58 | }
59 |
60 | override fun onError(exception: DescopeException) {
61 | Toast.makeText(this, "Something went wrong, please try again", Toast.LENGTH_LONG).show()
62 | }
63 |
64 | // internal
65 |
66 | private fun launchMainActivity() {
67 | startActivity(Intent(this, MainActivity::class.java))
68 | finish()
69 | }
70 |
71 | // Animations
72 |
73 | private fun hideFlowContainer(animated: Boolean = false) {
74 | if (animated) {
75 | flowContainer.animate().alpha(0f).setDuration(350L).withEndAction { flowContainer.visibility = GONE }.start()
76 | } else {
77 | flowContainer.visibility = GONE
78 | flowContainer.alpha = 0f
79 | }
80 | }
81 |
82 | private fun showFlowContainer() {
83 | flowContainer.visibility = VISIBLE
84 | flowContainer.animate().alpha(1f).setDuration(350L).start()
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/app/src/main/java/com/descope/androiddemo/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.descope.androiddemo
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import android.view.Menu
6 | import android.view.MenuInflater
7 | import android.view.MenuItem
8 | import android.widget.Button
9 | import android.widget.TextView
10 | import androidx.appcompat.app.AppCompatActivity
11 | import com.descope.Descope
12 | import com.descope.types.RevokeType
13 | import kotlinx.coroutines.Dispatchers
14 | import kotlinx.coroutines.GlobalScope
15 | import kotlinx.coroutines.launch
16 | import kotlinx.coroutines.withContext
17 |
18 | class MainActivity : AppCompatActivity() {
19 |
20 | // The simple API layer resides directly in the Activity for brevity and readability
21 | private val api = Api()
22 |
23 | override fun onCreate(savedInstanceState: Bundle?) {
24 | super.onCreate(savedInstanceState)
25 | setContentView(R.layout.activity_main)
26 | }
27 |
28 | override fun onResume() {
29 | super.onResume()
30 | // ensure the user is logged in
31 | if (ensureSession()) {
32 | launchLoginActivity()
33 | return
34 | }
35 |
36 | val textView: TextView = findViewById(R.id.text)
37 | val apiOutput: TextView = findViewById(R.id.api_output)
38 | val apiButton: Button = findViewById(R.id.api_button)
39 |
40 | textView.text = "Welcome, ${Descope.sessionManager.session!!.user.loginIds.first()}"
41 |
42 | // This code snippet represents a simplified protected API call.
43 | // It uses the GlobalScope and resides in the activity for brevity
44 | // and code readability. It is only an example of an operation you
45 | // might have in a ViewModel or an equivalent layer in your app.
46 | apiButton.setOnClickListener {
47 | GlobalScope.launch(Dispatchers.Main) {
48 | apiOutput.text = ""
49 | try {
50 | val result = withContext(Dispatchers.IO) {
51 | try {
52 | api.myApiCall()
53 | } catch (e: SessionExpired) {
54 | throw e
55 | } catch (e: Exception) {
56 | // handle other errors
57 | println("Request failed: $e")
58 | false
59 | }
60 | }
61 | apiOutput.text = if (result) "API call succeeded" else "API call failed"
62 | } catch (e: Exception) {
63 | apiOutput.text = "The session has expired - the user needs to re-authenticate"
64 | }
65 | }
66 | }
67 | }
68 |
69 | override fun onCreateOptionsMenu(menu: Menu): Boolean {
70 | val inflater: MenuInflater = menuInflater
71 | inflater.inflate(R.menu.main_menu, menu)
72 | return true
73 | }
74 |
75 | override fun onOptionsItemSelected(item: MenuItem): Boolean {
76 | return when (item.itemId) {
77 | R.id.logout_option -> {
78 | val refreshJwt = Descope.sessionManager.session!!.refreshJwt
79 | Descope.sessionManager.clearSession()
80 | GlobalScope.launch {
81 | try {
82 | Descope.auth.revokeSessions(RevokeType.CurrentSession, refreshJwt)
83 | } catch (ignored: Exception) {}
84 | }
85 | launchLoginActivity()
86 | true
87 | }
88 | else -> super.onOptionsItemSelected(item)
89 | }
90 | }
91 |
92 | // Internal
93 |
94 | // Make sure that we have a valid session. This function will
95 | // return true if the session needs to be renewed, false otherwise
96 | private fun ensureSession(): Boolean {
97 | val session = Descope.sessionManager.session
98 | return when {
99 | session == null -> true
100 | session.refreshToken.isExpired -> {
101 | Descope.sessionManager.clearSession()
102 | true
103 | }
104 | else -> false
105 | }
106 | }
107 |
108 | private fun launchLoginActivity() {
109 | startActivity(Intent(this, LoginActivity::class.java))
110 | finish()
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/app/src/main/java/com/descope/androiddemo/Api.kt:
--------------------------------------------------------------------------------
1 | package com.descope.androiddemo
2 |
3 | import com.descope.Descope
4 | import org.json.JSONObject
5 | import java.net.URL
6 | import java.net.URLConnection
7 | import javax.net.ssl.HttpsURLConnection
8 |
9 | // A class representing any number of exceptions that might
10 | // be thrown from the network layer. In this use case, there's
11 | // only one.
12 | class SessionExpired: Exception()
13 |
14 | // A class representing a very simplified network layer
15 | class Api {
16 |
17 | // This function is an example call and should not be used as is.
18 | // It represents an API call to your backend the requires the
19 | // user to be authenticated
20 | suspend fun myApiCall(): Boolean {
21 | val url = URL("https://api.descope.com/v1/auth/validate")
22 | val response = sendRequestWithSession(url, "POST", emptyMap())
23 | return (response.code == HttpsURLConnection.HTTP_OK)
24 | }
25 |
26 | private suspend fun sendRequestWithSession(url: URL, method: String, body: Map?): Response {
27 | val session = Descope.sessionManager.session ?: throw Exception("User is not logged in - cannot perform protected API")
28 |
29 | // refreshSessionIfNeeded will actively refresh the session only
30 | // if it is about to expire. Otherwise it is a no-op.
31 | // If it throws - the request fails and should be treated as a
32 | // refresh failure
33 | try {
34 | Descope.sessionManager.refreshSessionIfNeeded()
35 | } catch (e: Exception) {
36 | // refresh failed - the user must re-authenticate
37 | throw SessionExpired()
38 | }
39 |
40 | // perform the request
41 | var result = sendRequest(url, method, body, session.sessionJwt)
42 |
43 | // If the request is unauthorized - try to refresh
44 | if (result.code == HttpsURLConnection.HTTP_UNAUTHORIZED) {
45 |
46 | // if the refresh token is expired the user must re-authenticate
47 | if (session.refreshToken.isExpired) {
48 | throw SessionExpired()
49 | }
50 |
51 | // try to refresh
52 | try {
53 | val refreshResponse = Descope.auth.refreshSession(session.refreshJwt)
54 | Descope.sessionManager.updateTokens(refreshResponse)
55 | } catch (e: Exception) {
56 | // refresh failed - the user must re-authenticate
57 | throw SessionExpired()
58 | }
59 |
60 | // retry original request
61 | result = sendRequest(url, method, body, session.sessionJwt)
62 | }
63 | return result
64 | }
65 |
66 |
67 | private fun addAuthHeader(connection: URLConnection, sessionJwt: String) {
68 | connection.setRequestProperty("Authorization", "Bearer $descopeProjectId:$sessionJwt")
69 | }
70 |
71 | private fun sendRequest(url: URL, method: String, body: Map?, sessionJwt: String): Response {
72 | val connection = url.openConnection() as HttpsURLConnection
73 | try {
74 | connection.requestMethod = method
75 | connection.setRequestProperty("Accept", "application/json")
76 | addAuthHeader(connection, sessionJwt)
77 |
78 | Descope.sessionManager.session
79 |
80 | // Send body if needed
81 | body?.run {
82 | connection.setRequestProperty("Content-Type", "application/json")
83 | connection.doOutput = true
84 | // Send the request
85 | connection.outputStream.bufferedWriter().use {
86 | it.write(JSONObject(this).toString())
87 | it.flush()
88 | }
89 | }
90 |
91 | // Return response
92 | val responseCode = connection.responseCode
93 | val responseBody = if (responseCode == HttpsURLConnection.HTTP_OK) {
94 | connection.inputStream.bufferedReader().use { it.readText() }
95 | } else {
96 | connection.errorStream.bufferedReader().use { it.readText() }
97 | }
98 | println("Received: $responseCode, $responseBody")
99 | return Response(code = responseCode, body = responseBody)
100 | } finally {
101 | connection.disconnect()
102 | }
103 | }
104 | }
105 |
106 | private data class Response(
107 | val code: Int,
108 | val body: String,
109 | )
110 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------