mirror of
https://github.com/m1k1o/neko.git
synced 2025-05-28 16:37:15 +02:00
session handler with cookies.
This commit is contained in:
parent
546cd608c3
commit
6d59b3feff
5 changed files with 113 additions and 17 deletions
80
internal/api/session.go
Normal file
80
internal/api/session.go
Normal file
|
@ -0,0 +1,80 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"time"
|
||||
"net/http"
|
||||
|
||||
"demodesk/neko/internal/utils"
|
||||
"demodesk/neko/internal/types"
|
||||
"demodesk/neko/internal/http/auth"
|
||||
)
|
||||
|
||||
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{
|
||||
Name: "neko-id",
|
||||
Value: session.ID(),
|
||||
Expires: time.Now().Add(365 * 24 * time.Hour),
|
||||
HttpOnly: false,
|
||||
})
|
||||
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "neko-secret",
|
||||
Value: data.Secret,
|
||||
Expires: time.Now().Add(365 * 24 * time.Hour),
|
||||
HttpOnly: true,
|
||||
})
|
||||
|
||||
utils.HttpSuccess(w)
|
||||
}
|
||||
|
||||
func (api *ApiManagerCtx) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "neko-id",
|
||||
Value: "",
|
||||
Path: "/",
|
||||
Expires: time.Unix(0, 0),
|
||||
HttpOnly: false,
|
||||
})
|
||||
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "neko-secret",
|
||||
Value: "",
|
||||
Path: "/",
|
||||
Expires: time.Unix(0, 0),
|
||||
HttpOnly: true,
|
||||
})
|
||||
|
||||
utils.HttpSuccess(w)
|
||||
}
|
||||
|
||||
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(),
|
||||
})
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue