mirror of
https://github.com/filebrowser/filebrowser.git
synced 2025-05-08 11:22:10 +00:00

License: MIT Signed-off-by: Henrique Dias <hacdias@gmail.com> Former-commit-id: a44ebfc7a5687b5f51f0ff791335f66ab9f2e8e0 [formerly 9a044fadd8f2ebbb7dbb773273799c26a797f513] [formerly 7f374d016eaf756cfce215dd16a2274bbabe1915 [formerly f55f205ced82d7e05e0ffc158b302b5300409769]] Former-commit-id: 31015ddc5f4fc28c895743f6fe9dcf5488bb4b01 [formerly e439027304a1e49667fafde011e07d043ef0d2ee] Former-commit-id: 0394c60358673b56991364260b1cbe41fa457593
103 lines
2.0 KiB
Go
103 lines
2.0 KiB
Go
package auth
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/filebrowser/filebrowser/v2/settings"
|
|
"github.com/filebrowser/filebrowser/v2/users"
|
|
)
|
|
|
|
// MethodJSONAuth is used to identify json auth.
|
|
const MethodJSONAuth settings.AuthMethod = "json"
|
|
|
|
type jsonCred struct {
|
|
Password string `json:"password"`
|
|
Username string `json:"username"`
|
|
ReCaptcha string `json:"recaptcha"`
|
|
}
|
|
|
|
// JSONAuth is a json implementaion of an Auther.
|
|
type JSONAuth struct {
|
|
ReCaptcha *ReCaptcha
|
|
}
|
|
|
|
// Auth authenticates the user via a json in content body.
|
|
func (a *JSONAuth) Auth(r *http.Request, sto *users.Storage, set *settings.Settings) (*users.User, error) {
|
|
var cred jsonCred
|
|
|
|
if r.Body == nil {
|
|
return nil, os.ErrPermission
|
|
}
|
|
|
|
err := json.NewDecoder(r.Body).Decode(&cred)
|
|
if err != nil {
|
|
return nil, os.ErrPermission
|
|
}
|
|
|
|
// If ReCaptcha is enabled, check the code.
|
|
if a.ReCaptcha != nil && len(a.ReCaptcha.Secret) > 0 {
|
|
ok, err := a.ReCaptcha.Ok(cred.ReCaptcha)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if !ok {
|
|
return nil, os.ErrPermission
|
|
}
|
|
}
|
|
|
|
u, err := sto.Get(set.Scope, cred.Username)
|
|
if err != nil || !users.CheckPwd(cred.Password, u.Password) {
|
|
return nil, os.ErrPermission
|
|
}
|
|
|
|
return u, nil
|
|
}
|
|
|
|
const reCaptchaAPI = "/recaptcha/api/siteverify"
|
|
|
|
// ReCaptcha identifies a recaptcha conenction.
|
|
type ReCaptcha struct {
|
|
Host string `json:"host"`
|
|
Key string `json:"key"`
|
|
Secret string `json:"secret"`
|
|
}
|
|
|
|
// Ok checks if a reCaptcha responde is correct.
|
|
func (r *ReCaptcha) Ok(response string) (bool, error) {
|
|
body := url.Values{}
|
|
body.Set("secret", r.Key)
|
|
body.Add("response", response)
|
|
|
|
client := &http.Client{}
|
|
|
|
resp, err := client.Post(
|
|
r.Host+reCaptchaAPI,
|
|
"application/x-www-form-urlencoded",
|
|
strings.NewReader(body.Encode()),
|
|
)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return false, nil
|
|
}
|
|
|
|
var data struct {
|
|
Success bool `json:"success"`
|
|
}
|
|
|
|
err = json.NewDecoder(resp.Body).Decode(&data)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
return data.Success, nil
|
|
}
|