|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/rand" |
| 6 | + "encoding/base64" |
| 7 | + "encoding/gob" |
| 8 | + "encoding/json" |
| 9 | + "io" |
| 10 | + "log/slog" |
| 11 | + "net/http" |
| 12 | + "os" |
| 13 | + "slices" |
| 14 | + "time" |
| 15 | + |
| 16 | + "golang.org/x/oauth2" |
| 17 | + "golang.org/x/oauth2/endpoints" |
| 18 | +) |
| 19 | + |
| 20 | +type DiscordUser struct { |
| 21 | + ID string `json:"id"` |
| 22 | + Username string `json:"username"` |
| 23 | + Avatar string `json:"avatar"` |
| 24 | +} |
| 25 | + |
| 26 | +var discordOauthConfig *oauth2.Config |
| 27 | + |
| 28 | +func (a *API) oauthInit() { |
| 29 | + gob.Register(DiscordUser{}) |
| 30 | + baseUrl := "" |
| 31 | + if a.Config.RunDev { |
| 32 | + baseUrl = "http://localhost:5173" |
| 33 | + } else { |
| 34 | + baseUrl = "https://status.pluralkit.me" |
| 35 | + } |
| 36 | + discordOauthConfig = &oauth2.Config{ |
| 37 | + RedirectURL: baseUrl + "/api/v1/auth/discord/callback", |
| 38 | + ClientID: os.Getenv("DISCORD_OAUTH_CLIENT_ID"), |
| 39 | + ClientSecret: os.Getenv("DISCORD_OAUTH_CLIENT_SECRET"), |
| 40 | + Scopes: []string{"identify"}, |
| 41 | + Endpoint: endpoints.Discord, |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +const discordUserEndpoint = "https://discordapp.com/api/users/@me" |
| 46 | + |
| 47 | +func (a *API) logout(w http.ResponseWriter, r *http.Request) { |
| 48 | + err := a.Sessions.Destroy(r.Context()) |
| 49 | + if err != nil { |
| 50 | + a.Logger.Error("failed to destroy session", slog.Any("error", err)) |
| 51 | + http.Error(w, "Internal Server Error", http.StatusInternalServerError) |
| 52 | + return |
| 53 | + } |
| 54 | + http.SetCookie(w, &http.Cookie{ |
| 55 | + Name: "login_status", |
| 56 | + Value: "0", |
| 57 | + Path: "/", |
| 58 | + MaxAge: -1, |
| 59 | + HttpOnly: false, |
| 60 | + }) |
| 61 | + http.Redirect(w, r, "/", http.StatusSeeOther) |
| 62 | +} |
| 63 | + |
| 64 | +func (a *API) oauthDiscordLogin(w http.ResponseWriter, r *http.Request) { |
| 65 | + state := a.genState(w) |
| 66 | + |
| 67 | + url := discordOauthConfig.AuthCodeURL(state) |
| 68 | + http.Redirect(w, r, url, http.StatusTemporaryRedirect) |
| 69 | +} |
| 70 | + |
| 71 | +func (a *API) oauthDiscordCallback(w http.ResponseWriter, r *http.Request) { |
| 72 | + state, err := r.Cookie("oauthstate") |
| 73 | + if err != nil { |
| 74 | + a.Logger.Warn("error while retrieving oauth state", slog.Any("error", err)) |
| 75 | + http.Redirect(w, r, "/", http.StatusTemporaryRedirect) |
| 76 | + return |
| 77 | + } |
| 78 | + |
| 79 | + if r.FormValue("state") != state.Value { |
| 80 | + a.Logger.Warn("invalid oauth state", slog.Any("error", err)) |
| 81 | + http.Redirect(w, r, "/", http.StatusTemporaryRedirect) |
| 82 | + return |
| 83 | + } |
| 84 | + |
| 85 | + http.SetCookie(w, &http.Cookie{ |
| 86 | + Name: "oauthstate", |
| 87 | + Value: "", |
| 88 | + Path: "/", |
| 89 | + MaxAge: -1, |
| 90 | + HttpOnly: true, |
| 91 | + Secure: !a.Config.RunDev, |
| 92 | + SameSite: http.SameSiteLaxMode, |
| 93 | + }) |
| 94 | + |
| 95 | + data, err := getUserData(r.Context(), r.FormValue("code")) |
| 96 | + if err != nil { |
| 97 | + a.Logger.Error("error while getting user data", slog.Any("error", err)) |
| 98 | + http.Redirect(w, r, "/", http.StatusTemporaryRedirect) |
| 99 | + return |
| 100 | + } |
| 101 | + |
| 102 | + var user DiscordUser |
| 103 | + if err := json.Unmarshal(data, &user); err != nil { |
| 104 | + a.Logger.Error("error parsing json", slog.Any("error", err)) |
| 105 | + http.Redirect(w, r, "/", http.StatusTemporaryRedirect) |
| 106 | + return |
| 107 | + } |
| 108 | + |
| 109 | + if !slices.Contains(a.Config.AuthorizedUsers, user.ID) { |
| 110 | + http.Error(w, "You are not authorized to access this resource", http.StatusUnauthorized) |
| 111 | + a.Logger.Info("Unauthorized user attempted access", slog.Any("user", user)) |
| 112 | + return |
| 113 | + } |
| 114 | + |
| 115 | + if err := a.Sessions.RenewToken(r.Context()); err != nil { |
| 116 | + a.Logger.Error("error renewing token", slog.Any("error", err)) |
| 117 | + http.Error(w, "Server Error", http.StatusInternalServerError) |
| 118 | + return |
| 119 | + } |
| 120 | + |
| 121 | + a.Sessions.Put(r.Context(), "user_session", user) |
| 122 | + http.SetCookie(w, &http.Cookie{ |
| 123 | + Name: "login_status", |
| 124 | + Value: "1", |
| 125 | + Path: "/", |
| 126 | + HttpOnly: false, |
| 127 | + Secure: !a.Config.RunDev, |
| 128 | + MaxAge: 86400, |
| 129 | + }) |
| 130 | + http.Redirect(w, r, "/", http.StatusFound) |
| 131 | +} |
| 132 | + |
| 133 | +func (a *API) genState(w http.ResponseWriter) string { |
| 134 | + var expiration = time.Now().Add(24 * time.Hour) |
| 135 | + |
| 136 | + b := make([]byte, 16) |
| 137 | + rand.Read(b) |
| 138 | + state := base64.URLEncoding.EncodeToString(b) |
| 139 | + cookie := http.Cookie{ |
| 140 | + Name: "oauthstate", |
| 141 | + Value: state, |
| 142 | + Expires: expiration, |
| 143 | + HttpOnly: true, |
| 144 | + Secure: !a.Config.RunDev, |
| 145 | + SameSite: http.SameSiteLaxMode, |
| 146 | + } |
| 147 | + http.SetCookie(w, &cookie) |
| 148 | + |
| 149 | + return state |
| 150 | +} |
| 151 | + |
| 152 | +func getUserData(ctx context.Context, code string) ([]byte, error) { |
| 153 | + token, err := discordOauthConfig.Exchange(ctx, code) |
| 154 | + if err != nil { |
| 155 | + return nil, err |
| 156 | + } |
| 157 | + |
| 158 | + client := &http.Client{} |
| 159 | + req, err := http.NewRequest("GET", discordUserEndpoint, nil) |
| 160 | + if err != nil { |
| 161 | + return nil, err |
| 162 | + } |
| 163 | + |
| 164 | + token.SetAuthHeader(req) |
| 165 | + |
| 166 | + resp, err := client.Do(req) |
| 167 | + if err != nil { |
| 168 | + return nil, err |
| 169 | + } |
| 170 | + defer resp.Body.Close() |
| 171 | + |
| 172 | + content, err := io.ReadAll(resp.Body) |
| 173 | + if err != nil { |
| 174 | + return nil, err |
| 175 | + } |
| 176 | + return content, nil |
| 177 | +} |
0 commit comments