2022-11-18 06:27:52 -08:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
2023-06-03 07:18:47 -07:00
|
|
|
"codeberg.org/pronounscc/pronouns.cc/backend/db"
|
|
|
|
"codeberg.org/pronounscc/pronouns.cc/backend/server"
|
2022-11-18 06:27:52 -08:00
|
|
|
"emperror.dev/errors"
|
|
|
|
"github.com/go-chi/render"
|
|
|
|
)
|
|
|
|
|
|
|
|
type inviteResponse struct {
|
2023-03-13 16:16:19 -07:00
|
|
|
Code string `json:"code"`
|
2022-11-18 06:27:52 -08:00
|
|
|
Created time.Time `json:"created"`
|
|
|
|
Used bool `json:"used"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func dbInviteToResponse(i db.Invite) inviteResponse {
|
|
|
|
return inviteResponse{
|
|
|
|
Code: i.Code,
|
|
|
|
Created: i.Created,
|
|
|
|
Used: i.Used,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) getInvites(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
if !s.RequireInvite {
|
|
|
|
return server.APIError{Code: server.ErrInvitesDisabled}
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx := r.Context()
|
|
|
|
claims, _ := server.ClaimsFromContext(ctx)
|
|
|
|
|
2023-03-30 07:58:35 -07:00
|
|
|
if claims.APIToken {
|
|
|
|
return server.APIError{Code: server.ErrMissingPermissions, Details: "This endpoint cannot be used by API tokens"}
|
|
|
|
}
|
|
|
|
|
2022-11-18 06:27:52 -08:00
|
|
|
is, err := s.DB.UserInvites(ctx, claims.UserID)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "getting user invites")
|
|
|
|
}
|
|
|
|
|
|
|
|
resps := make([]inviteResponse, len(is))
|
|
|
|
for i := range is {
|
|
|
|
resps[i] = dbInviteToResponse(is[i])
|
|
|
|
}
|
|
|
|
|
|
|
|
render.JSON(w, r, resps)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) createInvite(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
if !s.RequireInvite {
|
|
|
|
return server.APIError{Code: server.ErrInvitesDisabled}
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx := r.Context()
|
|
|
|
claims, _ := server.ClaimsFromContext(ctx)
|
|
|
|
|
2023-03-30 07:58:35 -07:00
|
|
|
if claims.APIToken {
|
|
|
|
return server.APIError{Code: server.ErrMissingPermissions, Details: "This endpoint cannot be used by API tokens"}
|
|
|
|
}
|
|
|
|
|
2022-11-18 06:27:52 -08:00
|
|
|
inv, err := s.DB.CreateInvite(ctx, claims.UserID)
|
|
|
|
if err != nil {
|
|
|
|
if err == db.ErrTooManyInvites {
|
|
|
|
return server.APIError{Code: server.ErrInviteLimitReached}
|
|
|
|
}
|
|
|
|
|
|
|
|
return errors.Wrap(err, "creating invite")
|
|
|
|
}
|
|
|
|
|
|
|
|
render.JSON(w, r, dbInviteToResponse(inv))
|
|
|
|
return nil
|
|
|
|
}
|