60 lines
1.2 KiB
Go
60 lines
1.2 KiB
Go
package auth
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
|
|
"git.1248.nz/1248/Otfe/models"
|
|
)
|
|
|
|
type auth func(http.ResponseWriter, *http.Request, models.User)
|
|
|
|
func User(h auth) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
user, _ := getUserSession(r)
|
|
h(w, r, user)
|
|
}
|
|
}
|
|
|
|
func Perm(handler auth, fallback auth, perm string) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
user, err := getUserSession(r)
|
|
if err != nil {
|
|
http.Redirect(w, r, "/login", http.StatusFound)
|
|
return
|
|
}
|
|
if user.HasPermission(perm) {
|
|
handler(w, r, user)
|
|
} else {
|
|
if fallback == nil {
|
|
UnAuth(w)
|
|
} else {
|
|
fallback(w, r, user)
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
func getUserSession(r *http.Request) (models.User, error) {
|
|
var session models.Session
|
|
var user models.User
|
|
//Check for session in db
|
|
err := session.Get(r)
|
|
if err == nil {
|
|
//Get user associated with the session
|
|
err = user.Read("_id", session.UserID)
|
|
if err == nil {
|
|
return user, nil
|
|
|
|
}
|
|
}
|
|
return user, errors.New("User not logged in")
|
|
}
|
|
|
|
func UnAuth(w http.ResponseWriter) {
|
|
http.Error(w, "You are not authorized to view this page",
|
|
http.StatusForbidden)
|
|
}
|