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

97 lines
2.2 KiB
Go
Raw Normal View History

2020-03-04 11:07:12 +00:00
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"`
}
2020-03-04 11:07:12 +00:00
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))
}))
2020-03-04 11:07:12 +00:00
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{
2020-09-13 14:36:07 +00:00
Name: "auth",
Value: "",
Path: baseURL + "/",
Expires: time.Unix(0, 0),
Secure: true,
2020-03-04 11:07:12 +00:00
HttpOnly: true,
2020-09-13 14:36:07 +00:00
SameSite: http.SameSiteStrictMode,
2020-03-04 11:07:12 +00:00
})
return APIResponse{true}
}
2021-09-15 22:26:09 +00:00
func completeAuth(w http.ResponseWriter, username string, email string, firstname string, lastname string, groups string, session *Session) (err error) {
2020-03-04 11:07:12 +00:00
var usr User
if !userExists(username) {
2021-09-15 22:26:09 +00:00
if usr, err = NewUser(username, email, firstname, lastname, groups); err != nil {
2020-03-04 11:07:12 +00:00
return err
}
} else if usr, err = getUserByLogin(username); err != nil {
return err
}
2021-09-28 14:27:48 +00:00
if len(groups) > 255 {
groups = groups[:255]
}
2021-09-15 22:26:09 +00:00
if usr.Groups != groups {
usr.Groups = groups
usr.Update()
}
2020-03-04 11:07:12 +00:00
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{
2020-09-13 14:36:07 +00:00
Name: "auth",
Value: base64.StdEncoding.EncodeToString(session.Id),
Path: baseURL + "/",
Expires: time.Now().Add(30 * 24 * time.Hour),
Secure: true,
2020-03-04 11:07:12 +00:00
HttpOnly: true,
2020-09-13 14:36:07 +00:00
SameSite: http.SameSiteStrictMode,
2020-03-04 11:07:12 +00:00
})
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
}
2021-09-15 22:26:09 +00:00
return map[string]string{"status": "OK"}, completeAuth(w, lf["login"], lf["email"], lf["firstname"], lf["lastname"], "", nil)
2020-03-04 11:07:12 +00:00
}