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

Feature/change membership service to adhere to known agent limitations #74

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
38 changes: 28 additions & 10 deletions src/frontend/site.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const adManagerRouter = require('./controller/adManager');
const cheerio = require('cheerio');
const express = require('express');
const router = express.Router();
const querystring = require('querystring');

// Global Timeline route
router.get('/', showGlobalTimeline);
Expand Down Expand Up @@ -71,7 +72,7 @@ function showGlobalTimeline(req, res) {
username: getJwtUser(req.cookies),
isAdManager: hasJwtRole(req.cookies, roles.AD_MANAGER),
baseData: baseRequestFactory.baseData,
membership: membership.data.membership
membership: membership.data

}, req);
res.render('index.njk', data)
Expand Down Expand Up @@ -109,7 +110,7 @@ function showUsers(req, res) {
username: getJwtUser(req.cookies),
isAdManager: hasJwtRole(req.cookies, roles.AD_MANAGER),
baseData: baseRequestFactory.baseData,
membership: membership.data.membership
membership: membership.data

}, req);
res.render('users.njk', data);
Expand All @@ -130,7 +131,7 @@ function showPersonalTimeline(req, res) {
username: getJwtUser(req.cookies),
isAdManager: hasJwtRole(req.cookies, roles.AD_MANAGER),
baseData: baseRequestFactory.baseData,
membership: membership.data.membership
membership: membership.data
}, req);
res.render('index.njk', data);
}, (err) => displayError(err, res))
Expand All @@ -154,7 +155,7 @@ function showUserProfile(req, res) {
isAdManager: hasJwtRole(req.cookies, roles.AD_MANAGER),
bio: bioText,
baseData: baseRequestFactory.baseData,
membership: membership.data.membership
membership: membership.data
}, req);

res.render('profile.njk', data);
Expand Down Expand Up @@ -189,7 +190,7 @@ function showMembership(req, res) {
username: getJwtUser(req.cookies),
isAdManager: hasJwtRole(req.cookies, roles.AD_MANAGER),
baseData: baseRequestFactory.baseData,
membership: membership.data.membership
membership: membership.data
}, req);

res.render('membership.njk', data);
Expand Down Expand Up @@ -373,11 +374,28 @@ function unlikePost(req, res) {
}

function postMembership(req, res) {
const membership = {userid: getJwtUserId(req.cookies), membership: req.body.membershipText};
fetchUsingDeploymentBase(req, () => req.MEMBERSHIP_SERVICE_API.post('/', membership)).then((response) => {
res.redirect(extendURL(`/user/${getJwtUser(req.cookies)}`));
}, (error) => res.status(statusCodeForError(error)).render('error.njk', handleError(error)));

const formData = {
membership: req.body.membershipText,
};
fetchUsingDeploymentBase(req, () =>
req.MEMBERSHIP_SERVICE_API.post(
`/add/${getJwtUserId(req.cookies)}`,
querystring.stringify(formData),
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}
)
).then(
(response) => {
res.redirect(extendURL(`/user/${getJwtUser(req.cookies)}`));
},
(error) =>
res
.status(statusCodeForError(error))
.render("error.njk", handleError(error))
);
}

function postBio(req, res) {
Expand Down
5 changes: 3 additions & 2 deletions src/frontend/views/membership.njk
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{#
{#
Copyright 2023 Dynatrace LLC
Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -48,6 +48,7 @@ limitations under the License.
</ul>
</div>
</div>
</div>
</div>

<form method="post">
Expand All @@ -66,6 +67,6 @@ limitations under the License.
Update membership plan
</button>
</div>
</post>
</form>
</div>
{% endblock %}
137 changes: 104 additions & 33 deletions src/membership-service/Controllers/MembershipController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// <copyright company="Dynatrace LLC">
// Copyright 2023 Dynatrace LLC
// Copyright 2024 Dynatrace LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -14,52 +14,123 @@
// limitations under the License.
// </copyright>

using System;
using System.Data;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MembershipService.Persistence;
using MySqlConnector;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MySql.Data.MySqlClient;

namespace MembershipService.Controllers;

[ApiController]
[Route("[controller]-service")]
public class MembershipController : ControllerBase
namespace MembershipService.Controllers
{

[ApiController]
[Route("[controller]-service")]
public class MembershipController : ControllerBase
{
private readonly string _connectionString;
private readonly ILogger<MembershipController> _logger;
private readonly MembershipDbService _membershipDbService;

public MembershipController(ILogger<MembershipController> logger, MembershipDbService membershipDbService)
public MembershipController(IConfiguration configuration, ILogger<MembershipController> logger)
{
_logger = logger;
_membershipDbService = membershipDbService;
string dbPwd = Environment.GetEnvironmentVariable("MARIADB_PASSWORD");
string dbHost = Environment.GetEnvironmentVariable("MARIADB_SERVICE");
_connectionString = $"Server={dbHost};Port=3306;Database=memberships;user=root;password={dbPwd}";
_logger = logger;
}

[HttpGet("{userid}", Name = "FindOne")]
public async Task<ActionResult<MembershipEntity>> Get(int userid)
[HttpGet("{userid}")]
public async Task<IActionResult> GetMembershipStatus(string userid)
{
var result = await _membershipDbService.FindOne(userid);
if (result == default)
using (var connection = new MySqlConnection(_connectionString))
{
result = new MembershipEntity(userid, "FREE");
_logger.LogInformation($"GET requested => userid: {userid}");

await connection.OpenAsync();

string selectQuery = "SELECT membership FROM membership WHERE userid = " + userid;

W3D3 marked this conversation as resolved.
Show resolved Hide resolved
_logger.LogInformation($"Executing query: {selectQuery}");
W3D3 marked this conversation as resolved.
Show resolved Hide resolved

using (var selectCmd = new MySqlCommand(selectQuery, connection))
{
try
{
object result = await selectCmd.ExecuteScalarAsync();
if (result != null)
{
_logger.LogInformation($@"Membership status of userid {userid}: {result}");
return Ok(result);
}
else
{
_logger.LogInformation($"Membership status of userid {userid} not found");

// If no membership entry exists, insert a new one
string insertQuery = $@"INSERT INTO membership (userid, membership) VALUES ({userid}, ""FREE"")";
using (var insertCmd = new MySqlCommand(insertQuery, connection))
{
int rowsAffected = await insertCmd.ExecuteNonQueryAsync();
if (rowsAffected > 0)
{
_logger.LogInformation($"Membership status for userid {userid} inserted as 'FREE'");
return Ok("FREE");
}
else
{
_logger.LogInformation($"Membership status for userid {userid} could not be inserted");
return StatusCode((int)HttpStatusCode.InternalServerError);
}
}
}
}
catch (Exception ex)
{
return StatusCode((int)HttpStatusCode.InternalServerError, ex.Message);
}
}
}
return Ok(result);
}

[HttpPost]
public async Task<ActionResult<MembershipEntity>> Insert(MembershipEntity dto)

[HttpPost("add/{userid}")]
public async Task<IActionResult> SetMembershipStatus(string userid, [FromForm(Name = "membership")] string membership)
{
try
using (var connection = new MySqlConnection(_connectionString))
{
var id = await _membershipDbService.Insert(dto);
if (id != null)
return id;
else
return BadRequest();
}
catch(MySqlException e)
{
_logger.LogError(0, e, "Error while inserting membership");
return StatusCode(500);
await connection.OpenAsync();

_logger.LogInformation($"INSERT requested => userid: {userid}, membership: {membership}");

string query = "INSERT INTO membership (userid, membership) VALUES (" + userid + ",\"" + membership + "\") ON DUPLICATE KEY UPDATE membership = \"" + membership + "\"";

_logger.LogInformation($"Executing query: {query}");


using (var cmd = new MySqlCommand(query, connection))
{
try
{
int rowsAffected = await cmd.ExecuteNonQueryAsync();
if (rowsAffected > 0)
{
_logger.LogInformation($"Membership status for userid {userid} updated to {membership}");
return Ok();
}
else
{
_logger.LogInformation($"Membership status for userid {userid} could not be updated");
return StatusCode((int)HttpStatusCode.InternalServerError);
}
}
catch (Exception ex)
{
return StatusCode((int)HttpStatusCode.InternalServerError, ex.Message);
}
}
}
}
}
}
}
27 changes: 0 additions & 27 deletions src/membership-service/Membership.cs

This file was deleted.

8 changes: 5 additions & 3 deletions src/membership-service/MembershipService.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.1" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.20" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="5.0.0" />
<PackageReference Include="MySql.Data" Version="8.0.28" />
</ItemGroup>

</Project>
29 changes: 0 additions & 29 deletions src/membership-service/Persistence/DbInitializer.cs

This file was deleted.

36 changes: 0 additions & 36 deletions src/membership-service/Persistence/MariaDbContext.cs

This file was deleted.

Loading
Loading