Skip to content

Commit

Permalink
Read app credentials fom seed data. Fixes#284
Browse files Browse the repository at this point in the history
  • Loading branch information
julie authored and julie committed Mar 20, 2017
1 parent 1b71e73 commit a0dc685
Show file tree
Hide file tree
Showing 12 changed files with 201 additions and 8 deletions.
@@ -0,0 +1,51 @@
using Promact.Erp.DomainModel.DataRepository;
using Promact.Erp.DomainModel.Models;
using System;
using System.Threading.Tasks;

namespace Promact.Core.Repository.AppCredentialRepository
{
public class AppCredentialRepository : IAppCredentialRepository
{

private readonly IRepository<AppCredential> _appCredentialDataRepository;

public AppCredentialRepository(IRepository<AppCredential> appCredentialDataRepository)
{
_appCredentialDataRepository = appCredentialDataRepository;
}

/// <summary>
/// Get the app credentials of the given module - JJ
/// </summary>
/// <param name="module"></param>
/// <returns>object of AppCredential</returns>
public async Task<AppCredential> FetchAppCredentialByModule(string module)
{
return await _appCredentialDataRepository.FirstOrDefaultAsync(x => x.Module == module);
}

/// <summary>
/// Adds the app's credentials to the database - JJ
/// </summary>
/// <param name="appCredential"></param>
/// <returns></returns>
public async Task<int> AddAppCredentialAsync(AppCredential appCredential)
{
AppCredential credential = await FetchAppCredentialByModule(appCredential?.Module);
if (credential == null)
{
appCredential.CreatedOn = DateTime.UtcNow.Date;
_appCredentialDataRepository.Insert(appCredential);
}
else
{
credential.ClientId = appCredential.ClientId;
credential.ClientSecret = appCredential.ClientSecret;
_appCredentialDataRepository.Update(credential);
}
return await _appCredentialDataRepository.SaveChangesAsync();
}

}
}
@@ -0,0 +1,22 @@
using Promact.Erp.DomainModel.Models;
using System.Threading.Tasks;

namespace Promact.Core.Repository.AppCredentialRepository
{
public interface IAppCredentialRepository
{
/// <summary>
/// Get the app credentials of the given module - JJ
/// </summary>
/// <param name="module"></param>
/// <returns>object of AppCredential</returns>
Task<AppCredential> FetchAppCredentialByModule(string module);

/// <summary>
/// Adds the app's credentials to the database - JJ
/// </summary>
/// <param name="appCredential"></param>
/// <returns></returns>
Task<int> AddAppCredentialAsync(AppCredential appCredential);
}
}
Expand Up @@ -149,6 +149,8 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="AppCredentialRepository\AppCredentialRepository.cs" />
<Compile Include="AppCredentialRepository\IAppCredentialRepository.cs" />
<Compile Include="BaseRepository\RepositoryBase.cs" />
<Compile Include="AttachmentRepository\AttachmentRepository.cs" />
<Compile Include="AttachmentRepository\IAttachmentRepository.cs" />
Expand Down
@@ -0,0 +1,11 @@
using Promact.Erp.DomainModel.Models;
using System.Collections.Generic;


namespace Promact.Erp.DomainModel.ApplicationClass
{
public class SeedData
{
public List<AppCredential> AppCredential { get; set; }
}
}
Expand Up @@ -34,7 +34,8 @@ public PromactErpContext(DbConnection dbConnection) : base(dbConnection, true)
public DbSet<GroupEmailMapping> GroupEmailMapping { get; set; }
public DbSet<MailSetting> MailSetting { get; set; }
public DbSet<MailSettingMapping> MailSettingMapping { get; set; }

public DbSet<AppCredential> AppCredential { get; set; }

public static PromactErpContext Create()
{
return new PromactErpContext();
Expand Down
16 changes: 16 additions & 0 deletions Slack.Automation/Promact.Erp.DomainModel/Models/AppCredential.cs
@@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;

namespace Promact.Erp.DomainModel.Models
{
public class AppCredential : ModelBase
{
[Required]
public string Module { get; set; }

[Required]
public string ClientId { get; set; }

[Required]
public string ClientSecret { get; set; }
}
}
Expand Up @@ -133,6 +133,7 @@
<Compile Include="ApplicationClass\ProjectAc.cs" />
<Compile Include="ApplicationClass\ProjectUserDetailsApplicationClass.cs" />
<Compile Include="ApplicationClass\ScrumProjectDetails.cs" />
<Compile Include="ApplicationClass\SeedData.cs" />
<Compile Include="ApplicationClass\SlackRequestAndResponse\IncomingWebHookOAuthResponse.cs" />
<Compile Include="ApplicationClass\SlackRequestAndResponse\SlackChannelDetails.cs" />
<Compile Include="ApplicationClass\SlackRequestAndResponse\SlackChannelResponse.cs" />
Expand Down Expand Up @@ -160,6 +161,7 @@
<Compile Include="ApplicationClass\UserAdminBasicDetailsAC.cs" />
<Compile Include="ApplicationClass\UserEmailListAc.cs" />
<Compile Include="JSonConverterUtil\SlackChannelDetailsConverter.cs" />
<Compile Include="Models\AppCredential.cs" />
<Compile Include="Models\Group.cs" />
<Compile Include="Models\GroupEmailMapping.cs" />
<Compile Include="Models\MailSetting.cs" />
Expand Down
2 changes: 2 additions & 0 deletions Slack.Automation/Promact.Erp.Web/App_Start/AutofacConfig.cs
Expand Up @@ -5,6 +5,7 @@
using AutoMapper;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using Promact.Core.Repository.AppCredentialRepository;
using Promact.Core.Repository.AttachmentRepository;
using Promact.Core.Repository.AutoMapperConfig;
using Promact.Core.Repository.BotQuestionRepository;
Expand Down Expand Up @@ -73,6 +74,7 @@ public static IComponentContext RegisterDependancies()
builder.RegisterType<LeaveRequestRepository>().As<ILeaveRequestRepository>();
builder.RegisterType<SlackRepository>().As<ISlackRepository>();
builder.RegisterType<ScrumBotRepository>().As<IScrumBotRepository>();
builder.RegisterType<AppCredentialRepository>().As<IAppCredentialRepository>();
builder.RegisterType<ScrumSetUpRepository>().As<IScrumSetUpRepository>();
builder.RegisterType<StringConstantRepository>().As<IStringConstantRepository>();
builder.RegisterType<Client>().As<IClient>();
Expand Down
30 changes: 27 additions & 3 deletions Slack.Automation/Promact.Erp.Web/App_Start/Startup.Auth.cs
Expand Up @@ -13,7 +13,11 @@
using Microsoft.Owin.Security.Cookies;
using System.Threading.Tasks;
using System.Linq;
using Autofac.Extras.NLog;
using System.IO;
using System.Web.Hosting;
using Newtonsoft.Json;
using Promact.Erp.DomainModel.ApplicationClass;
using Promact.Core.Repository.AppCredentialRepository;

namespace Promact.Erp.Web
{
Expand All @@ -22,6 +26,7 @@ public partial class Startup
private IEnvironmentVariableRepository _environmentVariable;
private IStringConstantRepository _stringConstantRepository;
private IOAuthLoginRepository _oAuthLoginRepository;
private IAppCredentialRepository _appCredentialRepository;
private string _redirectUrl = null;
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864

Expand All @@ -31,16 +36,35 @@ public void ConfigureAuth(IAppBuilder app, IComponentContext context)
_oAuthLoginRepository = context.Resolve<IOAuthLoginRepository>();
_stringConstantRepository = context.Resolve<IStringConstantRepository>();
_redirectUrl = string.Format("{0}{1}", AppSettingUtil.PromactErpUrl, _stringConstantRepository.RedirectUrl);
_appCredentialRepository = context.Resolve<IAppCredentialRepository>();

#region Reads app credentials from json file

using (StreamReader str = new StreamReader(HostingEnvironment.MapPath("~/seedData.json")))
{
string text = str.ReadToEnd();
var seedData = JsonConvert.DeserializeObject<SeedData>(text);
foreach (var credential in seedData.AppCredential)
{
var status = _appCredentialRepository.AddAppCredentialAsync(credential).Result;
}
}

#endregion

// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(PromactErpContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = _stringConstantRepository.AuthenticationType
});


app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{

Expand Down Expand Up @@ -71,7 +95,7 @@ public void ConfigureAuth(IAppBuilder app, IComponentContext context)
var userInfoClient = new UserInfoClient(doc.UserInfoEndpoint);
var user = await userInfoClient.GetAsync(accessToken);
var tokenClient = new TokenClient(doc.TokenEndpoint, _environmentVariable.PromactOAuthClientId, _environmentVariable.PromactOAuthClientSecret);
var response = await tokenClient.RequestAuthorizationCodeAsync(tokenReceived.ProtocolMessage.Code, _redirectUrl);
var response = await tokenClient.RequestAuthorizationCodeAsync(tokenReceived.ProtocolMessage.Code, _redirectUrl);
var refreshToken = response.RefreshToken;
string userId = user.Claims.ToList().Single(x => x.Type == _stringConstantRepository.Sub).Value;
string email = user.Claims.ToList().Single(x => x.Type == _stringConstantRepository.Email).Value;
Expand All @@ -80,7 +104,7 @@ public void ConfigureAuth(IAppBuilder app, IComponentContext context)
AuthenticationFailed = authenticationFailed =>
{
authenticationFailed.Response.Redirect("/"); //redirect to home page.
authenticationFailed.HandleResponse();
authenticationFailed.HandleResponse();
return Task.FromResult(0);
},
}
Expand Down
@@ -0,0 +1,25 @@
{
"AppCredential": [
{
"Module": "scrum",
"ClientId": "234444.2532324",
"ClientSecret": "jkdfsh76278234"

},
{
"Module": "task",
"ClientId": "87980.324324789",
"ClientSecret": "lk87324jdf90978fd"
},
{
"Module": "leave",
"ClientId": "76896df789.435345",
"ClientSecret": "ewrret4356fg3456"
},
{
"Module": "redmine",
"ClientId": "56365dfg456546.5654rgth6urt",
"ClientSecret": "4567gfh56776trhrgh"
}
]
}
8 changes: 4 additions & 4 deletions Slack.Automation/Promact.Erp.Web/Promact.Erp.Web.csproj
Expand Up @@ -306,6 +306,7 @@
<Content Include="Content\fonts\line-icons.woff" />
<Content Include="app\shared\mock\mock.router.js.map" />
<Content Include="app\shared\mock\mock.activatedroute.js.map" />
<Content Include="CredentialSeedData\credentialSeedData.example.json" />
<None Include="NLog.xsd">
<SubType>Designer</SubType>
</None>
Expand Down Expand Up @@ -998,9 +999,11 @@
<Content Include="tsconfig.json" />
<Content Include="typings.json" />
<None Include="Properties\PublishProfiles\Local.pubxml" />
<Content Include="Views\Home\OAuthAppCredential.cshtml" />
</ItemGroup>
<ItemGroup>
<Folder Include="App_Data\" />
<Folder Include="Content\js\theme\" />
</ItemGroup>
<ItemGroup>
<Content Include="packages.config">
Expand Down Expand Up @@ -1162,10 +1165,7 @@
<Content Include="Scripts\respond\package.json" />
<Content Include="Scripts\respond\README.md" />
</ItemGroup>
<ItemGroup>
<Folder Include="App_Data\" />
<Folder Include="Content\js\theme\" />
</ItemGroup>
<ItemGroup />
<ItemGroup>
<Content Include="packages.config">
<SubType>Designer</SubType>
Expand Down
@@ -0,0 +1,37 @@

@model Promact.Erp.DomainModel.Models.AppCredential
@{
ViewBag.Title = "Enter App Credential";
Layout = null;
}

<h2>@ViewBag.Title.</h2>

@using (Html.BeginForm("OAuthAppCredential", "Home", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<h4>Change Password Form</h4>
<hr />
@Html.ValidationSummary("", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.ClientId, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.ClientId, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.ClientSecret, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.ClientSecret, new { @class = "form-control" })
</div>
</div>

<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Add" class="btn btn-default" />
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

0 comments on commit a0dc685

Please sign in to comment.