Skip to content

Commit

Permalink
refactor: make objects internal and move pkce variable out of requests (
Browse files Browse the repository at this point in the history
#32)

* refactor: make objects internal and move pkce variable out of requests

* fix: remove logs
  • Loading branch information
Varunalingam authored Dec 18, 2021
1 parent f221900 commit 9ec2d30
Show file tree
Hide file tree
Showing 9 changed files with 55 additions and 41 deletions.
6 changes: 3 additions & 3 deletions DauthSDK/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ android {
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro"

buildConfigField("String", "CLIENT_ID", "\"${parsedJson.client_id}\"")
buildConfigField("String", "REDIRECT_URI", "\"${parsedJson.redirect_uri}\"")
buildConfigField("String", "CLIENT_SECRET", "\"${parsedJson.client_secret}\"")
buildConfigField("String", "DAUTH_CLIENT_ID", "\"${parsedJson.client_id}\"")
buildConfigField("String", "DAUTH_REDIRECT_URI", "\"${parsedJson.redirect_uri}\"")
buildConfigField("String", "DAUTH_CLIENT_SECRET", "\"${parsedJson.client_secret}\"")
}

buildTypes {
Expand Down
70 changes: 41 additions & 29 deletions DauthSDK/src/main/java/edu/nitt/delta/DAuth.kt
Original file line number Diff line number Diff line change
Expand Up @@ -34,28 +34,30 @@ object DAuth {
* clientCreds [ClientCredentials] storing the credentials obtained after client registration in auth.delta.nitt.edu
*/
private var currentUser: User? = null
private var codeVerifier:String? = null
private val clientCreds: ClientCredentials = ClientCredentials(
BuildConfig.CLIENT_ID,
BuildConfig.REDIRECT_URI,
BuildConfig.CLIENT_SECRET
private val clientCredentials: ClientCredentials = ClientCredentials(
BuildConfig.DAUTH_CLIENT_ID,
BuildConfig.DAUTH_REDIRECT_URI,
BuildConfig.DAUTH_CLIENT_SECRET
)

/**
* Wrapper function for sign-in functionality for java consumer
*
* @param activity Activity
* @param authorizationRequest AuthorizationRequest
* @param isPkceEnabled Boolean which tells whether to choose pkce workflow
* @param signInListener ResultListener<Result>
*/
fun signIn(
activity: Activity,
authorizationRequest: AuthorizationRequest,
isPkceEnabled: Boolean,
signInListener: ResultListener<Result>
) {
signIn(
activity,
authorizationRequest,
isPkceEnabled,
onSuccess = { result -> signInListener.onSuccess(result) },
onFailure = { exception -> signInListener.onFailure(exception) }
)
Expand All @@ -66,38 +68,38 @@ object DAuth {
*
* @param activity Activity
* @param authorizationRequest AuthorizationRequest
* @param isPkceEnabled Boolean which tells whether to choose pkce workflow
* @param onSuccess Lambda Function that is called on successfull login taking Result as member and returns unit
* @param onFailure Lambda Function that is called on failure taking Exception as member and returns unit
*/
fun signIn(
activity: Activity,
authorizationRequest: AuthorizationRequest,
isPkceEnabled: Boolean,
onSuccess: (Result) -> Unit,
onFailure: (Exception) -> Unit
) {
requestAuthorization(
activity,
authorizationRequest,
isPkceEnabled,
onFailure = { errorState -> onFailure(Exception(errorState.toString())) },
onSuccess = { authorizationResponse ->
if (authorizationResponse.state == authorizationRequest.state) {
fetchToken(
authorizationRequest,
TokenRequest(
client_id = clientCreds.clientId,
client_secret = clientCreds.clientSecret,
grant_type = authorizationRequest.grant_type.toString(),
code = authorizationResponse.authorizationCode,
redirect_uri = clientCreds.redirectUri
code_verifier = authorizationResponse.codeVerifier
),
isPkceEnabled,
onFailure = { e -> onFailure(e) },
onSuccess = { token ->
if (authorizationRequest.scopes.contains(Scope.User)) {
fetchUserDetails(
token.access_token,
onFailure = { e -> onFailure(e) }
) { user ->
currentUser = user
if(authorizationRequest.scopes.contains(Scope.OpenID)){
fetchFromJwt(
authorizationRequest,
Expand Down Expand Up @@ -137,16 +139,19 @@ object DAuth {
*
* @param activity Activity
* @param authorizationRequest AuthorizationRequest
* @param isPkceEnabled Boolean which tells whether to choose pkce workflow
* @param authorizationListener ResultListener<AuthorizationResponse>
*/
fun requestAuthorization(
activity: Activity,
authorizationRequest: AuthorizationRequest,
isPkceEnabled: Boolean,
authorizationListener: ResultListener<AuthorizationResponse>
) {
requestAuthorization(
activity,
authorizationRequest,
isPkceEnabled,
onFailure = { authorizationErrorType -> authorizationListener.onFailure(Exception("$authorizationErrorType")) },
onSuccess = { authorizationResponse ->
authorizationListener.onSuccess(
Expand All @@ -161,12 +166,14 @@ object DAuth {
*
* @param activity Activity
* @param authorizationRequest AuthorizationRequest
* @param isPkceEnabled Boolean which tells whether to choose pkce workflow
* @param onFailure Lambda function called on failure taking AuthorizationErrorType as member and returns unit
* @param onSuccess Lambda function called on successful authorization taking AuthorizationResponse as member and returns unit
*/
fun requestAuthorization(
activity: Activity,
authorizationRequest: AuthorizationRequest,
isPkceEnabled: Boolean,
onFailure: (AuthorizationErrorType) -> Unit,
onSuccess: (AuthorizationResponse) -> Unit
) {
Expand All @@ -183,21 +190,19 @@ object DAuth {
.scheme(Scheme)
.authority(BaseAuthority)
.appendPath("authorize")
.appendQueryParameter("client_id", clientCreds.clientId)
.appendQueryParameter("redirect_uri", clientCreds.redirectUri)
.appendQueryParameter(
"response_type",
authorizationRequest.response_type.toString()
)
.appendQueryParameter("client_id", clientCredentials.clientId)
.appendQueryParameter("redirect_uri", clientCredentials.redirectUri)
.appendQueryParameter("response_type", authorizationRequest.response_type.toString())
.appendQueryParameter("grant_type", authorizationRequest.grant_type.toString())
.appendQueryParameter("state", authorizationRequest.state)
.appendQueryParameter("scope", Scope.combineScopes(authorizationRequest.scopes))
.appendQueryParameter("nonce", authorizationRequest.nonce)
if(authorizationRequest.isPkceEnabled){
var codeVerifier: String? = ""
if(isPkceEnabled){
try {
codeVerifier = pkceUtil.generateCodeVerifier()
uriBuilder.appendQueryParameter("code_challenge",pkceUtil.generateCodeChallenge(
codeVerifier!!,pkceUtil.getCodeChallengeMethod()))
codeVerifier,pkceUtil.getCodeChallengeMethod()))
uriBuilder.appendQueryParameter("code_challenge_method",pkceUtil.getCodeChallengeMethod())
}catch (e: Exception){
onFailure(AuthorizationErrorType.UnableToGenerateCodeVerifier)
Expand All @@ -211,13 +216,15 @@ object DAuth {
onFailure = { onFailure(AuthorizationErrorType.ServerDownError) }
) { url ->
val uri: Uri = Uri.parse(url)
if (url.startsWith(clientCreds.redirectUri)) {
if (url.startsWith(clientCredentials.redirectUri)) {
if (uri.query.isNullOrBlank() or uri.query.isNullOrEmpty()) {
onFailure(AuthorizationErrorType.AuthorizationDenied)
} else {
val authorizationResponse = AuthorizationResponse(
uri.getQueryParameter("code") ?: "",
uri.getQueryParameter("state") ?: ""
uri.getQueryParameter("state") ?: "",
codeVerifier ?: "",
isPkceEnabled
)
onSuccess(authorizationResponse)
}
Expand All @@ -243,18 +250,18 @@ object DAuth {
/**
* Wrapper function to fetch the auth token for java consumers
*
* @param authorizationRequest AuthorizationRequest
* @param request TokenRequest
* @param isPkceEnabled Boolean which tells whether to choose pkce workflow
* @param fetchTokenListener ResultListener<Token>
*/
fun fetchToken(
authorizationRequest: AuthorizationRequest,
request: TokenRequest,
isPkceEnabled: Boolean,
fetchTokenListener: ResultListener<Token>
) {
fetchToken(
authorizationRequest,
request,
isPkceEnabled,
onFailure = { exception -> fetchTokenListener.onFailure(exception) },
onSuccess = { token -> fetchTokenListener.onSuccess(token) }
)
Expand All @@ -263,21 +270,23 @@ object DAuth {
/**
* Fetches the auth token
*
* @param authorizationRequest AuthorizationRequest
* @param request TokenRequest
* @param isPkceEnabled Boolean which tells whether to choose pkce workflow
* @param onFailure Lambda function called on failure taking [Exception] as member and returns unit
* @param onSuccess Lambda function called after fetching token successfully taking [Token] as member and returns unit
*/
fun fetchToken(
authorizationRequest: AuthorizationRequest,
request: TokenRequest,
isPkceEnabled: Boolean,
onFailure: (Exception) -> Unit,
onSuccess: (Token) -> Unit
) {
var requestAsMap :Map<String,String> = request.toMap()
if(authorizationRequest.isPkceEnabled) {
requestAsMap = requestAsMap.plus(Pair("code_verifier", codeVerifier!!))
requestAsMap = requestAsMap.minus("client_secret")
requestAsMap = requestAsMap.plus(Pair("client_id", clientCredentials.clientId))
requestAsMap = requestAsMap.plus(Pair("redirect_uri", clientCredentials.redirectUri))
if(!isPkceEnabled){
requestAsMap = requestAsMap.plus(Pair("client_secret", clientCredentials.clientSecret))
requestAsMap = requestAsMap.minus("code_verifier")
}
RetrofitInstance.api.getToken(requestAsMap).enqueue(object : Callback<Token> {
override fun onResponse(call: Call<Token>, response: Response<Token>) {
Expand Down Expand Up @@ -329,7 +338,10 @@ object DAuth {
onFailure(Exception(response.code().toString()))
return
}
response.body()?.let { onSuccess(it) }
response.body()?.let {
currentUser = it
onSuccess(it)
}
}

override fun onFailure(call: Call<User>, t: Throwable) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import android.accounts.AccountManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import edu.nitt.delta.api.RetrofitInstance
import edu.nitt.delta.constants.ErrorCodeConstants
import edu.nitt.delta.constants.ErrorMessageConstants
Expand Down
2 changes: 1 addition & 1 deletion DauthSDK/src/main/java/edu/nitt/delta/helpers/PkceUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.security.SecureRandom

class PkceUtil {
internal class PkceUtil {
/**
* encodeSettings [encodeSettings] that stores constraints for encoding to string as int variable
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,5 @@ data class AuthorizationRequest(
val grant_type: GrantType,
val state: String,
val scopes: List<Scope>,
val nonce: String,
val isPkceEnabled: Boolean
val nonce: String
)
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@ package edu.nitt.delta.models

data class AuthorizationResponse(
val authorizationCode : String,
val state : String
val state : String,
val codeVerifier: String?,
val isPkceEnabled: Boolean
)
4 changes: 1 addition & 3 deletions DauthSDK/src/main/java/edu/nitt/delta/models/TokenRequest.kt
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package edu.nitt.delta.models

data class TokenRequest(
val client_id:String,
val client_secret:String,
val grant_type:String,
val code: String,
val redirect_uri: String
val code_verifier: String?
)
4 changes: 2 additions & 2 deletions sampleApp/src/Java/java/edu/nitt/delta/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ public void onClick(View view) {
GrantType.AuthorizationCode,
"1ww12",
scopes,
"ncsasd",
true),
"ncsasd"),
true,
new ResultListener<Result>() {
@Override
public void onSuccess(@NonNull Result result) {
Expand Down
2 changes: 2 additions & 0 deletions sampleApp/src/Kotlin/java/edu/nitt/delta/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class MainActivity : AppCompatActivity() {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val signInButton: DeltaButton = findViewById(R.id.sign_in_button)

signInButton.setOnClickListener {
DAuth.signIn(
activity = this,
Expand All @@ -28,6 +29,7 @@ class MainActivity : AppCompatActivity() {
listOf(Scope.OpenID,Scope.Profile,Scope.Email,Scope.User),
"ncsasd"
),
isPkceEnabled = true,
onSuccess = { result: Result ->
println("Success: $result")
},
Expand Down

0 comments on commit 9ec2d30

Please sign in to comment.