filebrowser/auth.go

177 lines
4.0 KiB
Go
Raw Normal View History

2017-07-02 16:40:52 +00:00
package filemanager
import (
2017-07-25 08:01:29 +00:00
"crypto/rand"
2017-07-03 07:59:49 +00:00
"encoding/json"
2017-07-02 16:40:52 +00:00
"net/http"
"strings"
2017-07-02 16:40:52 +00:00
"time"
2017-07-03 07:59:49 +00:00
"golang.org/x/crypto/bcrypt"
2017-07-02 16:40:52 +00:00
jwt "github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
)
2017-07-03 07:59:49 +00:00
// authHandler proccesses the authentication for the user.
func authHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {
2017-08-02 13:10:05 +00:00
// NoAuth instances shouldn't call this method.
if c.NoAuth {
return 0, nil
}
2017-07-03 07:59:49 +00:00
// Receive the credentials from the request and unmarshal them.
var cred User
if r.Body == nil {
return http.StatusForbidden, nil
}
err := json.NewDecoder(r.Body).Decode(&cred)
if err != nil {
return http.StatusForbidden, nil
}
// Checks if the user exists.
u, ok := c.Users[cred.Username]
2017-07-03 07:59:49 +00:00
if !ok {
return http.StatusForbidden, nil
}
// Checks if the password is correct.
if !checkPasswordHash(cred.Password, u.Password) {
return http.StatusForbidden, nil
}
2017-07-02 16:40:52 +00:00
c.User = u
2017-07-06 08:31:07 +00:00
return printToken(c, w)
2017-07-02 16:40:52 +00:00
}
2017-07-03 07:59:49 +00:00
// renewAuthHandler is used when the front-end already has a JWT token
// and is checking if it is up to date. If so, updates its info.
func renewAuthHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {
2017-07-03 07:59:49 +00:00
ok, u := validateAuth(c, r)
if !ok {
return http.StatusForbidden, nil
}
c.User = u
2017-07-06 08:31:07 +00:00
return printToken(c, w)
}
// claims is the JWT claims.
type claims struct {
User
2017-08-02 13:10:05 +00:00
NoAuth bool `json:"noAuth"`
2017-07-06 08:31:07 +00:00
jwt.StandardClaims
}
// printToken prints the final JWT token to the user.
func printToken(c *RequestContext, w http.ResponseWriter) (int, error) {
2017-07-06 08:31:07 +00:00
// Creates a copy of the user and removes it password
// hash so it never arrives to the user.
u := User{}
u = *c.User
2017-07-06 08:31:07 +00:00
u.Password = ""
// Builds the claims.
2017-07-03 07:59:49 +00:00
claims := claims{
u,
2017-08-02 13:10:05 +00:00
c.NoAuth,
2017-07-03 07:59:49 +00:00
jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 24).Unix(),
Issuer: "File Manager",
},
}
2017-07-02 16:40:52 +00:00
2017-07-06 08:31:07 +00:00
// Creates the token and signs it.
2017-07-03 07:59:49 +00:00
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
2017-08-02 13:10:05 +00:00
signed, err := token.SignedString(c.key)
2017-07-06 08:31:07 +00:00
2017-07-03 07:59:49 +00:00
if err != nil {
return http.StatusInternalServerError, err
2017-07-02 16:40:52 +00:00
}
2017-07-06 08:31:07 +00:00
// Writes the token.
2017-07-29 13:19:09 +00:00
w.Header().Set("Content-Type", "cty")
2017-08-02 13:10:05 +00:00
w.Write([]byte(signed))
2017-07-03 07:59:49 +00:00
return 0, nil
}
2017-07-03 14:19:17 +00:00
type extractor []string
func (e extractor) ExtractToken(r *http.Request) (string, error) {
token, _ := request.AuthorizationHeaderExtractor.ExtractToken(r)
2017-07-25 10:57:27 +00:00
// Checks if the token isn't empty and if it contains two dots.
// The former prevents incompatibility with URLs that previously
// used basic auth.
2017-07-25 10:57:27 +00:00
if token != "" && strings.Count(token, ".") == 2 {
2017-07-03 14:19:17 +00:00
return token, nil
}
cookie, err := r.Cookie("auth")
if err != nil {
return "", request.ErrNoTokenInRequest
2017-07-03 14:19:17 +00:00
}
return cookie.Value, nil
2017-07-03 14:19:17 +00:00
}
2017-07-03 07:59:49 +00:00
// validateAuth is used to validate the authentication and returns the
// User if it is valid.
func validateAuth(c *RequestContext, r *http.Request) (bool, *User) {
2017-08-02 13:10:05 +00:00
if c.NoAuth {
c.User = c.DefaultUser
return true, c.User
}
2017-07-03 07:59:49 +00:00
keyFunc := func(token *jwt.Token) (interface{}, error) {
return c.key, nil
2017-07-03 07:59:49 +00:00
}
var claims claims
token, err := request.ParseFromRequestWithClaims(r,
2017-07-03 14:19:17 +00:00
extractor{},
2017-07-03 07:59:49 +00:00
&claims,
keyFunc,
)
if err != nil || !token.Valid {
return false, nil
}
u, ok := c.Users[claims.User.Username]
2017-07-03 07:59:49 +00:00
if !ok {
return false, nil
}
c.User = u
2017-07-03 07:59:49 +00:00
return true, u
}
// hashPassword generates an hash from a password using bcrypt.
func hashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(bytes), err
}
// checkPasswordHash compares a password with an hash to check if they match.
func checkPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
2017-07-25 08:01:29 +00:00
// generateRandomBytes returns securely generated random bytes.
// It will return an error if the system's secure random
// number generator fails to function correctly, in which
// case the caller should not continue.
func generateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
// Note that err == nil only if we read len(b) bytes.
if err != nil {
return nil, err
2017-07-03 07:59:49 +00:00
}
2017-07-25 08:01:29 +00:00
return b, nil
2017-07-02 16:40:52 +00:00
}