lundi 3 mai 2021

Finding a specific pattern in a boolean array

I am working on a project and am getting stuck on the following bit : I have a boolean array and I would like to determine if a specific pattern is present in this array.

For example, let's imagine I have this boolean array : [True, False, False, True, False, False, True, False, True, True, True] and I would like to know if it contains the following pattern [False, False, True, False].

My first idea was to loop through all values of the boolean array, define a variable that counts the number of consecutive "False" then loops again to find if "True" is following that sequence, etc... But it seems a bit tedious and I imagine there is a better way to do this...

Any advice would be very welcomed ! Thank you

Converting Kotlin functional programming code to object oriented classes

I have the code for the design pattern Chain Of Resposibility in functional programming. I'm trying to convert it to regular OOP classes. Following is the working code for the design pattern:

Functional Programming Code

enum class LogLevel {
    INFO, DEBUG, WARNING, ERROR, FUNCTIONAL_MESSAGE, FUNCTIONAL_ERROR;

    companion object {
        public fun all(): Array<LogLevel> {
            return values()
        }
    }
}

/**
 * Handler: Contains a method for building a chain of handlers. 
 * It also declares a method for executing a request.
 */
fun interface Logger {
    fun message(message: String, severity: LogLevel)

    fun appendNext(nextLogger: Logger): Logger {
        return Logger { message, severity ->
            message(message, severity)
            nextLogger.message(message, severity)
        }
    }
}

/**
 * Base Handler: Base handler is an optional class where you can put the boilerplate
 * code that’s common to all handler classes.
 *
 * @param writeMessage is the container that acts as the next link in the chain of handlers.
 */
fun writeLogger(vararg levels: LogLevel,
    writeMessage: (String) -> Unit
): Logger {
    val specifiedLevelsSet = EnumSet.copyOf(listOf(*levels))
    return Logger { message, requestedLogLevel ->
        if (specifiedLevelsSet.contains(requestedLogLevel)) {
            writeMessage(message)
        }
    }
}

/**
 * Concrete Handlers: Concrete handlers contain the actual code for processing requests.
 */
fun consoleLogger(vararg levels: LogLevel) =
    writeLogger(*levels) { message -> System.err.println("Writing to console: $message") }

fun emailLogger(vararg levels: LogLevel) =
    writeLogger(*levels) { message -> System.err.println("Sending via email: $message") }

fun fileLogger(vararg levels: LogLevel) =
    writeLogger(*levels) { message -> System.err.println("Writing to Log File: $message") }

/**
 * Client:
 */
fun main() {

    // Build an immutable chain of responsibility
    val logger = consoleLogger(*LogLevel.all())
        .appendNext(emailLogger(LogLevel.FUNCTIONAL_MESSAGE, LogLevel.FUNCTIONAL_ERROR))
        .appendNext(fileLogger(LogLevel.WARNING, LogLevel.ERROR))

    // Handled by consoleLogger since it has been set to log all levels
    logger.message("Entering function ProcessOrder().", LogLevel.DEBUG)
    logger.message("Order record retrieved.", LogLevel.INFO)

    // Handled by consoleLogger and emailLogger since the emailLogger
    // implements FUNCTIONAL_ERROR & FUNCTIONAL_MESSAGE
    logger.message(
        "Unable to Process Order ORD1 Dated D1 For Customer C1.",
        LogLevel.FUNCTIONAL_ERROR
    )
    logger.message("Order Dispatched.", LogLevel.FUNCTIONAL_MESSAGE)

    // Handled by consoleLogger and fileLogger since fileLogger implements WARNING & ERROR
    logger.message("Customer Address details missing in Branch DataBase.", LogLevel.WARNING)
    logger.message("Customer Address details missing in Organization DataBase.", LogLevel.ERROR)
}

My Question

I want to convert the functional programming code to the regular classes for studying purposes. I want to convert fun interface to regular interface and convert the function writeLogger() to abstract class/regular class BaseLogger, consoleLogger() to the class ConsoleLogger, emailLogger() to EmailLogger and so on.


My attempt to convert to OOP classes

I'm having a hard time distributing the functional code above in the various classes below:

interface Logger {
    fun appendNext(nextLogger: Logger)
    fun message(message: String, severity: LogLevel)
}

abstract class BaseLogger(vararg levels: LogLevel) : Logger {
    private var severity: LogLevel? = null
    private var nextLogger: Logger? = null
    private val specifiedLevelsSet = EnumSet.copyOf(listOf(*levels))

    override fun appendNext(nextLogger: Logger) {
        message(message, severity)
        this.nextLogger = nextLogger    // This may be incorrect
    }

    override fun message(message: String, severity: LogLevel) {
        // what to write here?
    }
}

class ConsoleLogger(vararg level: LogLevel) : BaseLogger(*level) {
    private val message: String? = null

    override fun appendNext(nextLogger: Logger) {
        super.appendNext(nextLogger)
        System.err.println("Writing to console: $message")   // Maybe confused here.
    }

    override fun message(message: String, severity: LogLevel) {
        // what to write here?
    }
}

Any input would be much appreciated.

Avoiding accessing unauthorized data - architectural level

I have one SQL Server database that will contain data for multiple customers each customer has admin users to manage his own data related to his employees, I will give each customer a license to use the system to store and manage his business data ( data related to his employees) each employee has an account and has some privileges to do some specific actions and request.

My question, How to permanently prevent customer admin users to access employees of another customer? I am asking about the best practices or Ideas related to the system architecture level to avoid this kind of errors, I don't want to leave the decision to the developer because any wrong SQL query will lead to this issue.

access control layer on events for socket.io?

I would like to ask for suggestions/considerations about using a sort of access control layer with socket.io. I haven't found any information on this topic yet so I'm writing here. I'm wondering if there are correct patterns, if it's an anti-pattern or if my idea will do.

A little bit of context

I'm building an application which allows two different types of client to communicate to each other. The two types of client play two different role, let's say Role1 and Role2. Role1 and Role2 authenticate themselves on the server with a JWT, which they have obtained previously, sent in the auth option when they connect.

Role2's clients may represent anonymous clients. They can, with a special random code, retrieve from the server a special JWT which allow them to authenticate on the socket.io server.

Role2 must not play the Role1 part, so I need a way to control what a role2 client can do.

my idea

My current idea is to introduce an access control layer on events. Basically:

  • the JWT contains a list of events the client is allowed to emit
  • on server side there is a socket-level middleware which checks if the received event is allowed by the list contained in the JWT. If so the event is handled by the listener, otherwise it is discarded. I would like to know if my approach is valid or if there are better approach.

Thanks in advance! 😄

dimanche 2 mai 2021

How to design the system to manage RESTful API keys/credentials for external developers to call

Background

I'm working on a web service with Python as backend using FastAPI. As far as I know, for the front end user authentication and authorized requests there is JWT. Following the best practices, the token would expired in 15 minutes and refreshed before that.

However, if I want to expose some RESTful API endpoints (e.g. read/write data to my database) for other developers (e.g. Stripe users would call Stripe's API with some keys), I need to create a permanent API key with some configurable permission, like the personal access token for Github. It seems to me that using JWT is not a good option because it's not ideal to set long expiration time or ask external developers to refresh tokens frequently.

I had hard time finding related resources for designing such as system to manage these API keys, even though many companies provide this kind of service.

I would imagine the solution to be having a table in the database that stores the API keys with some permission levels as columns and links with the user table. However, with this method, each call from the external developers/service has to query the database to validate permission, which may hurt the response time compared to JWT. I'd like to know if this makes sense what are the best practices.

Questions

  • What is the work flow to generate the API keys for external developers/service to call my API endpoints that need user authentication?
  • How to revoke given API keys?
  • How to configure/validate API keys for different permissions?
  • How to design the table to manage API keys?

What files are consider for model , view and controller in MVC design pattern?

In MVC design pattern in android. which file comes under model, view and controller ? files like activities, fragment, adapter, pojo classes etc. How we can separate in context of MVC ?

Csharp design patterns [closed]

The relation between publisher and subscriber can easily be understood as an analogy to magazine subscription.a.A magazine (publisher) isthe business and publishes magazines (data).b.Ifa customer (subscriber) interested insubscription(subscribe/register), the magazine gets delivered to the customer each month after new edition ispublished.c.(unsubscribe/unregister), disconnects subscription and stops sending new editions to the customer as he/she remains no longer a subscriber after unsubscribing.d.Publisher doesn’t know who the customer areand how theyuse the magazine, hejust delivers magazines to the customers because both are bound in a relationship(loose coupling).Actual Problem StatementAssuming, in a real-world publishing business, HyperMediapublishing company hires you as developer and assigns you task to automate their magazine business. The magazine data consists title, number of pages,publishing dateand content.HyperMediawants anyone who is interested in magazine subscription, to facilitate subscribe/register and unsubscribe/unregister online. The subscribers will be sentan online digital copyin a PDF format each month when it gets published.Required SolutionUsing C# write a solution for HyperMedia publishing business by understanding the above written problem statement in the analogycontext.The solution you provide must be implementing the required design patterns that justify the reusability, extensibility, and maintainability.