neko/internal/api/session.go

108 lines
2.3 KiB
Go
Raw Normal View History

2021-01-30 10:22:14 +13:00
package api
import (
"net/http"
2021-03-02 06:52:05 +13:00
"os"
2021-02-15 02:40:17 +13:00
"time"
2021-01-30 10:22:14 +13:00
"demodesk/neko/internal/http/auth"
2021-02-15 02:40:17 +13:00
"demodesk/neko/internal/types"
"demodesk/neko/internal/utils"
2021-01-30 10:22:14 +13:00
)
2021-03-02 06:52:05 +13:00
var CookieExpirationDate = time.Now().Add(365 * 24 * time.Hour)
var UnsecureCookies = os.Getenv("DISABLE_SECURE_COOKIES") == "true"
2021-01-30 10:22:14 +13:00
type SessionLoginPayload struct {
ID string `json:"id"`
Secret string `json:"secret"`
}
type SessionWhoamiPayload struct {
ID string `json:"id"`
Profile types.MemberProfile `json:"profile"`
State types.MemberState `json:"state"`
}
func (api *ApiManagerCtx) Login(w http.ResponseWriter, r *http.Request) {
data := &SessionLoginPayload{}
if !utils.HttpJsonRequest(w, r, data) {
return
}
2021-03-14 09:11:48 +13:00
token := data.Secret
2021-03-14 08:42:56 +13:00
// TODO: Proper login.
2021-03-14 09:11:48 +13:00
session, err := api.sessions.Create(token, types.MemberProfile{
Name: data.ID,
IsAdmin: true,
CanLogin: true,
CanConnect: true,
CanWatch: true,
CanHost: true,
CanAccessClipboard: true,
})
if err != nil {
utils.HttpUnauthorized(w, err)
2021-01-30 10:22:14 +13:00
return
2021-03-14 09:11:48 +13:00
}
2021-01-30 10:22:14 +13:00
2021-03-02 06:52:05 +13:00
sameSite := http.SameSiteNoneMode
if UnsecureCookies {
sameSite = http.SameSiteDefaultMode
}
2021-01-30 10:22:14 +13:00
http.SetCookie(w, &http.Cookie{
2021-03-14 09:11:48 +13:00
Name: "NEKO_SESSION",
Value: token,
2021-03-02 06:52:05 +13:00
Expires: CookieExpirationDate,
Secure: !UnsecureCookies,
SameSite: sameSite,
2021-01-30 10:22:14 +13:00
HttpOnly: true,
})
utils.HttpSuccess(w, SessionWhoamiPayload{
ID: session.ID(),
Profile: session.GetProfile(),
State: session.GetState(),
})
2021-01-30 10:22:14 +13:00
}
func (api *ApiManagerCtx) Logout(w http.ResponseWriter, r *http.Request) {
2021-03-14 09:11:48 +13:00
session := auth.GetSession(r)
// TODO: Proper logout.
err := api.sessions.Delete(session.ID())
if err != nil {
utils.HttpUnauthorized(w, err)
return
}
2021-03-02 06:52:05 +13:00
sameSite := http.SameSiteNoneMode
if UnsecureCookies {
sameSite = http.SameSiteDefaultMode
}
2021-01-30 10:22:14 +13:00
http.SetCookie(w, &http.Cookie{
2021-03-14 09:11:48 +13:00
Name: "NEKO_SESSION",
2021-02-15 02:40:17 +13:00
Value: "",
Expires: time.Unix(0, 0),
2021-03-02 06:52:05 +13:00
Secure: !UnsecureCookies,
SameSite: sameSite,
2021-01-30 10:22:14 +13:00
HttpOnly: true,
})
utils.HttpSuccess(w, true)
2021-01-30 10:22:14 +13:00
}
func (api *ApiManagerCtx) Whoami(w http.ResponseWriter, r *http.Request) {
session := auth.GetSession(r)
utils.HttpSuccess(w, SessionWhoamiPayload{
ID: session.ID(),
Profile: session.GetProfile(),
State: session.GetState(),
})
}