canape/auth/auth.go
2016-02-20 19:37:48 +01:00

99 lines
2.3 KiB
Go

package auth
import (
"fmt"
"net/http"
"github.com/gorilla/sessions"
"golang.org/x/crypto/bcrypt"
)
var (
// ErrInvalidPassword returned when password and hash don't match
ErrInvalidPassword = fmt.Errorf("Invalid password")
// ErrCorrupted returned when session have been corrupted
ErrCorrupted = fmt.Errorf("Corrupted session")
)
// Authorizer handle sesssion
type Authorizer struct {
cookiejar *sessions.CookieStore
cookieName string
peeper string
cost int
}
// New Authorizer peeper is like a salt but not stored in database,
// cost is the bcrypt cost for hashing the password
func New(peeper, cookieName, cookieKey string, cost int) *Authorizer {
return &Authorizer{
cookiejar: sessions.NewCookieStore([]byte(cookieKey)),
cookieName: cookieName,
peeper: peeper,
cost: cost,
}
}
// GenHash generates a new hash from a password
func (a *Authorizer) GenHash(password string) (string, error) {
b, err := bcrypt.GenerateFromPassword([]byte(password+a.peeper), a.cost)
if err != nil {
return "", err
}
return string(b), nil
}
// Login cheks password and updates cookie info
func (a *Authorizer) Login(rw http.ResponseWriter, req *http.Request, username, hash, password string) error {
cookie, err := a.cookiejar.Get(req, a.cookieName)
if err != nil {
return err
}
err = bcrypt.CompareHashAndPassword([]byte(hash), []byte(password+a.peeper))
if err != nil {
return ErrInvalidPassword
}
cookie.Values["username"] = username
err = cookie.Save(req, rw)
if err != nil {
return err
}
return nil
}
// Logout remove cookie info
func (a *Authorizer) Logout(rw http.ResponseWriter, req *http.Request) error {
cookie, err := a.cookiejar.Get(req, a.cookieName)
if err != nil {
return err
}
cookie.Values["username"] = ""
cookie.Options.MaxAge = -1 // kill the cookie
err = cookie.Save(req, rw)
if err != nil {
return err
}
return nil
}
// CurrentUser returns the logged in username from session
func (a *Authorizer) CurrentUser(rw http.ResponseWriter, req *http.Request) (string, error) {
cookie, err := a.cookiejar.Get(req, a.cookieName)
if err != nil {
return "", err
}
username := cookie.Values["username"]
if !cookie.IsNew && username != nil {
str, ok := username.(string)
if !ok {
return "", ErrCorrupted
}
return str, nil
}
return "", nil
}