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

hard coded connection string to test #2

Merged
merged 28 commits into from
Jun 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
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
43 changes: 31 additions & 12 deletions .aws/TalkWaveApiTask.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,38 @@
{
"name": "talkwaveapi",
"image": "584742206045.dkr.ecr.us-east-2.amazonaws.com/talkwaveapi:latest",
"cpu": 700,
"memory": 700,
"cpu": 800,
"memory": 800,
"portMappings": [
{
"name": "talkwaveapi-80-tcp",
"containerPort": 80,
"hostPort": 80,
"name": "talkwaveapi-8080-tcp",
"containerPort": 8080,
"hostPort": 8080,
"protocol": "tcp",
"appProtocol": "http"
},
{
"name": "postgres",
"containerPort": 5432,
"hostPort": 5432,
"protocol": "tcp",
"appProtocol": "http"
},
{
"name": "redis",
"containerPort": 6379,
"hostPort": 6379,
"protocol": "tcp",
"appProtocol": "http"
}
],
"essential": true,
"environment": [],
"environment": [
{
"name": "CONNECTIONSTRINGS__DEFAULTCONNECTION",
"value": "Server=talkwave.cdgsao6goy8f.us-east-2.rds.amazonaws.com;Port=5432;Database=TalkWave;Username=postgres;password=Uq85xSNS4c4Q86kD"
}
],
"environmentFiles": [
{
"value": "arn:aws:s3:::talkwave-signalr-env/.env",
Expand All @@ -37,13 +56,13 @@
},
"healthCheck": {
"command": [
"[ \"CMD-SHELL\"",
"\"curl -f http://localhost/health || exit 1\" ]"
"CMD-SHELL",
"curl --fail http://localhost:8080/health || exit 1"
],
"interval": 30,
"timeout": 5,
"interval": 60,
"timeout": 10,
"retries": 3,
"startPeriod": 60
"startPeriod": 300
},
"systemControls": []
}
Expand All @@ -58,4 +77,4 @@
"cpuArchitecture": "X86_64",
"operatingSystemFamily": "LINUX"
}
}
}
3 changes: 1 addition & 2 deletions .github/workflows/aws.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ permissions:
env:
AWS_REGION: us-east-2 # set this to your preferred AWS region, e.g. us-west-1
ECR_REPOSITORY: 584742206045.dkr.ecr.us-east-2.amazonaws.com/talkwaveapi # set this to your Amazon ECR repository name
ECS_SERVICE: TalkWaveApiService # set this to your Amazon ECS service name
ECS_SERVICE: TalkWaveECSSignalR # set this to your Amazon ECS service name
ECS_CLUSTER: TalkWaveClusterSignalR # set this to your Amazon ECS cluster name
ECS_TASK_DEFINITION:
./.aws/TalkWaveApiTask.json # set this to the path to your Amazon ECS task definition
Expand Down Expand Up @@ -86,7 +86,6 @@ jobs:
id: task-def
uses: aws-actions/amazon-ecs-render-task-definition@v1
with:
env-files: arn:aws:s3:::talkwave-signalr-env/.env
task-definition: ${{ env.ECS_TASK_DEFINITION }}
container-name: ${{ env.CONTAINER_NAME }}
image: ${{ steps.build-image.outputs.image }}
Expand Down
9 changes: 7 additions & 2 deletions TalkWaveApi.WebSocket/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ RUN dotnet publish -c release -o /app
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app ./
EXPOSE 80
ENV ASPNETCORE_URLS=http://*:80
EXPOSE 8080
EXPOSE 5432
EXPOSE 6379

RUN apt-get update \
&& apt-get install -y curl

ENTRYPOINT ["dotnet", "TalkWaveApi.WebSocket.dll"]
70 changes: 6 additions & 64 deletions TalkWaveApi.WebSocket/Hubs/ChatHub.cs
Original file line number Diff line number Diff line change
@@ -1,36 +1,16 @@

using System.Diagnostics;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using TalkWaveApi.WebSocket.Models;
using TalkWaveApi.WebSocket.Services;


namespace TalkWaveApi.WebSocket.Hubs
{
[Authorize]
public class ChatHub(DatabaseContext dbContext) : Hub
public class ChatHub : Hub
{
private readonly DatabaseContext _context = dbContext;
public async Task JoinGroup(string groupId)
{
string? userId = Context.UserIdentifier;

if (!int.TryParse(userId, out int userParsedId))
{
Context.Abort();
return;
}
User? user = await _context.Users.FindAsync(userParsedId);
if (user == null)
{
Context.Abort();
return;
}
await ValidateChannel(groupId, user, Context);
await Groups.AddToGroupAsync(Context.ConnectionId, groupId);

}
Expand All @@ -41,59 +21,21 @@ public async Task LeaveGroup(string groupId)
}
public async Task SendMessage(string groupId, string message)
{
string? userId = Context.UserIdentifier;
if (!int.TryParse(userId, out int userParsedId))
{
Context.Abort();
return;
}
User? user = await _context.Users.FindAsync(userParsedId);
if (user == null)
string? userEmail = Context.UserIdentifier;

if (userEmail == null)
{
Context.Abort();
return;
}

Message dbMessage = new()
{
UserId = userParsedId,
ChannelId = int.Parse(groupId),
Content = message,
CreatedAt = DateTime.UtcNow
};

MessageDto messageDto = new()
{
Author = user.UserName,
Author = userEmail,
Content = message,
CreatedAt = DateTime.UtcNow,
};
await _context.Messages.AddAsync(dbMessage);
await _context.SaveChangesAsync();

await Clients.Group(groupId).SendAsync("ReceiveMessage", user.UserId, messageDto);
}
public async Task ValidateChannel(string Id, User user, HubCallerContext context)
{
//Validate Id can be casted as int
if (!int.TryParse(Id, out int ChannelId))
{
context.Abort();
}

//Validate channel exists
var channel = await _context.Channels.FindAsync(ChannelId);
if (channel == null)
{
context.Abort();
}

//Validate user is in channel
var userTest = await _context.ChannelUsersStatuses.Where(x => x.ChannelId == ChannelId).Where(x => x.UserId == user.UserId).FirstOrDefaultAsync();
if (userTest == null)
{
context.Abort();
}
await Clients.Group(groupId).SendAsync("ReceiveMessage", userEmail, messageDto);
}
};
}
Expand Down
14 changes: 0 additions & 14 deletions TalkWaveApi.WebSocket/Models/Channel.cs

This file was deleted.

14 changes: 0 additions & 14 deletions TalkWaveApi.WebSocket/Models/ChannelUserStatus.cs

This file was deleted.

15 changes: 0 additions & 15 deletions TalkWaveApi.WebSocket/Models/Message.cs

This file was deleted.

18 changes: 0 additions & 18 deletions TalkWaveApi.WebSocket/Models/User.cs

This file was deleted.

56 changes: 9 additions & 47 deletions TalkWaveApi.WebSocket/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using TalkWaveApi.WebSocket.Hubs;
using TalkWaveApi.WebSocket.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
Expand All @@ -17,7 +15,7 @@

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddSingleton<IUserIdProvider, UserIdProvider>();
builder.Services.AddSingleton<IUserIdProvider, EmailBasedUserIdProvider>();

builder.Services.AddCors(p => p.AddPolicy("dev", builder =>
{
Expand All @@ -26,13 +24,9 @@

builder.Services.AddCors(p => p.AddPolicy("prod", builder =>
{
builder.WithOrigins("https://talkwaveapp.com").AllowAnyMethod().AllowAnyHeader().AllowCredentials();
builder.AllowAnyMethod().AllowAnyHeader().AllowCredentials().SetIsOriginAllowed((host) => true);
}));

builder.Services.AddDbContext<DatabaseContext>(options =>
options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"), x => x.MigrationsHistoryTable("_EfMigrations", Configuration.GetSection("Schema").GetSection("TalkwaveDataSchema").Value)));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddHealthChecks();

builder.Services.AddAuthentication(options =>
Expand Down Expand Up @@ -72,58 +66,22 @@
};
});

var RedisConnection = builder.Configuration.GetConnectionString("RedisConnection");

if (RedisConnection != null)
{
builder.Services.AddSignalR(hubOptions =>
{
hubOptions.EnableDetailedErrors = true;
hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(10);
hubOptions.HandshakeTimeout = TimeSpan.FromSeconds(5);
}).AddStackExchangeRedis(RedisConnection, options =>
{
options.ConnectionFactory = async writer =>
{
var config = new ConfigurationOptions
{
AbortOnConnectFail = false,
Ssl = true
};
var connection = await ConnectionMultiplexer.ConnectAsync(config, writer);
connection.ConnectionFailed += (_, e) =>
{
Console.WriteLine(e.Exception?.ToString());
Console.WriteLine("Connection to Redis failed.");
};

if (!connection.IsConnected)
{
Console.WriteLine("Did not connect to Redis.");
}

return connection;
};
});
}
else
{
builder.Services.AddSignalR(hubOptions =>

builder.Services.AddSignalR(hubOptions =>
{
hubOptions.EnableDetailedErrors = true;
hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(10);
hubOptions.HandshakeTimeout = TimeSpan.FromSeconds(5);
});
}

var app = builder.Build();


if (app.Environment.IsDevelopment())
{
app.UseCors("dev");
}
else
else if (app.Environment.IsProduction())
{
app.UseCors("prod");
}
Expand All @@ -133,6 +91,10 @@
app.UseAuthorization();
app.MapHealthChecks("/health");
app.MapHub<ChatHub>("/api/Message");
app.MapGet("/", async context =>
{
await context.Response.WriteAsync("Welcome to running ASP.NET Core on ECS");
});
app.Run();


Expand Down
11 changes: 0 additions & 11 deletions TalkWaveApi.WebSocket/Services/DatabaseContext.cs

This file was deleted.

Loading
Loading