|
| 1 | +using Newtonsoft.Json.Linq; |
| 2 | +using RestApia.Shared.Common.Models; |
| 3 | +namespace RestApia.Extensions.Import.Postman.Logic; |
| 4 | + |
| 5 | +internal static class ImportAuthOAuth2 |
| 6 | +{ |
| 7 | + public static AuthContentModel? Import(JToken data) |
| 8 | + { |
| 9 | + var values = Tools.ParseValues(data["oauth2"] as JArray ?? []) |
| 10 | + .ToDictionary(x => x.Key, x => x.Value); |
| 11 | + |
| 12 | + var grandType = values.GetValueOrDefault("grant_type", string.Empty); |
| 13 | + return grandType switch |
| 14 | + { |
| 15 | + "authorization_code" => ParseAuthOAuth2AuthorizationCode(values), |
| 16 | + _ => ParseAuthOAuth2UnknownGrandType(data), |
| 17 | + }; |
| 18 | + } |
| 19 | + |
| 20 | + private static AuthContentModel ParseAuthOAuth2AuthorizationCode(Dictionary<string, string> values) |
| 21 | + { |
| 22 | + // OAuth2AuthCodeSettings object |
| 23 | + var settings = new Dictionary<string, string> |
| 24 | + { |
| 25 | + { "AuthUrl", values.GetValueOrDefault("authUrl", string.Empty) }, |
| 26 | + { "AccessTokenUrl", values.GetValueOrDefault("accessTokenUrl", string.Empty) }, |
| 27 | + { "RedirectUrl", values.GetValueOrDefault("redirect_uri", string.Empty) }, |
| 28 | + { "ClientId", values.GetValueOrDefault("clientId", string.Empty) }, |
| 29 | + { "ClientSecret", values.GetValueOrDefault("clientSecret", string.Empty) }, |
| 30 | + { "Scopes", values.GetValueOrDefault("scope", string.Empty) }, |
| 31 | + { "CredentialsSendMethod", values.GetValueOrDefault("client_authentication", string.Empty).Equals("body", StringComparison.OrdinalIgnoreCase) ? "Body" : "Header" }, |
| 32 | + }; |
| 33 | + |
| 34 | + return new AuthContentModel |
| 35 | + { |
| 36 | + Name = "OAuth2 - Authorization Code", |
| 37 | + SettingsClassFullName = "RestApia.Extensions.Auth.OAuth2.AuthCode.OAuth2AuthCodeSettings", |
| 38 | + Content = Tools.SerializeValues(settings), |
| 39 | + }; |
| 40 | + } |
| 41 | + |
| 42 | + private static AuthContentModel? ParseAuthOAuth2UnknownGrandType(JToken data) |
| 43 | + { |
| 44 | + var result = ImportCollection.ParseAuthUnsupported(data); |
| 45 | + if (result == null) return null; |
| 46 | + |
| 47 | + return result with |
| 48 | + { |
| 49 | + Name = "OAuth2 - Unsupported grant type", |
| 50 | + Content = $"// Unsupported OAuth2 grant type: {data["grant_type"]}\r\n" + result.Content, |
| 51 | + }; |
| 52 | + } |
| 53 | +} |
0 commit comments