Initial
This commit is contained in:
commit
97dc0a3570
78 files changed
+7054
No files matched your search
@@ -0,0 +1,85 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"goAuth/internal/auth"
|
||||
)
|
||||
|
||||
type sessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
Address string `json:"address"`
|
||||
Device string `json:"device"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
IsLong bool `json:"isLong"`
|
||||
Current bool `json:"current"`
|
||||
}
|
||||
|
||||
func (h *Handler) listSessions(w http.ResponseWriter, r *http.Request) {
|
||||
u := userFromRequest(r)
|
||||
current := sessionFromRequest(r)
|
||||
|
||||
limit, offset := pagination(r)
|
||||
sessions, err := h.sessions.Sessions(r.Context(), u, limit, offset)
|
||||
if err != nil {
|
||||
h.fail(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
result := make([]sessionResponse, 0, len(sessions))
|
||||
for _, session := range sessions {
|
||||
result = append(result, newSessionResponse(session, current))
|
||||
}
|
||||
|
||||
writeJson(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
func (h *Handler) signoutSession(w http.ResponseWriter, r *http.Request) {
|
||||
u := userFromRequest(r)
|
||||
|
||||
token := r.PathValue("token")
|
||||
session, err := h.sessions.SessionByToken(r.Context(), token)
|
||||
if err != nil || session.UserId != u.Id {
|
||||
writeError(w, http.StatusNotFound, "session not found")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.sessions.DeleteSession(r.Context(), session); err != nil {
|
||||
h.fail(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
if current := sessionFromRequest(r); current.Token == token {
|
||||
auth.SignoutCleanup(w, h.cfg.Cookies.SessionName, h.cfg.Cookies.Secure)
|
||||
h.refreshCsrf(w)
|
||||
}
|
||||
|
||||
writeNoContent(w)
|
||||
}
|
||||
|
||||
func (h *Handler) signoutAll(w http.ResponseWriter, r *http.Request) {
|
||||
u := userFromRequest(r)
|
||||
|
||||
if err := h.sessions.DeleteSessions(r.Context(), u); err != nil {
|
||||
h.fail(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
auth.SignoutCleanup(w, h.cfg.Cookies.SessionName, h.cfg.Cookies.Secure)
|
||||
h.refreshCsrf(w)
|
||||
writeNoContent(w)
|
||||
}
|
||||
|
||||
func newSessionResponse(session, current *auth.Session) sessionResponse {
|
||||
return sessionResponse{
|
||||
Token: session.Token,
|
||||
Address: session.Address,
|
||||
Device: session.Device,
|
||||
CreatedAt: session.CreatedAt,
|
||||
ExpiresAt: session.ExpiresAt,
|
||||
IsLong: session.IsLong,
|
||||
Current: current != nil && current.Token == session.Token,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user