neko/internal/api/session.go

66 lines
1.4 KiB
Go
Raw Normal View History

2021-01-30 10:22:14 +13:00
package api
import (
"net/http"
"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 {
2021-03-14 12:32:52 +13:00
Username string `json:"username"`
Password string `json:"password"`
2021-01-30 10:22:14 +13:00
}
2021-03-14 12:32:52 +13:00
type SessionDataPayload struct {
2021-01-30 10:22:14 +13:00
ID string `json:"id"`
Profile types.MemberProfile `json:"profile"`
2021-03-14 11:42:16 +13:00
State types.SessionState `json:"state"`
2021-01-30 10:22:14 +13:00
}
func (api *ApiManagerCtx) Login(w http.ResponseWriter, r *http.Request) {
data := &SessionLoginPayload{}
if !utils.HttpJsonRequest(w, r, data) {
return
}
2021-03-15 07:59:34 +13:00
session, token, err := api.members.Login(data.Username, data.Password)
2021-03-14 09:11:48 +13:00
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-18 02:09:10 +13:00
api.sessions.CookieSetToken(w, token)
2021-01-30 10:22:14 +13:00
2021-03-14 12:32:52 +13:00
utils.HttpSuccess(w, SessionDataPayload{
ID: session.ID(),
2021-03-14 12:45:51 +13:00
Profile: session.Profile(),
State: session.State(),
})
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)
2021-03-15 07:59:34 +13:00
err := api.members.Logout(session.ID())
2021-03-14 09:11:48 +13:00
if err != nil {
utils.HttpUnauthorized(w, err)
return
}
2021-03-25 22:29:28 +13:00
api.sessions.CookieClearToken(w, r)
2021-01-30 10:22:14 +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)
2021-03-14 12:32:52 +13:00
utils.HttpSuccess(w, SessionDataPayload{
2021-01-30 10:22:14 +13:00
ID: session.ID(),
2021-03-14 12:45:51 +13:00
Profile: session.Profile(),
State: session.State(),
2021-01-30 10:22:14 +13:00
})
}