Skip to content

Instantly share code, notes, and snippets.

View RaheemJnr's full-sized avatar
🎯
Focusing

Raheem Jnr RaheemJnr

🎯
Focusing
View GitHub Profile
/**
*Variables Initialization
* Client Configuration
* client.plugin(HttpSend).intercept { request -> ... }: Adds an interceptor to the HttpSend plugin of the HttpClient. This interceptor will intercept every HTTP request made by the client, allowing for custom logic to be executed before the request is sent and after the response is received.
* Access Token Handling
* val access = localDatabase.getAccessToken(mainRepo.getUserId).first(): Retrieves the current access token for the user from the local database. It assumes that getAccessToken returns a flow or collection, and .first() gets the first element.
*
* request.headers { append("Authorization", "Bearer $access") }: Modifies the HTTP request headers to include the current access token in the Authorization header.
*
* Response Status Check and Refresh Token Handling
fun generalHttpClient(): HttpClient {
val client =
HttpClient(getClientEngine()) {
expectSuccess = true
install(Logging) {
logger = Logger.DEFAULT
level = LogLevel.ALL
logger =
object : Logger {
override fun log(message: String) {
@RaheemJnr
RaheemJnr / JwtControllerPlugin.kt
Created March 30, 2024 15:01
JwtControllerPlugin.kt
/**
* configureSecurity Function
* fun Application.configureSecurity(jwtController: JwtController) { ... }: This extension function is defined for the Application class, taking a JwtController instance as an argument. It's responsible for configuring the security aspects of the Ktor application, particularly JWT authentication.
* Authentication Configuration
* install(Authentication) { ... }: Installs the Authentication feature into the Ktor application. This feature is used to secure your application by authenticating requests.
* JWT Authentication for Access Tokens
* jwt("main_auth_jwt") { ... }: Configures JWT authentication with the name "main_auth_jwt". This is used for authenticating access tokens.
*
* verifier(...): Sets up the JWT verifier by using the verifyToken method of the jwtController, specifying that it should verify access tokens. The verifier is responsible for validating the signatures of incoming tokens to ensure they were issued by the server and haven't been tampered with.
*
@RaheemJnr
RaheemJnr / JwtController.kt
Last active March 30, 2024 14:45
Jwt generate and refresh function
/**
*JwtController Class
* class JwtController(val tokenConfiguration: TokenConfig) { ... }: Defines a controller class for JWT operations, which is initialized with a TokenConfig object containing the configuration for tokens.
*
* val audience = tokenConfiguration.audience: Extracts the audience value from tokenConfiguration and assigns it to the audience property. The audience typically defines the recipients that the JWT is intended for.
*
* val issuer = tokenConfiguration.issuer: Similar to audience, this extracts the issuer value from tokenConfiguration and assigns it to the issuer property. The issuer is the entity that issues the token.
*
* fun generateToken(userId: String, tokenType: String, expirationDate: Long): String { ... }: A method to generate a token with specified userId, tokenType, and expirationDate. It creates a JWT with the specified audience, issuer, and claims (like user ID and token type), and sets an expiration date. It then signs the token with a secret key.
*
/**
* Manages all location related tasks for the app.
*/
//A callback for receiving notifications from the FusedLocationProviderClient.
lateinit var locationCallback: LocationCallback
//The main entry point for interacting with the Fused Location Provider
lateinit var locationProvider: FusedLocationProviderClient
@SuppressLint("MissingPermission")
fun getReadableLocation(latitude: Double, longitude: Double, context: Context): String {
var addressText = ""
val geocoder = Geocoder(context, Locale.getDefault())
try {
val addresses = geocoder.getFromLocation(latitude, longitude, 1)
if (addresses?.isNotEmpty() == true) {
val address = addresses[0]
fun stopLocationUpdate() {
try {
//Removes all location updates for the given callback.
val removeTask = locationProvider.removeLocationUpdates(locationCallback)
removeTask.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(LOCATION_TAG, "Location Callback removed.")
} else {
Log.d(LOCATION_TAG, "Failed to remove Location Callback.")
}
@SuppressLint("MissingPermission")
fun locationUpdate() {
locationCallback.let {
//An encapsulation of various parameters for requesting
// location through FusedLocationProviderClient.
val locationRequest: LocationRequest =
LocationRequest.create().apply {
interval = TimeUnit.SECONDS.toMillis(60)
fastestInterval = TimeUnit.SECONDS.toMillis(30)
maxWaitTime = TimeUnit.MINUTES.toMillis(2)
/**
* Manages all location related tasks for the app.
*/
//A callback for receiving notifications from the FusedLocationProviderClient.
lateinit var locationCallback: LocationCallback
//The main entry point for interacting with the Fused Location Provider
lateinit var locationProvider: FusedLocationProviderClient
@SuppressLint("MissingPermission")
@Composable
fun TextFields() {
Scaffold(
modifier = Modifier
) { contentPadding ->
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.fillMaxSize()