2021-01-30 10:22:14 +13:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
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
|
|
|
)
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
session, err := api.sessions.Authenticate(data.ID, data.Secret)
|
|
|
|
if err != nil {
|
|
|
|
utils.HttpUnauthorized(w, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
2021-02-15 02:40:17 +13:00
|
|
|
Name: "neko-id",
|
|
|
|
Value: session.ID(),
|
|
|
|
Expires: time.Now().Add(365 * 24 * time.Hour),
|
2021-01-30 10:22:14 +13:00
|
|
|
HttpOnly: false,
|
|
|
|
})
|
|
|
|
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
2021-02-15 02:40:17 +13:00
|
|
|
Name: "neko-secret",
|
|
|
|
Value: data.Secret,
|
|
|
|
Expires: time.Now().Add(365 * 24 * time.Hour),
|
2021-01-30 10:22:14 +13:00
|
|
|
HttpOnly: true,
|
|
|
|
})
|
|
|
|
|
2021-01-30 11:03:35 +13:00
|
|
|
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) {
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
2021-02-15 02:40:17 +13:00
|
|
|
Name: "neko-id",
|
|
|
|
Value: "",
|
|
|
|
Expires: time.Unix(0, 0),
|
2021-01-30 10:22:14 +13:00
|
|
|
HttpOnly: false,
|
|
|
|
})
|
|
|
|
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
2021-02-15 02:40:17 +13:00
|
|
|
Name: "neko-secret",
|
|
|
|
Value: "",
|
|
|
|
Expires: time.Unix(0, 0),
|
2021-01-30 10:22:14 +13:00
|
|
|
HttpOnly: true,
|
|
|
|
})
|
|
|
|
|
2021-01-30 11:03:35 +13:00
|
|
|
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(),
|
|
|
|
})
|
|
|
|
}
|