Add ASF 2FA service endpoints (#2426)

* Add ASF 2FA service endpoints

* Misc.

* Move back to .../TwoFactorAuthentication

* Remove duplicate endpoints

* Remove now useless constructor

* Apply feedback
This commit is contained in:
Sebastian Göls
2021-10-14 23:41:12 +02:00
committed by GitHub
parent aedc9f0b21
commit f93143c133
3 changed files with 211 additions and 71 deletions

View File

@@ -458,71 +458,5 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
return Ok(new GenericResponse(results.All(static result => result.Success), string.Join(Environment.NewLine, results.Select(static result => result.Message))));
}
/// <summary>
/// Handles 2FA confirmations of given bots, requires ASF 2FA module to be active on them.
/// </summary>
[HttpPost("{botNames:required}/TwoFactorAuthentication/Confirmations")]
[ProducesResponseType(typeof(GenericResponse<IReadOnlyDictionary<string, GenericResponse<IReadOnlyCollection<Confirmation>>>>), (int) HttpStatusCode.OK)]
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> TwoFactorAuthenticationConfirmationsPost(string botNames, [FromBody] TwoFactorAuthenticationConfirmationsRequest request) {
if (string.IsNullOrEmpty(botNames)) {
throw new ArgumentNullException(nameof(botNames));
}
if (request == null) {
throw new ArgumentNullException(nameof(request));
}
if (request.AcceptedType.HasValue && ((request.AcceptedType.Value == Confirmation.EType.Unknown) || !Enum.IsDefined(typeof(Confirmation.EType), request.AcceptedType.Value))) {
return BadRequest(new GenericResponse(false, string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsInvalid, nameof(request.AcceptedType))));
}
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse<IReadOnlyDictionary<string, GenericResponse<IReadOnlyCollection<Confirmation>>>>(false, string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)));
}
IList<(bool Success, IReadOnlyCollection<Confirmation>? HandledConfirmations, string Message)> results = await Utilities.InParallel(bots.Select(bot => bot.Actions.HandleTwoFactorAuthenticationConfirmations(request.Accept, request.AcceptedType, request.AcceptedCreatorIDs.Count > 0 ? request.AcceptedCreatorIDs : null, request.WaitIfNeeded))).ConfigureAwait(false);
Dictionary<string, GenericResponse<IReadOnlyCollection<Confirmation>>> result = new(bots.Count, Bot.BotsComparer);
foreach (Bot bot in bots) {
(bool success, IReadOnlyCollection<Confirmation>? handledConfirmations, string message) = results[result.Count];
result[bot.BotName] = new GenericResponse<IReadOnlyCollection<Confirmation>>(success, message, handledConfirmations);
}
return Ok(new GenericResponse<IReadOnlyDictionary<string, GenericResponse<IReadOnlyCollection<Confirmation>>>>(result));
}
/// <summary>
/// Fetches 2FA tokens of given bots, requires ASF 2FA module to be active on them.
/// </summary>
[HttpGet("{botNames:required}/TwoFactorAuthentication/Token")]
[ProducesResponseType(typeof(GenericResponse<IReadOnlyDictionary<string, GenericResponse<string>>>), (int) HttpStatusCode.OK)]
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> TwoFactorAuthenticationTokenGet(string botNames) {
if (string.IsNullOrEmpty(botNames)) {
throw new ArgumentNullException(nameof(botNames));
}
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse<IReadOnlyDictionary<string, GenericResponse<string>>>(false, string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)));
}
IList<(bool Success, string? Token, string Message)> results = await Utilities.InParallel(bots.Select(static bot => bot.Actions.GenerateTwoFactorAuthenticationToken())).ConfigureAwait(false);
Dictionary<string, GenericResponse<string>> result = new(bots.Count, Bot.BotsComparer);
foreach (Bot bot in bots) {
(bool success, string? token, string message) = results[result.Count];
result[bot.BotName] = new GenericResponse<string>(success, message, token);
}
return Ok(new GenericResponse<IReadOnlyDictionary<string, GenericResponse<string>>>(result));
}
}
}

View File

@@ -0,0 +1,167 @@
// _ _ _ ____ _ _____
// / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
// / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
// / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
// /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
// |
// Copyright 2015-2021 Łukasz "JustArchi" Domeradzki
// Contact: JustArchi@JustArchi.net
// |
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// |
// http://www.apache.org/licenses/LICENSE-2.0
// |
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#if NETFRAMEWORK
using JustArchiNET.Madness;
#endif
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using ArchiSteamFarm.Core;
using ArchiSteamFarm.IPC.Requests;
using ArchiSteamFarm.IPC.Responses;
using ArchiSteamFarm.Localization;
using ArchiSteamFarm.Steam;
using ArchiSteamFarm.Steam.Security;
using Microsoft.AspNetCore.Mvc;
namespace ArchiSteamFarm.IPC.Controllers.Api {
[Route("Api/Bot/{botNames:required}/TwoFactorAuthentication")]
public sealed class TwoFactorAuthenticationController : ArchiController {
/// <summary>
/// Deletes the MobileAuthenticator of given bots if an ASF 2FA module is active on them.
/// </summary>
[HttpDelete]
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)]
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> AuthenticatorDelete(string botNames) {
if (string.IsNullOrEmpty(botNames)) {
throw new ArgumentNullException(nameof(botNames));
}
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse<IReadOnlyDictionary<string, GenericResponse<string>>>(false, string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)));
}
IList<(bool Success, string? Message)> results = await Utilities.InParallel(bots.Select(static bot => Task.Run(bot.RemoveAuthenticator))).ConfigureAwait(false);
Dictionary<string, GenericResponse<string>> result = new (bots.Count, Bot.BotsComparer);
foreach (Bot bot in bots) {
(bool success, string? message) = results[result.Count];
result[bot.BotName] = new GenericResponse<string>(success, message);
}
return Ok(new GenericResponse<IReadOnlyDictionary<string, GenericResponse<string>>>(result));
}
/// <summary>
/// Imports a MobileAuthenticator into the ASF 2FA module of a given bot.
/// </summary>
[Consumes("application/json")]
[HttpPost]
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)]
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public ActionResult<GenericResponse> AuthenticatorPost(string botNames, [FromBody] MobileAuthenticator authenticator) {
if (string.IsNullOrEmpty(botNames)) {
throw new ArgumentNullException(nameof(botNames));
}
Bot? bot = Bot.GetBot(botNames);
if (bot == null) {
return BadRequest(new GenericResponse<IReadOnlyDictionary<string, GenericResponse<string>>>(false, string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)));
}
if (authenticator == null) {
throw new ArgumentNullException(nameof(authenticator));
}
if (bot.TryImportAuthenticator(authenticator)) {
return Ok(new GenericResponse(true));
}
return BadRequest(new GenericResponse(false, string.Format(CultureInfo.CurrentCulture, Strings.WarningFailed)));
}
/// <summary>
/// Handles 2FA confirmations of given bots, requires ASF 2FA module to be active on them.
/// </summary>
[Consumes("application/json")]
[HttpPost("Confirmations")]
[ProducesResponseType(typeof(GenericResponse<IReadOnlyDictionary<string, GenericResponse<IReadOnlyCollection<Confirmation>>>>), (int) HttpStatusCode.OK)]
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> ConfirmationsPost(string botNames, [FromBody] TwoFactorAuthenticationConfirmationsRequest request) {
if (string.IsNullOrEmpty(botNames)) {
throw new ArgumentNullException(nameof(botNames));
}
if (request == null) {
throw new ArgumentNullException(nameof(request));
}
if (request.AcceptedType.HasValue && ((request.AcceptedType.Value == Confirmation.EType.Unknown) || !Enum.IsDefined(typeof(Confirmation.EType), request.AcceptedType.Value))) {
return BadRequest(new GenericResponse(false, string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsInvalid, nameof(request.AcceptedType))));
}
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse<IReadOnlyDictionary<string, GenericResponse<IReadOnlyCollection<Confirmation>>>>(false, string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)));
}
IList<(bool Success, IReadOnlyCollection<Confirmation>? HandledConfirmations, string Message)> results = await Utilities.InParallel(bots.Select(bot => bot.Actions.HandleTwoFactorAuthenticationConfirmations(request.Accept, request.AcceptedType, request.AcceptedCreatorIDs.Count > 0 ? request.AcceptedCreatorIDs : null, request.WaitIfNeeded))).ConfigureAwait(false);
Dictionary<string, GenericResponse<IReadOnlyCollection<Confirmation>>> result = new(bots.Count, Bot.BotsComparer);
foreach (Bot bot in bots) {
(bool success, IReadOnlyCollection<Confirmation>? handledConfirmations, string message) = results[result.Count];
result[bot.BotName] = new GenericResponse<IReadOnlyCollection<Confirmation>>(success, message, handledConfirmations);
}
return Ok(new GenericResponse<IReadOnlyDictionary<string, GenericResponse<IReadOnlyCollection<Confirmation>>>>(result));
}
/// <summary>
/// Fetches 2FA tokens of given bots, requires ASF 2FA module to be active on them.
/// </summary>
[HttpGet("Token")]
[ProducesResponseType(typeof(GenericResponse<IReadOnlyDictionary<string, GenericResponse<string>>>), (int) HttpStatusCode.OK)]
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> TokenGet(string botNames) {
if (string.IsNullOrEmpty(botNames)) {
throw new ArgumentNullException(nameof(botNames));
}
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse<IReadOnlyDictionary<string, GenericResponse<string>>>(false, string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)));
}
IList<(bool Success, string? Token, string Message)> results = await Utilities.InParallel(bots.Select(static bot => bot.Actions.GenerateTwoFactorAuthenticationToken())).ConfigureAwait(false);
Dictionary<string, GenericResponse<string>> result = new (bots.Count, Bot.BotsComparer);
foreach (Bot bot in bots) {
(bool success, string? token, string message) = results[result.Count];
result[bot.BotName] = new GenericResponse<string>(success, message, token);
}
return Ok(new GenericResponse<IReadOnlyDictionary<string, GenericResponse<string>>>(result));
}
}
}

View File

@@ -487,7 +487,9 @@ namespace ArchiSteamFarm.Steam {
Regex regex;
try {
#pragma warning disable CA3012
regex = new Regex(botsPattern, botsRegex);
#pragma warning restore CA3012
} catch (ArgumentException e) {
ASF.ArchiLogger.LogGenericWarningException(e);
@@ -1647,7 +1649,7 @@ namespace ArchiSteamFarm.Steam {
}
if (File.Exists(mobileAuthenticatorFilePath)) {
await ImportAuthenticator(mobileAuthenticatorFilePath).ConfigureAwait(false);
await ImportAuthenticatorFromFile(mobileAuthenticatorFilePath).ConfigureAwait(false);
}
}
@@ -1918,7 +1920,7 @@ namespace ArchiSteamFarm.Steam {
}
}
private async Task ImportAuthenticator(string maFilePath) {
private async Task ImportAuthenticatorFromFile(string maFilePath) {
if (HasMobileAuthenticator || !File.Exists(maFilePath)) {
return;
}
@@ -1942,8 +1944,9 @@ namespace ArchiSteamFarm.Steam {
return;
}
authenticator.Init(this);
BotDatabase.MobileAuthenticator = authenticator;
if (!TryImportAuthenticator(authenticator)) {
return;
}
File.Delete(maFilePath);
} catch (Exception e) {
@@ -1955,6 +1958,42 @@ namespace ArchiSteamFarm.Steam {
ArchiLogger.LogGenericInfo(Strings.BotAuthenticatorImportFinished);
}
internal bool TryImportAuthenticator(MobileAuthenticator authenticator) {
if (authenticator == null) {
throw new ArgumentNullException(nameof(authenticator));
}
if (HasMobileAuthenticator) {
return false;
}
try {
authenticator.Init(this);
BotDatabase.MobileAuthenticator = authenticator;
} catch (Exception e) {
ArchiLogger.LogGenericException(e);
return false;
}
ArchiLogger.LogGenericInfo(Strings.BotAuthenticatorImportFinished);
return true;
}
internal (bool Success, string? Message) RemoveAuthenticator() {
MobileAuthenticator? authenticator = BotDatabase.MobileAuthenticator;
if (authenticator == null) {
return (false, Strings.BotNoASFAuthenticator);
}
BotDatabase.MobileAuthenticator = null;
authenticator.Dispose();
return (true, null);
}
private void InitConnectionFailureTimer() {
if (ConnectionFailureTimer != null) {
return;
@@ -2743,7 +2782,7 @@ namespace ArchiSteamFarm.Steam {
string maFilePath = Path.Combine(SharedInfo.ConfigDirectory, SteamID + SharedInfo.MobileAuthenticatorExtension);
if (File.Exists(maFilePath)) {
await ImportAuthenticator(maFilePath).ConfigureAwait(false);
await ImportAuthenticatorFromFile(maFilePath).ConfigureAwait(false);
}
}