Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(auth): add support for device code grant flow #5680

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
- Minor: Indicate when subscriptions and resubscriptions are for multiple months. (#5642)
- Minor: Proxy URL information is now included in the `/debug-env` command. (#5648)
- Minor: Make raid entry message usernames clickable. (#5651)
- Minor: Added support for the "Device code grant flow" for authentication. (#5680)
- Bugfix: Fixed tab move animation occasionally failing to start after closing a tab. (#5426, #5612)
- Bugfix: If a network request errors with 200 OK, Qt's error code is now reported instead of the HTTP status. (#5378)
- Bugfix: Fixed restricted users usernames not being clickable. (#5405)
Expand Down
8 changes: 6 additions & 2 deletions src/Application.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,9 @@ void Application::initialize(Settings &settings, const Paths &paths)

// XXX: Loading Twitch badges after Helix has been initialized, which only happens after
// the AccountController initialize has been called
this->twitchBadges->loadTwitchBadges();
this->accounts->twitch.requestCurrent([this](const auto &) {
this->twitchBadges->loadTwitchBadges();
});

#ifdef CHATTERINO_HAVE_PLUGINS
this->plugins->initialize(settings);
Expand Down Expand Up @@ -271,7 +273,9 @@ void Application::initialize(Settings &settings, const Paths &paths)
{
this->initNm(paths);
}
this->twitchPubSub->initialize();
this->accounts->twitch.requestCurrent([this](const auto &) {
this->twitchPubSub->initialize();
});

this->initBttvLiveUpdates();
this->initSeventvEventAPI();
Expand Down
16 changes: 15 additions & 1 deletion src/common/ChatterinoSetting.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,6 @@ class EnumStringSetting : public pajlada::Settings::Setting<QString>
_registerSetting(this->getData());
}

template <typename T2>
EnumStringSetting<Enum> &operator=(Enum newValue)
{
this->setValue(qmagicenum::enumNameString(newValue).toLower());
Expand All @@ -134,6 +133,21 @@ class EnumStringSetting : public pajlada::Settings::Setting<QString>
.value_or(this->defaultValue);
}

static Enum get(const std::string &path, Enum defaultValue)
{
EnumStringSetting<Enum> setting(path, defaultValue);

return setting.getEnum();
}

static void set(const std::string &path, Enum newValue,
Enum defaultValue = static_cast<Enum>(0))
{
EnumStringSetting<Enum> setting(path, defaultValue);

setting = newValue;
}

Enum defaultValue;

using pajlada::Settings::Setting<QString>::operator==;
Expand Down
2 changes: 1 addition & 1 deletion src/providers/irc/IrcConnection2.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ IrcConnection::IrcConnection(QObject *parent)
else
{
qCDebug(chatterinoIrc) << "Reconnecting";
this->open();
this->connectAndInitializeRequested();
}
});

Expand Down
7 changes: 7 additions & 0 deletions src/providers/irc/IrcConnection2.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ namespace chatterino {

class IrcConnection : public Communi::IrcConnection
{
Q_OBJECT

public:
IrcConnection(QObject *parent = nullptr);
~IrcConnection() override;
Expand All @@ -31,6 +33,11 @@ class IrcConnection : public Communi::IrcConnection
virtual void open();
virtual void close();

signals:
/// Emitted when this connection intends to be connected.
/// The server should initialize this connection an open it.
void connectAndInitializeRequested();

private:
QTimer pingTimer_;
QTimer reconnectTimer_;
Expand Down
132 changes: 109 additions & 23 deletions src/providers/twitch/TwitchAccount.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,74 @@ namespace chatterino {

using namespace literals;

TwitchAccount::TwitchAccount(const QString &username, const QString &oauthToken,
const QString &oauthClient, const QString &userID)
std::optional<TwitchAccountData> TwitchAccountData::loadRaw(
const std::string &key)
{
using QStringSetting = pajlada::Settings::Setting<QString>;

auto username = QStringSetting::get("/accounts/" + key + "/username");
auto userID = QStringSetting::get("/accounts/" + key + "/userID");
auto clientID = QStringSetting::get("/accounts/" + key + "/clientID");
auto oauthToken = QStringSetting::get("/accounts/" + key + "/oauthToken");

if (username.isEmpty() || userID.isEmpty() || clientID.isEmpty() ||
oauthToken.isEmpty())
{
return std::nullopt;
}

auto accountType = EnumStringSetting<TwitchAccount::Type>::get(
"/accounts/" + key + "/accountType",
TwitchAccount::Type::ImplicitGrant);
auto refreshToken =
QStringSetting::get("/accounts/" + key + "/refreshToken");
auto expiresAtStr = QStringSetting::get("/accounts/" + key + "/expiresAt");
QDateTime expiresAt;
if (accountType == TwitchAccount::Type::DeviceAuth)
{
expiresAt = QDateTime::fromString(expiresAtStr, Qt::ISODate);
}

return TwitchAccountData{
.username = username.trimmed(),
.userID = userID.trimmed(),
.clientID = clientID.trimmed(),
.oauthToken = oauthToken.trimmed(),
.ty = accountType,
.refreshToken = refreshToken,
.expiresAt = expiresAt,
};
}

void TwitchAccountData::save() const
{
using QStringSetting = pajlada::Settings::Setting<QString>;

auto basePath = "/accounts/uid" + this->userID.toStdString();
QStringSetting::set(basePath + "/username", this->username);
QStringSetting::set(basePath + "/userID", this->userID);
QStringSetting::set(basePath + "/clientID", this->clientID);
QStringSetting::set(basePath + "/oauthToken", this->oauthToken);
EnumStringSetting<TwitchAccount::Type>::set(basePath + "/accountType",
this->ty);
QStringSetting::set(basePath + "/refreshToken", this->refreshToken);
if (this->ty == TwitchAccount::Type::DeviceAuth)
{
QStringSetting::set(basePath + "/expiresAt",
this->expiresAt.toString(Qt::ISODate));
}
}

TwitchAccount::TwitchAccount(const TwitchAccountData &data)
: Account(ProviderId::Twitch)
, oauthClient_(oauthClient)
, oauthToken_(oauthToken)
, userName_(username)
, userId_(userID)
, isAnon_(username == ANONYMOUS_USERNAME)
, oauthClient_(data.clientID)
, oauthToken_(data.oauthToken)
, userName_(data.username)
, userId_(data.userID)
, type_(data.ty)
, refreshToken_(data.refreshToken)
, expiresAt_(data.expiresAt)
, isAnon_(data.username == ANONYMOUS_USERNAME)
, emoteSets_(std::make_shared<TwitchEmoteSetMap>())
, emotes_(std::make_shared<EmoteMap>())
{
Expand Down Expand Up @@ -70,6 +130,21 @@ const QString &TwitchAccount::getUserId() const
return this->userId_;
}

const QString &TwitchAccount::refreshToken() const
{
return this->refreshToken_;
}

const QDateTime &TwitchAccount::expiresAt() const
{
return this->expiresAt_;
}

TwitchAccount::Type TwitchAccount::type() const
{
return this->type_;
}

QColor TwitchAccount::color()
{
return this->color_.get();
Expand All @@ -80,28 +155,39 @@ void TwitchAccount::setColor(QColor color)
this->color_.set(std::move(color));
}

bool TwitchAccount::setOAuthClient(const QString &newClientID)
bool TwitchAccount::setData(const TwitchAccountData &data)
{
if (this->oauthClient_.compare(newClientID) == 0)
{
return false;
}
assert(this->userName_ == data.username && this->userId_ == data.userID);

this->oauthClient_ = newClientID;

return true;
}
bool anyUpdate = false;

bool TwitchAccount::setOAuthToken(const QString &newOAuthToken)
{
if (this->oauthToken_.compare(newOAuthToken) == 0)
if (this->oauthToken_ != data.oauthToken)
{
return false;
this->oauthToken_ = data.oauthToken;
anyUpdate = true;
}
if (this->oauthClient_ != data.clientID)
{
this->oauthClient_ = data.clientID;
anyUpdate = true;
}
if (this->refreshToken_ != data.refreshToken)
{
this->refreshToken_ = data.refreshToken;
anyUpdate = true;
}
if (this->expiresAt_ != data.expiresAt)
{
this->expiresAt_ = data.expiresAt;
anyUpdate = true;
}
if (this->type_ != data.ty)
{
this->type_ = data.ty;
anyUpdate = true;
}

this->oauthToken_ = newOAuthToken;

return true;
return anyUpdate;
}

bool TwitchAccount::isAnon() const
Expand Down
65 changes: 56 additions & 9 deletions src/providers/twitch/TwitchAccount.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include <boost/unordered/unordered_flat_map_fwd.hpp>
#include <pajlada/signals.hpp>
#include <QColor>
#include <QDateTime>
#include <QElapsedTimer>
#include <QObject>
#include <QString>
Expand All @@ -26,11 +27,41 @@ namespace chatterino {
class Channel;
using ChannelPtr = std::shared_ptr<Channel>;

struct TwitchAccountData;

class TwitchAccount : public Account
{
public:
TwitchAccount(const QString &username, const QString &oauthToken_,
const QString &oauthClient_, const QString &_userID);
enum class Type : uint32_t {
Nerixyz marked this conversation as resolved.
Show resolved Hide resolved
Nerixyz marked this conversation as resolved.
Show resolved Hide resolved
Nerixyz marked this conversation as resolved.
Show resolved Hide resolved
/// Tokens as obtained from https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#implicit-grant-flow
ImplicitGrant,
/// Tokens as obtained from https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#device-code-grant-flow
DeviceAuth,
};
struct TwitchEmote {
EmoteId id;
EmoteName name;
};

struct EmoteSet {
QString key;
QString channelName;
QString channelID;
QString text;
bool subscriber{false};
bool local{false};
std::vector<TwitchEmote> emotes;
};

struct TwitchAccountEmoteData {
std::vector<std::shared_ptr<EmoteSet>> emoteSets;

// this EmoteMap should contain all emotes available globally
// excluding locally available emotes, such as follower ones
EmoteMap emotes;
};

TwitchAccount(const TwitchAccountData &data);
~TwitchAccount() override;
TwitchAccount(const TwitchAccount &) = delete;
TwitchAccount(TwitchAccount &&) = delete;
Expand All @@ -43,6 +74,9 @@ class TwitchAccount : public Account
const QString &getOAuthToken() const;
const QString &getOAuthClient() const;
const QString &getUserId() const;
[[nodiscard]] const QString &refreshToken() const;
[[nodiscard]] const QDateTime &expiresAt() const;
[[nodiscard]] Type type() const;

/**
* The Seventv user-id of the current user.
Expand All @@ -53,13 +87,10 @@ class TwitchAccount : public Account
QColor color();
void setColor(QColor color);

// Attempts to update the users OAuth Client ID
// Returns true if the value has changed, otherwise false
bool setOAuthClient(const QString &newClientID);

// Attempts to update the users OAuth Token
// Returns true if the value has changed, otherwise false
bool setOAuthToken(const QString &newOAuthToken);
/// Attempts to update the account data
/// @pre The name and userID must match this account.
/// @returns true if the value has changed, otherwise false
bool setData(const TwitchAccountData &data);

bool isAnon() const;

Expand Down Expand Up @@ -112,6 +143,9 @@ class TwitchAccount : public Account
QString oauthToken_;
QString userName_;
QString userId_;
Type type_ = Type::ImplicitGrant;
QString refreshToken_;
QDateTime expiresAt_;
const bool isAnon_;
Atomic<QColor> color_;

Expand All @@ -128,4 +162,17 @@ class TwitchAccount : public Account
QString seventvUserID_;
};

struct TwitchAccountData {
QString username;
QString userID;
QString clientID;
QString oauthToken;
TwitchAccount::Type ty = TwitchAccount::Type::ImplicitGrant;
QString refreshToken;
QDateTime expiresAt;

static std::optional<TwitchAccountData> loadRaw(const std::string &key);
void save() const;
};

} // namespace chatterino
Loading
Loading