This repository has been archived on 2024-03-28. You can view files and clone it, but cannot push or open issues or pull requests.
atsebay.t/auth.go

94 lines
2.2 KiB
Go

package main
import (
"encoding/base64"
"encoding/json"
"net/http"
"time"
"github.com/julienschmidt/httprouter"
)
var LocalAuthFunc = checkAuthKrb5
var localAuthUsers arrayFlags
type loginForm struct {
Login string `json:"username"`
Password string `json:"password"`
}
func init() {
router.GET("/api/auth", apiAuthHandler(validateAuthToken))
router.POST("/api/auth", apiRawHandler(func(w http.ResponseWriter, ps httprouter.Params, body []byte) HTTPResponse {
return formatApiResponse(LocalAuthFunc(w, ps, body))
}))
router.POST("/api/auth/logout", apiRawHandler(logout))
}
func validateAuthToken(u *User, _ httprouter.Params, _ []byte) HTTPResponse {
return APIResponse{u}
}
func logout(w http.ResponseWriter, ps httprouter.Params, body []byte) HTTPResponse {
http.SetCookie(w, &http.Cookie{
Name: "auth",
Value: "",
Path: baseURL + "/",
Expires: time.Unix(0, 0),
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
return APIResponse{true}
}
func completeAuth(w http.ResponseWriter, username string, email string, firstname string, lastname string, groups string, session *Session) (err error) {
var usr User
if !userExists(username) {
if usr, err = NewUser(username, email, firstname, lastname, groups); err != nil {
return err
}
} else if usr, err = getUserByLogin(username); err != nil {
return err
}
if usr.Groups != groups {
usr.Groups = groups
usr.Update()
}
if session == nil {
var s Session
s, err = usr.NewSession()
session = &s
} else {
_, err = session.SetUser(usr)
}
if err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
Name: "auth",
Value: base64.StdEncoding.EncodeToString(session.Id),
Path: baseURL + "/",
Expires: time.Now().Add(30 * 24 * time.Hour),
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
return nil
}
func dummyAuth(w http.ResponseWriter, _ httprouter.Params, body []byte) (interface{}, error) {
var lf map[string]string
if err := json.Unmarshal(body, &lf); err != nil {
return nil, err
}
return map[string]string{"status": "OK"}, completeAuth(w, lf["login"], lf["email"], lf["firstname"], lf["lastname"], "", nil)
}