martini-contrib / auth

Martini handlers for authentication.
MIT License
67 stars 32 forks source link

Make BasicFunc support dependency injection #18

Open vpereira opened 9 years ago

vpereira commented 9 years ago

I was able to solve this problem, using db as global variable. However, would be better if I could pass it to my callback (that today, accepts just two params - user and password). Could you support a variable number of params, where I could for example pass the db handle? I stumbled many times in this question and either I found a "use another middlewear" or "set your db variable global"..

attilaolah commented 9 years ago

This is a little tricky because (I think) we would have to inject the username and password in the context as well in order for BasicFunc to be able to access it.

vpereira commented 9 years ago

maybe if the function accepts not 2 strings, but a struct, where at least includes the fields username and password?

attilaolah commented 9 years ago

No you can't do that with a struct.

You can, however, do that with an interface, but that seems like too much complexity. After all, you could just pass in the db in a closure. Or pass in a method to auth.BasicFunc, and have the method access the db via the struct.


func main() {
    // …
    m.Use(auth.BasicFunc(&(DBAuth{…}).Authenticate))
}

type DBAuth struct {
    // …
}

func (a *DBAuth) Authenticate(username, password string) bool {
    db := a.Database()
    // authenticate username and password using the db…
}

func (a *DBAuth) Database() *DB {
    return &DB{…}
}

…you get the idea.


Summary: what you want can already be achieved without DI. I don't see a great need for DI here, but, if someone wants to implement this, why not. Just send a PR.