You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
116 lines
2.4 KiB
116 lines
2.4 KiB
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"git.aiterp.net/gisle/wrouter/response"
|
|
)
|
|
|
|
type handler struct {
|
|
}
|
|
|
|
func (h *handler) Handle(path string, w http.ResponseWriter, req *http.Request, user *User) bool {
|
|
// Get the subpath out of the path
|
|
subpath := req.URL.Path[len(path):]
|
|
if subpath[0] == '/' {
|
|
subpath = subpath[1:]
|
|
}
|
|
|
|
method := FindAuthenticator(req.Form.Get("method"))
|
|
if method == nil {
|
|
if user == nil {
|
|
response.Text(w, 400, "Invalid method: "+req.Form.Get("method"))
|
|
return true
|
|
}
|
|
|
|
method = user.method
|
|
}
|
|
|
|
switch strings.ToLower(subpath) {
|
|
case "login":
|
|
{
|
|
if req.Method != "POST" {
|
|
response.Text(w, 405, req.Method+" not allowed")
|
|
return true
|
|
}
|
|
|
|
username := req.Form.Get("username")
|
|
password := req.Form.Get("password")
|
|
|
|
w.Header().Set("X-Auth-Method", method.Name())
|
|
|
|
user, err := method.Login(username, password)
|
|
if err == nil && user != nil {
|
|
sess := OpenSession(user)
|
|
http.SetCookie(w, &http.Cookie{Name: SessionCookieName, Value: sess.ID, Expires: sess.Time.Add(SessionMaxTime)})
|
|
|
|
response.JSON(w, 200, sess)
|
|
} else {
|
|
response.Text(w, 401, "Login failed")
|
|
}
|
|
}
|
|
case "register":
|
|
{
|
|
if req.Method != "POST" {
|
|
response.Text(w, 405, req.Method+" not allowed")
|
|
return true
|
|
}
|
|
|
|
data := make(map[string]string)
|
|
for key, value := range req.Form {
|
|
if key != "username" && key != "password" && key != "method" {
|
|
data[key] = value[0]
|
|
}
|
|
}
|
|
|
|
username := req.Form.Get("username")
|
|
password := req.Form.Get("password")
|
|
|
|
user, err := method.Register(username, password, data)
|
|
if err == nil && user != nil {
|
|
sess := OpenSession(user)
|
|
http.SetCookie(w, &http.Cookie{Name: SessionCookieName, Value: sess.ID, Expires: sess.Time.Add(SessionMaxTime)})
|
|
|
|
response.JSON(w, 200, sess)
|
|
} else {
|
|
response.Text(w, 401, "Register failed")
|
|
}
|
|
}
|
|
case "logout-all":
|
|
{
|
|
if req.Method != "POST" {
|
|
response.Text(w, 405, req.Method+" not allowed")
|
|
return true
|
|
}
|
|
|
|
if user != nil {
|
|
ClearSessions(user)
|
|
response.Empty(w)
|
|
} else {
|
|
response.Text(w, 401, "Not logged in")
|
|
}
|
|
}
|
|
case "status":
|
|
{
|
|
if req.Method != "GET" {
|
|
response.Text(w, 405, req.Method+" not allowed")
|
|
return true
|
|
}
|
|
|
|
if user != nil {
|
|
response.JSON(w, 200, user)
|
|
} else {
|
|
response.Text(w, 401, "Not logged in")
|
|
}
|
|
}
|
|
default:
|
|
{
|
|
response.Text(w, 404, "Operation not found: "+subpath)
|
|
}
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
var Handler = &handler{}
|