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 10 commits into
base: master
Choose a base branch
from
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
- Minor: Tabs unhighlight when their content is read in other tabs. (#5649)
- Minor: Made usernames in bits and sub messages clickable. (#5686)
- Minor: Mentions of FrankerFaceZ and BetterTTV in settings are standardized as such. (#5698)
- 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 @@ -111,7 +111,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 @@ -138,6 +137,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
23 changes: 23 additions & 0 deletions src/messages/MessageBuilder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1987,6 +1987,29 @@ MessagePtr MessageBuilder::makeLowTrustUpdateMessage(
return builder.release();
}

MessagePtrMut MessageBuilder::makeAccountExpiredMessage(
const QString &expirationText)
{
auto loginPromptText = u"Try adding your account again."_s;

MessageBuilder builder;
auto text = expirationText % ' ' % loginPromptText;
builder->messageText = text;
builder->searchText = text;
builder->flags.set(MessageFlag::System,
MessageFlag::DoNotTriggerNotification);

builder.emplace<TimestampElement>();
builder.emplace<TextElement>(expirationText, MessageElementFlag::Text,
MessageColor::System);
builder
.emplace<TextElement>(loginPromptText, MessageElementFlag::Text,
MessageColor::Link)
->setLink({Link::OpenAccountsPage, {}});

return builder.release();
}

std::pair<MessagePtrMut, HighlightAlert> MessageBuilder::makeIrcMessage(
/* mutable */ Channel *channel, const Communi::IrcMessage *ircMessage,
const MessageParseArgs &args, /* mutable */ QString content,
Expand Down
3 changes: 3 additions & 0 deletions src/messages/MessageBuilder.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,9 @@ class MessageBuilder
const QVariantMap &tags,
const QTime &time);

static MessagePtrMut makeAccountExpiredMessage(
const QString &expirationText);

private:
struct TextState {
TwitchChannel *twitchChannel = nullptr;
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
23 changes: 2 additions & 21 deletions src/providers/twitch/IrcMessageHandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -230,29 +230,10 @@ MessagePtr parseNoticeMessage(Communi::IrcNoticeMessage *message)

if (message->content().startsWith("Login auth", Qt::CaseInsensitive))
{
const auto linkColor = MessageColor(MessageColor::Link);
const auto accountsLink = Link(Link::OpenAccountsPage, QString());
const auto curUser = getApp()->getAccounts()->twitch.getCurrent();
const auto expirationText = QString("Login expired for user \"%1\"!")
.arg(curUser->getUserName());
const auto loginPromptText = QString("Try adding your account again.");

MessageBuilder builder;
auto text = QString("%1 %2").arg(expirationText, loginPromptText);
builder.message().messageText = text;
builder.message().searchText = text;
builder.message().flags.set(MessageFlag::System);
builder.message().flags.set(MessageFlag::DoNotTriggerNotification);

builder.emplace<TimestampElement>();
builder.emplace<TextElement>(expirationText, MessageElementFlag::Text,
MessageColor::System);
builder
.emplace<TextElement>(loginPromptText, MessageElementFlag::Text,
linkColor)
->setLink(accountsLink);

return builder.release();
return MessageBuilder::makeAccountExpiredMessage(
u"Login expired for user \"" % curUser->getUserName() % u"\"!");
}

if (message->content().startsWith("You are permanently banned "))
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
Loading
Loading