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

Add basic authorization #4

Merged
merged 1 commit into from
Oct 25, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 3 additions & 2 deletions Apis/IServerDiscordApi.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Refit;
using app.Models;
using Refit;

namespace app.Apis;

Expand Down Expand Up @@ -29,5 +30,5 @@ public interface IServerDiscordApi
Task<bool> PostBan(string channel, ulong senderId, string senderName, ulong targetId, string targetName, string reason);

[Post("/login")]
Task<(bool, string)> PostLogin(string name, ulong id, string username, string discriminator, string avatarurl, string password);
Task<ResponsePairDto> PostLogin(string name, ulong id, string username, string discriminator, string avatarurl, string password);
}
2 changes: 2 additions & 0 deletions Controllers/DiscordController.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
using app.Apis;
using app.Models;
using app.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace app.Controllers
{
[ApiController]
[Authorize]
[Route("[controller]/[action]")]
public class DiscordController : ControllerBase
{
Expand Down
4 changes: 3 additions & 1 deletion Controllers/FeedsController.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using app.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace app.Controllers
{
[ApiController]
[Authorize]
[Route("[controller]/[action]")]
public class FeedsController : ControllerBase
{
Expand All @@ -14,7 +16,7 @@ public FeedsController(DiscordService discordService)
}

[HttpPost(Name = "send")]
public async Task PostSend(string channel, [FromBody] string message)
public async Task PostSend(string channel, string message)
{
var discordChannel = channel switch
{
Expand Down
2 changes: 2 additions & 0 deletions Controllers/PresenceController.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
using app.Services;
using DSharpPlus.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace app.Controllers
{
[ApiController]
[Authorize]
[Route("[controller]/[action]")]
public class PresenceController : ControllerBase
{
Expand Down
53 changes: 53 additions & 0 deletions Middlewares/BasicAuthenticationHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using app.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;

namespace app.Middlewares
{
public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
private readonly IConfiguration _configuration;
private readonly Credentials _credentials;

public BasicAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
IOptions<Credentials> credentials,
IConfiguration configuration) : base(options, logger, encoder, clock)
{
_configuration = configuration;
_credentials = credentials.Value;
}

protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
string authHeader = Request.Headers["Authorization"];
if (authHeader != null && authHeader.StartsWith("Basic"))
{

var authHeaderValue = authHeader.Replace("Basic ", "");
var decodedAuthHeaderValue = Encoding.UTF8.GetString(Convert.FromBase64String(authHeaderValue));
var userPassArray = decodedAuthHeaderValue.Split(":");
var extractedUsername = userPassArray[0];
var extractedPassword = userPassArray[1];

if (string.Equals(_credentials.Username, extractedUsername) && string.Equals(extractedPassword, _credentials.Password))
{
var claims = new[] { new Claim(ClaimTypes.Name, _credentials.Username) };
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);

return AuthenticateResult.Success(ticket);
}
}
return AuthenticateResult.Fail("Failed to authenticate");
}
}

}
8 changes: 8 additions & 0 deletions Models/Credentials.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace app.Models
{
public class Credentials
{
public string Username { get; set; }
public string Password { get; set; }
}
}
18 changes: 18 additions & 0 deletions Models/ResponsePairDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
namespace app.Models
{
public class ResponsePairDto
{
public ResponsePairDto()
{
}

public ResponsePairDto(bool status, string message)
{
Status = status;
Message = message;
}

public bool Status { get; set; }
public string Message { get; set; }
}
}
38 changes: 36 additions & 2 deletions Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
using app.Services;
using app.Settings;
using app;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.OpenApi.Models;
using app.Models;
using Microsoft.Extensions.Configuration;
using app.Middlewares;
using Microsoft.AspNetCore.Authentication;

var builder = WebApplication.CreateBuilder(args);

Expand All @@ -9,6 +17,7 @@

builder.Services.Configure<DiscordSettings>(options => builder.Configuration.GetSection(nameof(DiscordSettings)).Bind(options));
builder.Services.Configure<ServerApiSettings>(options => builder.Configuration.GetSection(nameof(ServerApiSettings)).Bind(options));
builder.Services.Configure<Credentials>(options => builder.Configuration.GetSection(nameof(Credentials)).Bind(options));

builder.Services.AddRefitServices(serverApiSettings);
builder.Services.AddControllers();
Expand All @@ -19,6 +28,32 @@
builder.Services.AddSingleton<RunnerService>();
builder.Services.AddSingleton<GuildJoinService>();
builder.Services.AddHostedService(provider => provider.GetService<RunnerService>());
builder.Services.AddAuthentication("BasicAuthentication")
.AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);

builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" });
c.AddSecurityDefinition("Basic", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "basic",
In = ParameterLocation.Header,
Description = "Basic Authorization header."
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Basic" }
},
new string[] { }
}
});
});


var app = builder.Build();

Expand All @@ -32,9 +67,8 @@
await app.Services.GetService<DiscordService>().Start();

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();
14 changes: 9 additions & 5 deletions Services/LoginService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ private async Task HandleLoginCommand(MessageCreateEventArgs e, string name, str
return;
}

var (status, response) = await _serverDiscordApi.PostLogin(name, discordMember.Id, discordMember.Username, discordMember.Discriminator, discordMember.AvatarUrl, password);
var response = await _serverDiscordApi.PostLogin(name, discordMember.Id, discordMember.Username, discordMember.Discriminator, discordMember.AvatarUrl, password);

if(status)
if(response.Status)
{
await discordMember.GrantRoleAsync(_discordService.MemberRole);
}
await e.Channel.SendMessageAsync(response);

await e.Message.RespondAsync(response.Message);
}

private async Task OnPrivateMessage(MessageCreateEventArgs e)
Expand All @@ -62,7 +62,7 @@ private async Task OnPrivateMessage(MessageCreateEventArgs e)

if (index == -1)
{
await e.Channel.SendMessageAsync("Incorrect format! Write **!login USERNAME PASSWORD**");
await e.Message.RespondAsync("Incorrect format! Write **!login USERNAME PASSWORD**");
return;
}

Expand All @@ -71,5 +71,9 @@ private async Task OnPrivateMessage(MessageCreateEventArgs e)

await HandleLoginCommand(e, accountName, password);
}
else
{
await e.Message.RespondAsync("Incorrect format! Write **!login USERNAME PASSWORD**");
}
}
}
3 changes: 2 additions & 1 deletion app.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>de413ddd-1e74-4cb2-80c7-bc2e2469d599</UserSecretsId>
Expand All @@ -12,6 +12,7 @@
<ItemGroup>
<PackageReference Include="DSharpPlus" Version="4.4.2" />
<PackageReference Include="DSharpPlus.CommandsNext" Version="4.4.2" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.13" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
<PackageReference Include="Refit" Version="7.0.0" />
<PackageReference Include="Refit.HttpClientFactory" Version="7.0.0" />
Expand Down
58 changes: 31 additions & 27 deletions appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,36 +6,40 @@
}
},
"AllowedHosts": "*",
"Credentials": {
"Username": "your_username",
"Password": "your_password"
},
"ServerApiSettings": {
"Url": "http://localhost:9696/api/",
"Username": "admin",
"Password": "test2"
"Password": "test"
},
"DiscordSettings": {
"Token": "DISCORD_BOT_API",
"Guild": 42069,
"Channels": {
"Commands": 42069,
"General": 42069,
"Surveilance": 42069,
"Cheat": 42069,
"LinkedAccounts": 42069,
"VerifyLogs": 42069,
"DiscordBotLogs": 42069,
"Verification": 42069,
"HelpVerify": 42069,
"LinkedAccountsCompact": 42069,
"WeazelFeed": 42069,
"QuizUpdates": 42069,
"AccountCreation": 42069,
"BanNotifications": 42069
},
"Roles": {
"Donator": 42069,
"Member": 42069,
"Banned": 42069,
"ReadOnly": 42069,
"Creator": 42069
}
"DiscordSettings": {
"Token": "DISCORD_BOT_API",
"Guild": 42069,
"Channels": {
"Commands": 42069,
"General": 42069,
"Surveilance": 42069,
"Cheat": 42069,
"LinkedAccounts": 42069,
"VerifyLogs": 42069,
"DiscordBotLogs": 42069,
"Verification": 42069,
"HelpVerify": 42069,
"LinkedAccountsCompact": 42069,
"WeazelFeed": 42069,
"QuizUpdates": 42069,
"AccountCreation": 42069,
"BanNotifications": 42069
},
"Roles": {
"Donator": 42069,
"Member": 42069,
"Banned": 42069,
"ReadOnly": 42069,
"Creator": 42069
}
}
}