2022-05-02 08:19:37 -07:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
2022-05-04 07:27:16 -07:00
|
|
|
"net/http"
|
2022-05-02 08:19:37 -07:00
|
|
|
"os"
|
2023-03-14 08:16:07 -07:00
|
|
|
"time"
|
2022-05-02 08:19:37 -07:00
|
|
|
|
2022-05-14 07:52:08 -07:00
|
|
|
"codeberg.org/u1f320/pronouns.cc/backend/db"
|
|
|
|
"codeberg.org/u1f320/pronouns.cc/backend/log"
|
|
|
|
"codeberg.org/u1f320/pronouns.cc/backend/server"
|
2022-11-17 17:17:27 -08:00
|
|
|
"emperror.dev/errors"
|
2022-05-04 07:27:16 -07:00
|
|
|
"github.com/bwmarrin/discordgo"
|
|
|
|
"github.com/go-chi/render"
|
2022-11-17 17:17:27 -08:00
|
|
|
"github.com/mediocregopher/radix/v4"
|
2022-12-31 15:34:38 -08:00
|
|
|
"github.com/rs/xid"
|
2022-05-02 08:19:37 -07:00
|
|
|
"golang.org/x/oauth2"
|
|
|
|
)
|
|
|
|
|
2022-05-04 07:27:16 -07:00
|
|
|
var discordOAuthConfig = oauth2.Config{
|
2022-05-02 08:19:37 -07:00
|
|
|
ClientID: os.Getenv("DISCORD_CLIENT_ID"),
|
|
|
|
ClientSecret: os.Getenv("DISCORD_CLIENT_SECRET"),
|
|
|
|
Endpoint: oauth2.Endpoint{
|
|
|
|
AuthURL: "https://discord.com/api/oauth2/authorize",
|
|
|
|
TokenURL: "https://discord.com/api/oauth2/token",
|
|
|
|
AuthStyle: oauth2.AuthStyleInParams,
|
|
|
|
},
|
|
|
|
Scopes: []string{"identify"},
|
|
|
|
}
|
2022-05-04 07:27:16 -07:00
|
|
|
|
2023-04-18 13:52:58 -07:00
|
|
|
type oauthCallbackRequest struct {
|
2022-05-12 07:41:32 -07:00
|
|
|
CallbackDomain string `json:"callback_domain"`
|
|
|
|
Code string `json:"code"`
|
|
|
|
State string `json:"state"`
|
2022-05-04 07:27:16 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
type discordCallbackResponse struct {
|
|
|
|
HasAccount bool `json:"has_account"` // if true, Token and User will be set. if false, Ticket and Discord will be set
|
|
|
|
|
2022-06-17 06:18:44 -07:00
|
|
|
Token string `json:"token,omitempty"`
|
|
|
|
User *userResponse `json:"user,omitempty"`
|
2022-05-04 07:27:16 -07:00
|
|
|
|
2023-04-24 07:51:55 -07:00
|
|
|
Discord string `json:"discord,omitempty"` // username, for UI purposes
|
|
|
|
Ticket string `json:"ticket,omitempty"`
|
|
|
|
RequireInvite bool `json:"require_invite"` // require an invite for signing up
|
|
|
|
RequireCaptcha bool `json:"require_captcha"`
|
2023-03-14 08:16:07 -07:00
|
|
|
|
2023-03-23 07:40:33 -07:00
|
|
|
IsDeleted bool `json:"is_deleted"`
|
|
|
|
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
|
|
|
SelfDelete *bool `json:"self_delete,omitempty"`
|
|
|
|
DeleteReason *string `json:"delete_reason,omitempty"`
|
2022-05-04 07:27:16 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) discordCallback(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
ctx := r.Context()
|
|
|
|
|
2023-04-18 13:52:58 -07:00
|
|
|
decoded, err := Decode[oauthCallbackRequest](r)
|
2022-05-04 07:27:16 -07:00
|
|
|
if err != nil {
|
|
|
|
return server.APIError{Code: server.ErrBadRequest}
|
|
|
|
}
|
|
|
|
|
|
|
|
// if the state can't be validated, return
|
|
|
|
if valid, err := s.validateCSRFState(ctx, decoded.State); !valid {
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return server.APIError{Code: server.ErrInvalidState}
|
|
|
|
}
|
|
|
|
|
2022-05-12 07:41:32 -07:00
|
|
|
cfg := discordOAuthConfig
|
2023-03-11 19:25:53 -08:00
|
|
|
cfg.RedirectURL = decoded.CallbackDomain + "/auth/login/discord"
|
2022-05-12 07:41:32 -07:00
|
|
|
token, err := cfg.Exchange(r.Context(), decoded.Code)
|
2022-05-04 07:27:16 -07:00
|
|
|
if err != nil {
|
|
|
|
log.Errorf("exchanging oauth code: %v", err)
|
|
|
|
|
|
|
|
return server.APIError{Code: server.ErrInvalidOAuthCode}
|
|
|
|
}
|
|
|
|
|
|
|
|
dg, _ := discordgo.New(token.Type() + " " + token.AccessToken)
|
|
|
|
du, err := dg.User("@me")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
u, err := s.DB.DiscordUser(ctx, du.ID)
|
|
|
|
if err == nil {
|
2023-03-23 07:40:33 -07:00
|
|
|
if u.DeletedAt != nil {
|
2023-03-14 08:16:07 -07:00
|
|
|
// store cancel delete token
|
|
|
|
token := undeleteToken()
|
|
|
|
err = s.saveUndeleteToken(ctx, u.ID, token)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("saving undelete token: %v", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
render.JSON(w, r, discordCallbackResponse{
|
2023-03-23 07:40:33 -07:00
|
|
|
HasAccount: true,
|
|
|
|
Token: token,
|
|
|
|
User: dbUserToUserResponse(u, []db.Field{}),
|
|
|
|
IsDeleted: true,
|
|
|
|
DeletedAt: u.DeletedAt,
|
|
|
|
SelfDelete: u.SelfDelete,
|
|
|
|
DeleteReason: u.DeleteReason,
|
2023-03-14 08:16:07 -07:00
|
|
|
})
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-05-04 07:27:16 -07:00
|
|
|
err = u.UpdateFromDiscord(ctx, s.DB, du)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("updating user %v with Discord info: %v", u.ID, err)
|
|
|
|
}
|
|
|
|
|
2022-12-31 15:34:38 -08:00
|
|
|
// TODO: implement user + token permissions
|
|
|
|
tokenID := xid.New()
|
2023-03-19 08:14:09 -07:00
|
|
|
token, err := s.Auth.CreateToken(u.ID, tokenID, u.IsAdmin, false, true)
|
2022-05-04 07:27:16 -07:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-12-31 15:34:38 -08:00
|
|
|
// save token to database
|
2023-03-30 07:50:30 -07:00
|
|
|
_, err = s.DB.SaveToken(ctx, u.ID, tokenID, false, false)
|
2022-12-31 15:34:38 -08:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "saving token to database")
|
|
|
|
}
|
|
|
|
|
2023-03-11 16:31:31 -08:00
|
|
|
fields, err := s.DB.UserFields(ctx, u.ID)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "querying fields")
|
|
|
|
}
|
|
|
|
|
2022-05-04 07:27:16 -07:00
|
|
|
render.JSON(w, r, discordCallbackResponse{
|
|
|
|
HasAccount: true,
|
|
|
|
Token: token,
|
2023-03-11 16:31:31 -08:00
|
|
|
User: dbUserToUserResponse(u, fields),
|
2022-05-04 07:27:16 -07:00
|
|
|
})
|
2022-06-17 06:18:44 -07:00
|
|
|
|
2022-06-16 15:00:52 -07:00
|
|
|
return nil
|
|
|
|
|
2022-05-04 07:27:16 -07:00
|
|
|
} else if err != db.ErrUserNotFound { // internal error
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-05-17 13:35:26 -07:00
|
|
|
// no user found, so save a ticket + save their Discord info in Redis
|
|
|
|
ticket := RandBase64(32)
|
|
|
|
err = s.DB.SetJSON(ctx, "discord:"+ticket, du, "EX", "600")
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("setting Discord user for ticket %q: %v", ticket, err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
render.JSON(w, r, discordCallbackResponse{
|
2023-04-24 07:51:55 -07:00
|
|
|
HasAccount: false,
|
|
|
|
Discord: du.String(),
|
|
|
|
Ticket: ticket,
|
|
|
|
RequireInvite: s.RequireInvite,
|
|
|
|
RequireCaptcha: s.hcaptchaSecret != "",
|
2022-05-17 13:35:26 -07:00
|
|
|
})
|
2022-05-04 07:27:16 -07:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-03-18 08:33:12 -07:00
|
|
|
type linkRequest struct {
|
|
|
|
Ticket string `json:"ticket"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) discordLink(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
ctx := r.Context()
|
|
|
|
|
|
|
|
claims, _ := server.ClaimsFromContext(ctx)
|
|
|
|
|
|
|
|
// only site tokens can be used for this endpoint
|
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"}
|
2023-03-18 08:33:12 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
req, err := Decode[linkRequest](r)
|
|
|
|
if err != nil {
|
|
|
|
return server.APIError{Code: server.ErrBadRequest}
|
|
|
|
}
|
|
|
|
|
|
|
|
u, err := s.DB.User(ctx, claims.UserID)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "getting user")
|
|
|
|
}
|
|
|
|
|
|
|
|
if u.Discord != nil {
|
|
|
|
return server.APIError{Code: server.ErrAlreadyLinked}
|
|
|
|
}
|
|
|
|
|
|
|
|
du := new(discordgo.User)
|
|
|
|
err = s.DB.GetJSON(ctx, "discord:"+req.Ticket, &du)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("getting discord user for ticket: %v", err)
|
|
|
|
|
|
|
|
return server.APIError{Code: server.ErrInvalidTicket}
|
|
|
|
}
|
|
|
|
|
2023-04-20 15:07:02 -07:00
|
|
|
if du.ID == "" {
|
|
|
|
log.Errorf("linking user with id %v: discord user ID was empty", claims.UserID)
|
|
|
|
return server.APIError{Code: server.ErrInternalServerError, Details: "Discord user ID is empty"}
|
|
|
|
}
|
|
|
|
|
2023-03-18 08:33:12 -07:00
|
|
|
err = u.UpdateFromDiscord(ctx, s.DB, du)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "updating user from discord")
|
|
|
|
}
|
|
|
|
|
|
|
|
fields, err := s.DB.UserFields(ctx, u.ID)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "getting user fields")
|
|
|
|
}
|
|
|
|
|
|
|
|
render.JSON(w, r, dbUserToUserResponse(u, fields))
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-03-18 08:54:31 -07:00
|
|
|
func (s *Server) discordUnlink(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
ctx := r.Context()
|
|
|
|
|
|
|
|
claims, _ := server.ClaimsFromContext(ctx)
|
|
|
|
|
|
|
|
// only site tokens can be used for this endpoint
|
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"}
|
2023-03-18 08:54:31 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
u, err := s.DB.User(ctx, claims.UserID)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "getting user")
|
|
|
|
}
|
|
|
|
|
|
|
|
if u.Discord == nil {
|
|
|
|
return server.APIError{Code: server.ErrNotLinked}
|
|
|
|
}
|
|
|
|
|
2023-03-18 15:04:50 -07:00
|
|
|
// cannot unlink last auth provider
|
|
|
|
if u.NumProviders() <= 1 {
|
|
|
|
return server.APIError{Code: server.ErrLastProvider}
|
|
|
|
}
|
|
|
|
|
2023-03-18 08:54:31 -07:00
|
|
|
err = u.UnlinkDiscord(ctx, s.DB)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "updating user in db")
|
|
|
|
}
|
|
|
|
|
|
|
|
fields, err := s.DB.UserFields(ctx, u.ID)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "getting user fields")
|
|
|
|
}
|
|
|
|
|
|
|
|
render.JSON(w, r, dbUserToUserResponse(u, fields))
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-04-18 13:52:58 -07:00
|
|
|
type signupRequest struct {
|
2023-04-24 07:51:55 -07:00
|
|
|
Ticket string `json:"ticket"`
|
|
|
|
Username string `json:"username"`
|
|
|
|
InviteCode string `json:"invite_code"`
|
|
|
|
CaptchaResponse string `json:"captcha_response"`
|
2022-11-17 17:17:27 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
type signupResponse struct {
|
|
|
|
User userResponse `json:"user"`
|
|
|
|
Token string `json:"token"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) discordSignup(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
ctx := r.Context()
|
|
|
|
|
2023-04-18 13:52:58 -07:00
|
|
|
req, err := Decode[signupRequest](r)
|
2022-11-17 17:17:27 -08:00
|
|
|
if err != nil {
|
|
|
|
return server.APIError{Code: server.ErrBadRequest}
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.RequireInvite && req.InviteCode == "" {
|
|
|
|
return server.APIError{Code: server.ErrInviteRequired}
|
|
|
|
}
|
|
|
|
|
|
|
|
valid, taken, err := s.DB.UsernameTaken(ctx, req.Username)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if !valid {
|
|
|
|
return server.APIError{Code: server.ErrInvalidUsername}
|
|
|
|
}
|
|
|
|
if taken {
|
|
|
|
return server.APIError{Code: server.ErrUsernameTaken}
|
|
|
|
}
|
|
|
|
|
|
|
|
tx, err := s.DB.Begin(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "beginning transaction")
|
|
|
|
}
|
|
|
|
defer tx.Rollback(ctx)
|
|
|
|
|
2022-11-17 17:26:40 -08:00
|
|
|
du := new(discordgo.User)
|
2022-11-17 17:17:27 -08:00
|
|
|
err = s.DB.GetJSON(ctx, "discord:"+req.Ticket, &du)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("getting discord user for ticket: %v", err)
|
|
|
|
|
|
|
|
return server.APIError{Code: server.ErrInvalidTicket}
|
|
|
|
}
|
|
|
|
|
2023-04-24 07:51:55 -07:00
|
|
|
// check captcha
|
|
|
|
if s.hcaptchaSecret != "" {
|
|
|
|
ok, err := s.verifyCaptcha(ctx, req.CaptchaResponse)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("verifying captcha: %v", err)
|
|
|
|
return server.APIError{Code: server.ErrInternalServerError}
|
|
|
|
}
|
|
|
|
|
|
|
|
if !ok {
|
|
|
|
return server.APIError{Code: server.ErrInvalidCaptcha}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-17 17:17:27 -08:00
|
|
|
u, err := s.DB.CreateUser(ctx, tx, req.Username)
|
|
|
|
if err != nil {
|
2023-03-18 07:19:53 -07:00
|
|
|
if errors.Cause(err) == db.ErrUsernameTaken {
|
|
|
|
return server.APIError{Code: server.ErrUsernameTaken}
|
|
|
|
}
|
|
|
|
|
2022-11-17 17:17:27 -08:00
|
|
|
return errors.Wrap(err, "creating user")
|
|
|
|
}
|
|
|
|
|
2023-04-20 15:07:02 -07:00
|
|
|
if du.ID == "" {
|
|
|
|
log.Errorf("creating user with name %q: user ID was empty", req.Username)
|
|
|
|
return server.APIError{Code: server.ErrInternalServerError, Details: "Discord user ID is empty"}
|
|
|
|
}
|
|
|
|
|
2022-11-17 17:26:40 -08:00
|
|
|
err = u.UpdateFromDiscord(ctx, tx, du)
|
2022-11-17 17:17:27 -08:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "updating user from discord")
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.RequireInvite {
|
2022-11-18 06:27:52 -08:00
|
|
|
valid, used, err := s.DB.InvalidateInvite(ctx, tx, req.InviteCode)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "checking and invalidating invite")
|
|
|
|
}
|
2022-11-17 17:17:27 -08:00
|
|
|
|
2022-11-18 06:27:52 -08:00
|
|
|
if !valid {
|
2022-11-17 17:17:27 -08:00
|
|
|
return server.APIError{Code: server.ErrInviteRequired}
|
|
|
|
}
|
2022-11-18 06:27:52 -08:00
|
|
|
|
|
|
|
if used {
|
|
|
|
return server.APIError{Code: server.ErrInviteAlreadyUsed}
|
|
|
|
}
|
2022-11-17 17:17:27 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// delete sign up ticket
|
|
|
|
err = s.DB.Redis.Do(ctx, radix.Cmd(nil, "DEL", "discord:"+req.Ticket))
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "deleting signup ticket")
|
|
|
|
}
|
|
|
|
|
|
|
|
// commit transaction
|
|
|
|
err = tx.Commit(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "committing transaction")
|
|
|
|
}
|
|
|
|
|
|
|
|
// create token
|
2022-12-31 15:34:38 -08:00
|
|
|
// TODO: implement user + token permissions
|
|
|
|
tokenID := xid.New()
|
2023-03-13 09:10:54 -07:00
|
|
|
token, err := s.Auth.CreateToken(u.ID, tokenID, false, false, true)
|
2022-11-17 17:17:27 -08:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "creating token")
|
|
|
|
}
|
|
|
|
|
2022-12-31 15:34:38 -08:00
|
|
|
// save token to database
|
2023-03-30 07:50:30 -07:00
|
|
|
_, err = s.DB.SaveToken(ctx, u.ID, tokenID, false, false)
|
2022-12-31 15:34:38 -08:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "saving token to database")
|
|
|
|
}
|
|
|
|
|
2022-11-17 17:17:27 -08:00
|
|
|
// return user
|
|
|
|
render.JSON(w, r, signupResponse{
|
2023-03-11 16:31:31 -08:00
|
|
|
User: *dbUserToUserResponse(u, nil),
|
2022-11-17 17:17:27 -08:00
|
|
|
Token: token,
|
|
|
|
})
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-05-04 07:27:16 -07:00
|
|
|
func Decode[T any](r *http.Request) (T, error) {
|
|
|
|
decoded := *new(T)
|
|
|
|
|
|
|
|
return decoded, render.Decode(r, &decoded)
|
|
|
|
}
|