-
Notifications
You must be signed in to change notification settings - Fork 1
Integrate to your system
In the Getting started article you have setted up an simple REST API to do simple auth stuff.
Now you want to build some more, how about an "support ticket" site where:
- Only logged user can post a ticket.
- Only the owner or admin can view/delete the ticket.
kiddstuff/auth package provide auth.HANDLER_REGISTER function (in fact a function variale overided by manager) which have the signature:
func(fn auth.HandleFunc, owner bool, pri []string) http.Handler
The HANDLER_REGISTER wrapper function use the OR logic, thats mean:
auth.HANDLER_REGISTER(FooHandler, true, []{"manage_content", "do_foo"})
will trigger the FooHandler if the current user are the owner or he can "manage_content" or "do_foo".
To use it for our support ticket site:
// the CreateTicket only run for a "logged" user
r.Handle("/users/{user_id}/tickets",
auth.HANDLER_REGISTER(CreateTicket, true, nil)).Methods("POST")
r.Handle("/users/{user_id}/tickets/{ticket_id}",
auth.HANDLER_REGISTER(GetTicket, true, []string{"manage_content"})).Methods("GET")
r.Handle("/users/{user_id}/tickets/{ticket_id}",
auth.HANDLER_REGISTER(DeleteTicket, true, []string{"manage_content"})).Methods("DELETE")
These routes not really pretty, you may ask why we include "/users/{user_id}" for these paths?
It because the HANDLER_REGISTER will look for the user_id param in request path, compare it with the current user's ID to determine if they are the owner or not (and of course an owner is a logged user).
Note: By running the setup.go we already have an admin an accoutn with "manage_user", "manage_setting", "manage_content" privileges.
Next we need to implemenet the handler functions, creat a tickets.go file in the same folder of main.go.
tickets.go
import (
"github.com/kidstuff/auth"
"labix.org/v2/mgo/bson"
"net/http"
)
type Ticket struct {
Id bson.ObjectId `bson:"_id"`
Content string
}
func CreateTicket(ctx *auth.AuthContext, rw http.ResponseWriter, req *http.Request) (int, error) {
return http.StatusOK, nil
}
func GetTicket(ctx *auth.AuthContext, rw http.ResponseWriter, req *http.Request) (int, error) {
return http.StatusOK, nil
}
func DeleteTicket(ctx *auth.AuthContext, rw http.ResponseWriter, req *http.Request) (int, error) {
return http.StatusOK, nil
}
CreateTicket, GetTicket and DeleteTicket have the auth.HandleFunc signature:
With the auth.AuthContext allow us to access some resource like Loggin and Notification system (remember what you do in main.go?) and many more.