OAuth OK!

This commit is contained in:
Paul Schneider 2016-06-12 01:32:51 +02:00
commit 567e4a6635
382 changed files with 52478 additions and 7572 deletions

View file

@ -3,8 +3,6 @@ using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.WebEncoders;
using System;
using System.IO;
using Yavsc.Auth;
namespace OAuth.AspNet.AuthServer

View file

@ -1,4 +1,3 @@
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Http;
namespace OAuth.AspNet.AuthServer

View file

@ -62,6 +62,10 @@ namespace OAuth.AspNet.AuthServer
Parameters = parameters,
};
}
else
{
throw new ArgumentException("No grant type found in the request");
}
}
/// <summary>

View file

@ -33,6 +33,7 @@ namespace Yavsc.Auth
Scope.Add("openid");
Scope.Add("profile");
Scope.Add("email");
}
/// <summary>
@ -40,5 +41,6 @@ namespace Yavsc.Auth
/// </summary>
public string AccessType { get; set; }
}
}

View file

@ -4,17 +4,14 @@ namespace Yavsc
public static class Constants
{
public const string AccessDeniedPath = "~/signin";
public const string AuthorizePath = "~/authorize";
public const string TokenPath = "~/token";
public const string AccessDeniedPath = "~/signin", AuthorizePath = "~/authorize",
TokenPath = "~/token", LocalLoginPath = "~/signin", LoginPath = "~/signin",
ExternalLoginPath = "~/extsign", LogoutPath = "~/signout", MePath = "~/api/Me";
public const string LocalLoginPath = "~/login";
public const string LoginPath = "~/signin";
public const string ExternalLoginPath = "~/extsign";
public const string LogoutPath = "~/signout";
public const string MePath = "~/api/Me";
public const string ApplicationAuthenticationSheme = "ServerCookie";
public const string
ApplicationAuthenticationSheme = "ServerCookie",
ExternalAuthenticationSheme= "ExternalCookie";
public static readonly Scope[] SiteScopes = { 
new Scope { Id = "profile", Description = "Your profile informations" },  
new Scope { Id = "book" , Description ="Your booking interface"},  
@ -26,32 +23,26 @@ namespace Yavsc
new Scope { Id = "frontoffice" , Description ="Your front office interface" }
};
public const string CompanyInfoUrl = " https://societeinfo.com/app/rest/api/v1/company/json?registration_number={0}&key={1}";
public const string DefaultFactor = "Default";
public const string MobileAppFactor = "Google.clood";
public const string EMailFactor = "Email";
public const string SMSFactor = "Phone";
public const string AdminGroupName = "Administrator";
public const string BlogModeratorGroupName = "Moderator";
public const string FrontOfficeGroupName = "FrontOffice";
public const string UserBillsFilesDir= "Bills";
public const string UserFilesDir = "UserFiles";
public const string GCMNotificationUrl = "https://gcm-http.googleapis.com/gcm/send";
public const string
CompanyInfoUrl = " https://societeinfo.com/app/rest/api/v1/company/json?registration_number={0}&key={1}",
DefaultFactor = "Default",
MobileAppFactor = "Google.clood",
EMailFactor = "Email",
SMSFactor = "Phone",
AdminGroupName = "Administrator",
BlogModeratorGroupName = "Moderator",
FrontOfficeGroupName = "FrontOffice",
UserBillsFilesDir= "Bills",
UserFilesDir = "UserFiles",
GCMNotificationUrl = "https://gcm-http.googleapis.com/gcm/send",
KeyProtectorPurpose = "OAuth.AspNet.AuthServer";
private static readonly string[] GoogleScopes = { "openid", "profile", "email" };
public static readonly string[] GoogleCalendarScopes =
{ "openid", "profile", "email", "https://www.googleapis.com/auth/calendar" };
public const string ApplicationName = "Yavsc";
public const string Issuer = "https://dev.pschneider.fr";
public const string CompanyClaimType = "https://schemas.pschneider.fr/identity/claims/Company";
public const string UserNameRegExp = @"^[a-zA-Z][a-zA-Z0-9 ]*$";
public const string KeyProtectorPurpose = "OAuth.AspNet.AuthServer";
public const string ApplicationName = "Yavsc",
Issuer = "https://dev.pschneider.fr",
CompanyClaimType = "https://schemas.pschneider.fr/identity/claims/Company",
UserNameRegExp = @"^[a-zA-Z][a-zA-Z0-9 ]*$";
}
}

View file

@ -11,11 +11,10 @@ using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using Microsoft.AspNet.Http;
using Yavsc.Extensions;
using Yavsc.Models;
using Yavsc.Services;
using Yavsc.ViewModels.Account;
using Microsoft.AspNet.Http.Authentication;
using Yavsc.Helpers;
namespace Yavsc.Controllers
{
@ -50,6 +49,7 @@ namespace Yavsc.Controllers
_smtpSettings = smtpSettings.Value;
_twilioSettings = twilioSettings.Value;
_logger = loggerFactory.CreateLogger<AccountController>();
}
[HttpGet(Constants.LoginPath)]
@ -127,6 +127,7 @@ namespace Yavsc.Controllers
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return Redirect(model.ReturnUrl);

View file

@ -1,122 +0,0 @@
using System;
using System.Linq;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using Yavsc.Models;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class ApplicationController : Controller
{
private ApplicationDbContext _context;
public ApplicationController(ApplicationDbContext context)
{
_context = context;
}
// GET: Application
public IActionResult Index()
{
return View(_context.Applications.ToList());
}
// GET: Application/Details/5
public IActionResult Details(string id)
{
if (id == null)
{
return HttpNotFound();
}
Application application = _context.Applications.Single(m => m.ApplicationID == id);
if (application == null)
{
return HttpNotFound();
}
return View(application);
}
// GET: Application/Create
public IActionResult Create()
{
return View();
}
// POST: Application/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Application application)
{
if (ModelState.IsValid)
{
application.ApplicationID = Guid.NewGuid().ToString();
_context.Applications.Add(application);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(application);
}
// GET: Application/Edit/5
public IActionResult Edit(string id)
{
if (id == null)
{
return HttpNotFound();
}
Application application = _context.Applications.Single(m => m.ApplicationID == id);
if (application == null)
{
return HttpNotFound();
}
return View(application);
}
// POST: Application/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(Application application)
{
if (ModelState.IsValid)
{
_context.Update(application);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(application);
}
// GET: Application/Delete/5
[ActionName("Delete")]
public IActionResult Delete(string id)
{
if (id == null)
{
return HttpNotFound();
}
Application application = _context.Applications.Single(m => m.ApplicationID == id);
if (application == null)
{
return HttpNotFound();
}
return View(application);
}
// POST: Application/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(string id)
{
Application application = _context.Applications.Single(m => m.ApplicationID == id);
_context.Applications.Remove(application);
_context.SaveChanges();
return RedirectToAction("Index");
}
}
}

View file

@ -0,0 +1,137 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Auth;
namespace Yavsc.Controllers
{
public class ClientController : Controller
{
private ApplicationDbContext _context;
public ClientController(ApplicationDbContext context)
{
_context = context;
}
// GET: Client
public async Task<IActionResult> Index()
{
return View(await _context.Applications.ToListAsync());
}
// GET: Client/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
return HttpNotFound();
}
Client client = await _context.Applications.SingleAsync(m => m.Id == id);
if (client == null)
{
return HttpNotFound();
}
return View(client);
}
// GET: Client/Create
public IActionResult Create()
{
return View();
}
// POST: Client/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Client client)
{
if (ModelState.IsValid)
{
client.Id = Guid.NewGuid().ToString();
_context.Applications.Add(client);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
SetAppTypesInputValues();
return View(client);
}
private void SetAppTypesInputValues()
{
ViewData["Type"] =
new SelectListItem[] { 
new SelectListItem {
Text = ApplicationTypes.JavaScript.ToString(),
Value = ((int) ApplicationTypes.JavaScript).ToString() },
new SelectListItem {
Text = ApplicationTypes.NativeConfidential.ToString(),
Value = ((int) ApplicationTypes.NativeConfidential).ToString()
}
};
}
// GET: Client/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null)
{
return HttpNotFound();
}
Client client = await _context.Applications.SingleAsync(m => m.Id == id);
if (client == null)
{
return HttpNotFound();
}
SetAppTypesInputValues();
return View(client);
}
// POST: Client/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Client client)
{
if (ModelState.IsValid)
{
_context.Update(client);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(client);
}
// GET: Client/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return HttpNotFound();
}
Client client = await _context.Applications.SingleAsync(m => m.Id == id);
if (client == null)
{
return HttpNotFound();
}
return View(client);
}
// POST: Client/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
Client client = await _context.Applications.SingleAsync(m => m.Id == id);
_context.Applications.Remove(client);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View file

@ -6,6 +6,7 @@ using Microsoft.AspNet.Identity;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Logging;
using Yavsc.Models.Booking;
using Yavsc.Helpers;
namespace Yavsc.Controllers
{

View file

@ -1,4 +1,5 @@
using System.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
@ -9,8 +10,10 @@ using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using Microsoft.Extensions.Primitives;
using OAuth.AspNet.AuthServer;
using Yavsc.Models;
using Yavsc.Models.Auth;
namespace Yavsc.Controllers
{
@ -109,7 +112,7 @@ namespace Yavsc.Controllers
return Ok(claims);
}
[HttpGet(Constants.AuthorizePath)]
[HttpGet(Constants.AuthorizePath),HttpPost(Constants.AuthorizePath)]
public async Task<ActionResult> Authorize()
{
if (Response.StatusCode != 200)
@ -118,12 +121,13 @@ namespace Yavsc.Controllers
}
AuthenticationManager authentication = Request.HttpContext.Authentication;
var appAuthSheme = Startup.IdentityAppOptions.Cookies.ApplicationCookieAuthenticationScheme;
ClaimsPrincipal principal = await authentication.AuthenticateAsync(Constants.ApplicationAuthenticationSheme);
ClaimsPrincipal principal = await authentication.AuthenticateAsync(appAuthSheme);
if (principal == null)
{
await authentication.ChallengeAsync(Constants.ApplicationAuthenticationSheme);
await authentication.ChallengeAsync(appAuthSheme);
if (Response.StatusCode == 200)
return new HttpUnauthorizedResult();
@ -132,15 +136,36 @@ namespace Yavsc.Controllers
}
string[] scopes = { };
string redirect_uri = null;
string client_id = null;
string state = null;
IDictionary<string,StringValues> queryStringComponents = null;
if (Request.QueryString.HasValue)
{
var queryStringComponents = QueryHelpers.ParseQuery(Request.QueryString.Value);
queryStringComponents = QueryHelpers.ParseQuery(Request.QueryString.Value);
if (queryStringComponents.ContainsKey("scope"))
scopes = queryStringComponents["scope"];
if (queryStringComponents.ContainsKey("redirect_uri"))
redirect_uri = queryStringComponents["redirect_uri"];
if (queryStringComponents.ContainsKey("client_id"))
client_id = queryStringComponents["client_id"];
if (queryStringComponents.ContainsKey("state"))
state = queryStringComponents["state"];
}
var model = new AuthorisationView {
Scopes = Constants.SiteScopes.Where(s=> scopes.Contains(s.Id)).ToArray(),
RedirectUrl = redirect_uri,
Message = "Welcome.",
QueryStringComponents = queryStringComponents,
ClientId = client_id,
State = state,
ResponseType="code"
} ;
if (Request.Method == "POST")
{
if (!string.IsNullOrEmpty(Request.Form["submit.Grant"]))
@ -153,21 +178,19 @@ namespace Yavsc.Controllers
{
primaryIdentity.AddClaim(new Claim("urn:oauth:scope", scope));
}
_logger.LogWarning("Logging user {principal} against {OAuthDefaults.AuthenticationType}");
await authentication.SignInAsync(OAuthDefaults.AuthenticationType, principal);
}
if (!string.IsNullOrEmpty(Request.Form["submit.Login"]))
{
await authentication.SignOutAsync(Constants.ApplicationAuthenticationSheme);
await authentication.ChallengeAsync(Constants.ApplicationAuthenticationSheme);
await authentication.SignOutAsync(appAuthSheme);
await authentication.ChallengeAsync(appAuthSheme);
return new HttpUnauthorizedResult();
}
}
return View(new AuthorisationView { Scopes = scopes } );
return View(model);
}
}

View file

@ -4,7 +4,7 @@ using Owin;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
#if OWIN
namespace Yavsc
{
using Microsoft.AspNet.SignalR;
@ -43,4 +43,3 @@ namespace Yavsc
}
}
}
#endif

View file

@ -18,6 +18,7 @@
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using Yavsc.Helpers;
using Yavsc.Model;
using Yavsc.Models.Google;

View file

@ -4,7 +4,7 @@ using System.Collections.Generic;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication;
namespace Yavsc.Extensions {
namespace Yavsc.Helpers {
public static class HttpContextExtensions {
public static IEnumerable<AuthenticationDescription> GetExternalProviders(this HttpContext context) {
if (context == null) {
@ -26,4 +26,6 @@ namespace Yavsc.Extensions {
select description).Any();
}
}
}

View file

@ -4,7 +4,7 @@ using System.Linq;
using Microsoft.AspNet.Mvc.Rendering;
using Yavsc.Models;
namespace Yavsc {
namespace Yavsc.Helpers {
public static class ListItemHelpers {
public static List<SelectListItem> ActivityItems(

View file

@ -0,0 +1,18 @@
using System;
using System.Security.Cryptography;
namespace Yavsc.Helpers {
public class Helper
{
public static string GetHash(string input)
{
HashAlgorithm hashAlgorithm = new SHA256CryptoServiceProvider();
byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(input);
byte[] byteHash = hashAlgorithm.ComputeHash(byteValue);
return Convert.ToBase64String(byteHash);
}
}
}

View file

@ -23,7 +23,7 @@ using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace Yavsc.Model
namespace Yavsc.Helpers
{
/// <summary>
/// Simple json post method.

View file

@ -0,0 +1,694 @@
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using Yavsc.Models;
namespace Yavsc.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20160610153353_client")]
partial class client
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348");
modelBuilder.Entity("GoogleCloudMobileDeclaration", b =>
{
b.Property<string>("RegistrationId");
b.Property<string>("DeviceOwnerId");
b.Property<string>("Name");
b.HasKey("RegistrationId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("Yavsc.Location", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Address")
.IsRequired();
b.Property<double>("Latitude");
b.Property<double>("Longitude");
b.HasKey("Id");
});
modelBuilder.Entity("Yavsc.Models.AccountBalance", b =>
{
b.Property<string>("UserId");
b.Property<long>("ContactCredits");
b.Property<decimal>("Credits");
b.HasKey("UserId");
});
modelBuilder.Entity("Yavsc.Models.Activity", b =>
{
b.Property<string>("Code")
.HasAnnotation("MaxLength", 512);
b.Property<string>("ActorDenomination");
b.Property<string>("Description");
b.Property<string>("ModeratorGroupName");
b.Property<string>("Name")
.IsRequired()
.HasAnnotation("MaxLength", 512);
b.Property<string>("Photo");
b.HasKey("Code");
});
modelBuilder.Entity("Yavsc.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("DedicatedGoogleCalendar");
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<long?>("PostalAddressId");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("Yavsc.Models.Auth.Client", b =>
{
b.Property<string>("Id");
b.Property<bool>("Active");
b.Property<string>("AllowedOrigin")
.HasAnnotation("MaxLength", 100);
b.Property<string>("DisplayName");
b.Property<string>("LogoutRedirectUri");
b.Property<string>("RedirectUri");
b.Property<int>("RefreshTokenLifeTime");
b.Property<string>("Secret");
b.Property<int>("Type");
b.HasKey("Id");
});
modelBuilder.Entity("Yavsc.Models.Auth.RefreshToken", b =>
{
b.Property<string>("Id");
b.Property<string>("ClientId")
.IsRequired()
.HasAnnotation("MaxLength", 50);
b.Property<DateTime>("ExpiresUtc");
b.Property<DateTime>("IssuedUtc");
b.Property<string>("ProtectedTicket")
.IsRequired();
b.Property<string>("Subject")
.IsRequired()
.HasAnnotation("MaxLength", 50);
b.HasKey("Id");
});
modelBuilder.Entity("Yavsc.Models.BalanceImpact", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("BalanceId")
.IsRequired();
b.Property<DateTime>("ExecDate");
b.Property<decimal>("Impact");
b.Property<string>("Reason")
.IsRequired();
b.HasKey("Id");
});
modelBuilder.Entity("Yavsc.Models.BaseProduct", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Description");
b.Property<string>("Name");
b.Property<bool>("Public");
b.HasKey("Id");
});
modelBuilder.Entity("Yavsc.Models.Blog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("AuthorId")
.IsRequired();
b.Property<string>("bcontent");
b.Property<DateTime>("modified");
b.Property<string>("photo");
b.Property<DateTime>("posted");
b.Property<int>("rate");
b.Property<string>("title");
b.Property<bool>("visible");
b.HasKey("Id");
});
modelBuilder.Entity("Yavsc.Models.Booking.BookQuery", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClientId")
.IsRequired();
b.Property<DateTime>("CreationDate")
.ValueGeneratedOnAdd()
.HasAnnotation("Relational:GeneratedValueSql", "LOCALTIMESTAMP");
b.Property<DateTime>("EventDate");
b.Property<int>("Lag");
b.Property<long>("LocationId");
b.Property<string>("PerformerId")
.IsRequired();
b.Property<decimal?>("Previsional");
b.Property<DateTime?>("ValidationDate");
b.HasKey("Id");
});
modelBuilder.Entity("Yavsc.Models.Circle", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.Property<string>("OwnerId");
b.HasKey("Id");
});
modelBuilder.Entity("Yavsc.Models.CircleMember", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long?>("CircleId")
.IsRequired();
b.Property<string>("MemberId")
.IsRequired();
b.HasKey("Id");
});
modelBuilder.Entity("Yavsc.Models.Command", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClientId")
.IsRequired();
b.Property<DateTime>("CreationDate");
b.Property<int>("Lag");
b.Property<string>("PerformerId")
.IsRequired();
b.Property<decimal?>("Previsional");
b.Property<DateTime?>("ValidationDate");
b.HasKey("Id");
});
modelBuilder.Entity("Yavsc.Models.CommandLine", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long?>("ArticleId");
b.Property<long?>("BookQueryId");
b.Property<long?>("CommandId");
b.Property<string>("Comment");
b.Property<int>("Count");
b.Property<long?>("EstimateId");
b.Property<decimal>("UnitaryCost");
b.HasKey("Id");
});
modelBuilder.Entity("Yavsc.Models.Contact", b =>
{
b.Property<string>("OwnerId");
b.Property<string>("UserId");
b.HasKey("OwnerId", "UserId");
});
modelBuilder.Entity("Yavsc.Models.Estimate", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("AttachedFilesString");
b.Property<string>("AttachedGraphicsString");
b.Property<long?>("CommandId");
b.Property<string>("Description");
b.Property<int?>("Status");
b.Property<string>("Title");
b.HasKey("Id");
});
modelBuilder.Entity("Yavsc.Models.OAuth.OAuth2Tokens", b =>
{
b.Property<string>("UserId");
b.Property<string>("AccessToken");
b.Property<DateTime>("Expiration");
b.Property<string>("ExpiresIn");
b.Property<string>("RefreshToken");
b.Property<string>("TokenType");
b.HasKey("UserId");
});
modelBuilder.Entity("Yavsc.Models.PerformerProfile", b =>
{
b.Property<string>("PerfomerId");
b.Property<bool>("AcceptGeoLocalisation");
b.Property<bool>("AcceptNotifications");
b.Property<bool>("AcceptPublicContact");
b.Property<bool>("Active");
b.Property<string>("ActivityCode")
.IsRequired();
b.Property<int?>("MaxDailyCost");
b.Property<int?>("MinDailyCost");
b.Property<long?>("OfferId");
b.Property<long>("OrganisationAddressId");
b.Property<int>("Rate");
b.Property<string>("SIREN")
.IsRequired()
.HasAnnotation("MaxLength", 14);
b.Property<string>("WebSite");
b.HasKey("PerfomerId");
});
modelBuilder.Entity("Yavsc.Models.Service", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("Billing");
b.Property<string>("ContextId");
b.Property<string>("Description");
b.Property<string>("Name");
b.Property<decimal?>("Pricing");
b.Property<bool>("Public");
b.HasKey("Id");
});
modelBuilder.Entity("Yavsc.Models.Skill", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.Property<int>("Rate");
b.HasKey("Id");
});
modelBuilder.Entity("GoogleCloudMobileDeclaration", b =>
{
b.HasOne("Yavsc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("DeviceOwnerId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("Yavsc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("Yavsc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("Yavsc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Yavsc.Models.AccountBalance", b =>
{
b.HasOne("Yavsc.Models.ApplicationUser")
.WithOne()
.HasForeignKey("Yavsc.Models.AccountBalance", "UserId");
});
modelBuilder.Entity("Yavsc.Models.ApplicationUser", b =>
{
b.HasOne("Yavsc.Location")
.WithMany()
.HasForeignKey("PostalAddressId");
});
modelBuilder.Entity("Yavsc.Models.BalanceImpact", b =>
{
b.HasOne("Yavsc.Models.AccountBalance")
.WithMany()
.HasForeignKey("BalanceId");
});
modelBuilder.Entity("Yavsc.Models.Blog", b =>
{
b.HasOne("Yavsc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("AuthorId");
});
modelBuilder.Entity("Yavsc.Models.Booking.BookQuery", b =>
{
b.HasOne("Yavsc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("ClientId");
b.HasOne("Yavsc.Location")
.WithMany()
.HasForeignKey("LocationId");
b.HasOne("Yavsc.Models.PerformerProfile")
.WithMany()
.HasForeignKey("PerformerId");
});
modelBuilder.Entity("Yavsc.Models.Circle", b =>
{
b.HasOne("Yavsc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("OwnerId");
});
modelBuilder.Entity("Yavsc.Models.CircleMember", b =>
{
b.HasOne("Yavsc.Models.Circle")
.WithMany()
.HasForeignKey("CircleId");
b.HasOne("Yavsc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("MemberId");
});
modelBuilder.Entity("Yavsc.Models.Command", b =>
{
b.HasOne("Yavsc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("ClientId");
b.HasOne("Yavsc.Models.PerformerProfile")
.WithMany()
.HasForeignKey("PerformerId");
});
modelBuilder.Entity("Yavsc.Models.CommandLine", b =>
{
b.HasOne("Yavsc.Models.BaseProduct")
.WithMany()
.HasForeignKey("ArticleId");
b.HasOne("Yavsc.Models.Booking.BookQuery")
.WithMany()
.HasForeignKey("BookQueryId");
b.HasOne("Yavsc.Models.Command")
.WithMany()
.HasForeignKey("CommandId");
b.HasOne("Yavsc.Models.Estimate")
.WithMany()
.HasForeignKey("EstimateId");
});
modelBuilder.Entity("Yavsc.Models.Contact", b =>
{
b.HasOne("Yavsc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("OwnerId");
});
modelBuilder.Entity("Yavsc.Models.Estimate", b =>
{
b.HasOne("Yavsc.Models.Command")
.WithMany()
.HasForeignKey("CommandId");
});
modelBuilder.Entity("Yavsc.Models.PerformerProfile", b =>
{
b.HasOne("Yavsc.Models.Activity")
.WithMany()
.HasForeignKey("ActivityCode");
b.HasOne("Yavsc.Models.Service")
.WithMany()
.HasForeignKey("OfferId");
b.HasOne("Yavsc.Location")
.WithMany()
.HasForeignKey("OrganisationAddressId");
b.HasOne("Yavsc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("PerfomerId");
});
modelBuilder.Entity("Yavsc.Models.Service", b =>
{
b.HasOne("Yavsc.Models.Activity")
.WithMany()
.HasForeignKey("ContextId");
});
}
}
}

View file

@ -0,0 +1,395 @@
using System;
using System.Collections.Generic;
using Microsoft.Data.Entity.Migrations;
namespace Yavsc.Migrations
{
public partial class client : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_AccountBalance_ApplicationUser_UserId", table: "AccountBalance");
migrationBuilder.DropForeignKey(name: "FK_BalanceImpact_AccountBalance_BalanceId", table: "BalanceImpact");
migrationBuilder.DropForeignKey(name: "FK_Blog_ApplicationUser_AuthorId", table: "Blog");
migrationBuilder.DropForeignKey(name: "FK_BookQuery_ApplicationUser_ClientId", table: "BookQuery");
migrationBuilder.DropForeignKey(name: "FK_BookQuery_Location_LocationId", table: "BookQuery");
migrationBuilder.DropForeignKey(name: "FK_BookQuery_PerformerProfile_PerformerId", table: "BookQuery");
migrationBuilder.DropForeignKey(name: "FK_CircleMember_Circle_CircleId", table: "CircleMember");
migrationBuilder.DropForeignKey(name: "FK_CircleMember_ApplicationUser_MemberId", table: "CircleMember");
migrationBuilder.DropForeignKey(name: "FK_Command_ApplicationUser_ClientId", table: "Command");
migrationBuilder.DropForeignKey(name: "FK_Command_PerformerProfile_PerformerId", table: "Command");
migrationBuilder.DropForeignKey(name: "FK_Contact_ApplicationUser_OwnerId", table: "Contact");
migrationBuilder.DropForeignKey(name: "FK_PerformerProfile_Activity_ActivityCode", table: "PerformerProfile");
migrationBuilder.DropForeignKey(name: "FK_PerformerProfile_Location_OrganisationAddressId", table: "PerformerProfile");
migrationBuilder.DropForeignKey(name: "FK_PerformerProfile_ApplicationUser_PerfomerId", table: "PerformerProfile");
migrationBuilder.DropColumn(name: "GoogleRegId", table: "AspNetUsers");
migrationBuilder.DropTable("Application");
migrationBuilder.CreateTable(
name: "GoogleCloudMobileDeclaration",
columns: table => new
{
RegistrationId = table.Column<string>(nullable: false),
DeviceOwnerId = table.Column<string>(nullable: true),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_GoogleCloudMobileDeclaration", x => x.RegistrationId);
table.ForeignKey(
name: "FK_GoogleCloudMobileDeclaration_ApplicationUser_DeviceOwnerId",
column: x => x.DeviceOwnerId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Client",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Active = table.Column<bool>(nullable: false),
AllowedOrigin = table.Column<string>(nullable: true),
DisplayName = table.Column<string>(nullable: true),
LogoutRedirectUri = table.Column<string>(nullable: true),
RedirectUri = table.Column<string>(nullable: true),
RefreshTokenLifeTime = table.Column<int>(nullable: false),
Secret = table.Column<string>(nullable: true),
Type = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Client", x => x.Id);
});
migrationBuilder.CreateTable(
name: "RefreshToken",
columns: table => new
{
Id = table.Column<string>(nullable: false),
ClientId = table.Column<string>(nullable: false),
ExpiresUtc = table.Column<DateTime>(nullable: false),
IssuedUtc = table.Column<DateTime>(nullable: false),
ProtectedTicket = table.Column<string>(nullable: false),
Subject = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_RefreshToken", x => x.Id);
});
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_AccountBalance_ApplicationUser_UserId",
table: "AccountBalance",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_BalanceImpact_AccountBalance_BalanceId",
table: "BalanceImpact",
column: "BalanceId",
principalTable: "AccountBalance",
principalColumn: "UserId",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Blog_ApplicationUser_AuthorId",
table: "Blog",
column: "AuthorId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_BookQuery_ApplicationUser_ClientId",
table: "BookQuery",
column: "ClientId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_BookQuery_Location_LocationId",
table: "BookQuery",
column: "LocationId",
principalTable: "Location",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_BookQuery_PerformerProfile_PerformerId",
table: "BookQuery",
column: "PerformerId",
principalTable: "PerformerProfile",
principalColumn: "PerfomerId",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_CircleMember_Circle_CircleId",
table: "CircleMember",
column: "CircleId",
principalTable: "Circle",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_CircleMember_ApplicationUser_MemberId",
table: "CircleMember",
column: "MemberId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Command_ApplicationUser_ClientId",
table: "Command",
column: "ClientId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Command_PerformerProfile_PerformerId",
table: "Command",
column: "PerformerId",
principalTable: "PerformerProfile",
principalColumn: "PerfomerId",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Contact_ApplicationUser_OwnerId",
table: "Contact",
column: "OwnerId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_PerformerProfile_Activity_ActivityCode",
table: "PerformerProfile",
column: "ActivityCode",
principalTable: "Activity",
principalColumn: "Code",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_PerformerProfile_Location_OrganisationAddressId",
table: "PerformerProfile",
column: "OrganisationAddressId",
principalTable: "Location",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_PerformerProfile_ApplicationUser_PerfomerId",
table: "PerformerProfile",
column: "PerfomerId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_AccountBalance_ApplicationUser_UserId", table: "AccountBalance");
migrationBuilder.DropForeignKey(name: "FK_BalanceImpact_AccountBalance_BalanceId", table: "BalanceImpact");
migrationBuilder.DropForeignKey(name: "FK_Blog_ApplicationUser_AuthorId", table: "Blog");
migrationBuilder.DropForeignKey(name: "FK_BookQuery_ApplicationUser_ClientId", table: "BookQuery");
migrationBuilder.DropForeignKey(name: "FK_BookQuery_Location_LocationId", table: "BookQuery");
migrationBuilder.DropForeignKey(name: "FK_BookQuery_PerformerProfile_PerformerId", table: "BookQuery");
migrationBuilder.DropForeignKey(name: "FK_CircleMember_Circle_CircleId", table: "CircleMember");
migrationBuilder.DropForeignKey(name: "FK_CircleMember_ApplicationUser_MemberId", table: "CircleMember");
migrationBuilder.DropForeignKey(name: "FK_Command_ApplicationUser_ClientId", table: "Command");
migrationBuilder.DropForeignKey(name: "FK_Command_PerformerProfile_PerformerId", table: "Command");
migrationBuilder.DropForeignKey(name: "FK_Contact_ApplicationUser_OwnerId", table: "Contact");
migrationBuilder.DropForeignKey(name: "FK_PerformerProfile_Activity_ActivityCode", table: "PerformerProfile");
migrationBuilder.DropForeignKey(name: "FK_PerformerProfile_Location_OrganisationAddressId", table: "PerformerProfile");
migrationBuilder.DropForeignKey(name: "FK_PerformerProfile_ApplicationUser_PerfomerId", table: "PerformerProfile");
migrationBuilder.DropTable("GoogleCloudMobileDeclaration");
migrationBuilder.DropTable("Client");
migrationBuilder.DropTable("RefreshToken");
migrationBuilder.CreateTable(
name: "Application",
columns: table => new
{
ApplicationID = table.Column<string>(nullable: false),
DisplayName = table.Column<string>(nullable: true),
LogoutRedirectUri = table.Column<string>(nullable: true),
RedirectUri = table.Column<string>(nullable: true),
Secret = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Application", x => x.ApplicationID);
});
migrationBuilder.AddColumn<string>(
name: "GoogleRegId",
table: "AspNetUsers",
nullable: true);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AccountBalance_ApplicationUser_UserId",
table: "AccountBalance",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_BalanceImpact_AccountBalance_BalanceId",
table: "BalanceImpact",
column: "BalanceId",
principalTable: "AccountBalance",
principalColumn: "UserId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Blog_ApplicationUser_AuthorId",
table: "Blog",
column: "AuthorId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_BookQuery_ApplicationUser_ClientId",
table: "BookQuery",
column: "ClientId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_BookQuery_Location_LocationId",
table: "BookQuery",
column: "LocationId",
principalTable: "Location",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_BookQuery_PerformerProfile_PerformerId",
table: "BookQuery",
column: "PerformerId",
principalTable: "PerformerProfile",
principalColumn: "PerfomerId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_CircleMember_Circle_CircleId",
table: "CircleMember",
column: "CircleId",
principalTable: "Circle",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_CircleMember_ApplicationUser_MemberId",
table: "CircleMember",
column: "MemberId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Command_ApplicationUser_ClientId",
table: "Command",
column: "ClientId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Command_PerformerProfile_PerformerId",
table: "Command",
column: "PerformerId",
principalTable: "PerformerProfile",
principalColumn: "PerfomerId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Contact_ApplicationUser_OwnerId",
table: "Contact",
column: "OwnerId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_PerformerProfile_Activity_ActivityCode",
table: "PerformerProfile",
column: "ActivityCode",
principalTable: "Activity",
principalColumn: "Code",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_PerformerProfile_Location_OrganisationAddressId",
table: "PerformerProfile",
column: "OrganisationAddressId",
principalTable: "Location",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_PerformerProfile_ApplicationUser_PerfomerId",
table: "PerformerProfile",
column: "PerfomerId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}

View file

@ -1,6 +1,8 @@
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using Yavsc.Models;
namespace Yavsc.Migrations
@ -13,6 +15,17 @@ namespace Yavsc.Migrations
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348");
modelBuilder.Entity("GoogleCloudMobileDeclaration", b =>
{
b.Property<string>("RegistrationId");
b.Property<string>("DeviceOwnerId");
b.Property<string>("Name");
b.HasKey("RegistrationId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
@ -95,21 +108,6 @@ namespace Yavsc.Migrations
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("Yavsc.Application", b =>
{
b.Property<string>("ApplicationID");
b.Property<string>("DisplayName");
b.Property<string>("LogoutRedirectUri");
b.Property<string>("RedirectUri");
b.Property<string>("Secret");
b.HasKey("ApplicationID");
});
modelBuilder.Entity("Yavsc.Location", b =>
{
b.Property<long>("Id")
@ -172,8 +170,6 @@ namespace Yavsc.Migrations
b.Property<bool>("EmailConfirmed");
b.Property<string>("GoogleRegId");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
@ -210,6 +206,52 @@ namespace Yavsc.Migrations
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("Yavsc.Models.Auth.Client", b =>
{
b.Property<string>("Id");
b.Property<bool>("Active");
b.Property<string>("AllowedOrigin")
.HasAnnotation("MaxLength", 100);
b.Property<string>("DisplayName");
b.Property<string>("LogoutRedirectUri");
b.Property<string>("RedirectUri");
b.Property<int>("RefreshTokenLifeTime");
b.Property<string>("Secret");
b.Property<int>("Type");
b.HasKey("Id");
});
modelBuilder.Entity("Yavsc.Models.Auth.RefreshToken", b =>
{
b.Property<string>("Id");
b.Property<string>("ClientId")
.IsRequired()
.HasAnnotation("MaxLength", 50);
b.Property<DateTime>("ExpiresUtc");
b.Property<DateTime>("IssuedUtc");
b.Property<string>("ProtectedTicket")
.IsRequired();
b.Property<string>("Subject")
.IsRequired()
.HasAnnotation("MaxLength", 50);
b.HasKey("Id");
});
modelBuilder.Entity("Yavsc.Models.BalanceImpact", b =>
{
b.Property<long>("Id")
@ -394,7 +436,7 @@ namespace Yavsc.Migrations
b.HasKey("Id");
});
modelBuilder.Entity("Yavsc.Models.OAuth2Tokens", b =>
modelBuilder.Entity("Yavsc.Models.OAuth.OAuth2Tokens", b =>
{
b.Property<string>("UserId");
@ -477,6 +519,13 @@ namespace Yavsc.Migrations
b.HasKey("Id");
});
modelBuilder.Entity("GoogleCloudMobileDeclaration", b =>
{
b.HasOne("Yavsc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("DeviceOwnerId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")

View file

@ -5,7 +5,9 @@ using System.Threading.Tasks;
using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Data.Entity;
using Yavsc.Models.Auth;
using Yavsc.Models.Booking;
using Yavsc.Models.OAuth;
namespace Yavsc.Models
{
@ -26,7 +28,9 @@ namespace Yavsc.Models
optionsBuilder.UseNpgsql(Startup.ConnectionString);
}
public DbSet<Application> Applications { get; set; }
public DbSet<Client> Applications { get; set; }
public DbSet<RefreshToken> RefreshTokens { get; set; }
/// <summary>
/// Activities referenced on this site
/// </summary>
@ -151,10 +155,12 @@ namespace Yavsc.Models
return Task.FromResult(0);
}
Application FindApplication(string clientId)
Client FindApplication(string clientId)
{
return Applications.FirstOrDefault(
app=>app.ApplicationID == clientId);
app=>app.Id == clientId);
}
}
}

View file

@ -0,0 +1,10 @@
namespace Yavsc.Models.Auth
{
public enum ApplicationTypes: int
{
JavaScript = 0,
NativeConfidential = 1
};
}

View file

@ -1,14 +1,20 @@
using System.ComponentModel.DataAnnotations;
namespace Yavsc
namespace Yavsc.Models.Auth
{
public class Application
public class Client
{
[Key]
public string ApplicationID { get; set; }
public string Id { get; set; }
public string DisplayName { get; set; }
public string RedirectUri { get; set; }
[MaxLength(100)]
public string LogoutRedirectUri { get; set; }
public string Secret { get; set; }
public ApplicationTypes Type { get; set; }
public bool Active { get; set; }
public int RefreshTokenLifeTime { get; set; }
}
}

View file

@ -0,0 +1,33 @@
using System.ComponentModel.DataAnnotations;
namespace Yavsc.Models.Auth {
public class ExternalLoginViewModel
{
public string Name { get; set; }
public string Url { get; set; }
public string State { get; set; }
}
public class RegisterExternalBindingModel
{
[Required]
public string UserName { get; set; }
[Required]
public string Provider { get; set; }
[Required]
public string ExternalAccessToken { get; set; }
}
public class ParsedExternalAccessToken
{
public string user_id { get; set; }
public string app_id { get; set; }
}
}

View file

@ -1,11 +1,11 @@
using System;
using System.ComponentModel.DataAnnotations;
namespace Yavsc.Models
namespace Yavsc.Models.OAuth
{
/// <summary>
/// OffLine OAuth2 Token
/// To use against the Google Calendar Api
/// To use against a third party Api
/// </summary>
public partial class OAuth2Tokens
{
@ -17,7 +17,7 @@ namespace Yavsc.Models
public string UserId { get; set; }
/// <summary>
/// Expiration date & time
/// Expiration date &amp; time
/// </summary>
/// <returns></returns>
public DateTime Expiration { get; set; }

View file

@ -0,0 +1,23 @@
using System;
using System.ComponentModel.DataAnnotations;
namespace Yavsc.Models.Auth
{
public class RefreshToken
{
[Key]
public string Id { get; set; }
[Required]
[MaxLength(50)]
public string Subject { get; set; }
[Required]
[MaxLength(50)]
public string ClientId { get; set; }
public DateTime IssuedUtc { get; set; }
public DateTime ExpiresUtc { get; set; }
[Required]
public string ProtectedTicket { get; set; }
}
}

View file

@ -1,6 +1,11 @@
using System.ComponentModel.DataAnnotations;
namespace Yavsc.Models.Auth {
public class Scope {
[Key]
public string Id { get; set; }

View file

@ -1,4 +1,6 @@
using Yavsc.Models.OAuth;
namespace Yavsc.Models.Auth {
public class UserCredential {

View file

@ -1,6 +1,8 @@
using System;
using System.Security.Claims;
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.AspNet.Authentication.Facebook;
using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
@ -18,10 +20,21 @@ namespace Yavsc
public partial class Startup
{
public static CookieAuthenticationOptions ExternalCookieAppOptions { get; private set; }
public static IdentityOptions IdentityAppOptions { get; set; }
public static FacebookOptions FacebookAppOptions { get; private set; }
public static OAuthAuthorizationServerOptions OAuthServerAppOptions { get; private set; }
public static YavscGoogleOptions YavscGoogleAppOptions { get; private set; }
public static MonoDataProtectionProvider ProtectionProvider { get; private set; }
// public static CookieAuthenticationOptions BearerCookieOptions { get; private set; }
private void ConfigureOAuthServices(IServiceCollection services)
{
services.Configure<SharedAuthenticationOptions>(options => options.SignInScheme = Constants.ApplicationAuthenticationSheme);
services.Add(ServiceDescriptor.Singleton(typeof(IOptions<OAuth2AppSettings>), typeof(OptionsManager<OAuth2AppSettings>)));
// used by the YavscGoogleOAuth middelware (TODO drop it)
services.AddTransient<Microsoft.Extensions.WebEncoders.UrlEncoder, UrlEncoder>();
@ -42,143 +55,69 @@ namespace Yavsc
new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature);
}
); */
services.AddAuthentication(options =>
services.AddAuthentication(options =>
{
options.SignInScheme = Constants.ApplicationAuthenticationSheme;
options.SignInScheme = Constants.ExternalAuthenticationSheme;
});
var protector = new MonoDataProtectionProvider(Configuration["Site:Title"]);;
services.AddInstance<MonoDataProtectionProvider>(
protector
);
ProtectionProvider = new MonoDataProtectionProvider(Configuration["Site:Title"]); ;
services.AddInstance<MonoDataProtectionProvider>
(ProtectionProvider);
services.AddIdentity<ApplicationUser, IdentityRole>(
option =>
{
IdentityAppOptions = option;
option.User.AllowedUserNameCharacters += " ";
option.User.RequireUniqueEmail = true;
option.Cookies.ApplicationCookie.DataProtectionProvider = protector;
option.Cookies.ApplicationCookie.LoginPath = new PathString(Constants.LoginPath.Substring(1));
option.Cookies.ApplicationCookie.AccessDeniedPath = new PathString(Constants.AccessDeniedPath.Substring(1));
option.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
// option.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
// option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme;
// option.Cookies.TwoFactorRememberMeCookie.ExpireTimeSpan = TimeSpan.FromDays(30);
// option.Cookies.TwoFactorRememberMeCookie.DataProtectionProvider = protector;
//option.Cookies.ExternalCookieAuthenticationScheme = Constants.ExternalAuthenticationSheme;
// option.Cookies.ExternalCookie.AutomaticAuthenticate = true;
//option.Cookies.ExternalCookie.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
// option.Cookies.ExternalCookie.DataProtectionProvider = protector;
// option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.ApplicationCookie.LoginPath = "/signin";
// option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
/*
option.Cookies.ApplicationCookie.DataProtectionProvider = protector;
option.Cookies.ApplicationCookie.LoginPath = new PathString(Constants.LoginPath.Substring(1));
option.Cookies.ApplicationCookie.AccessDeniedPath = new PathString(Constants.AccessDeniedPath.Substring(1));
option.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.TwoFactorRememberMeCookie.ExpireTimeSpan = TimeSpan.FromDays(30);
option.Cookies.TwoFactorRememberMeCookie.DataProtectionProvider = protector;
option.Cookies.ExternalCookieAuthenticationScheme = Constants.ExternalAuthenticationSheme;
option.Cookies.ExternalCookie.AutomaticAuthenticate = true;
option.Cookies.ExternalCookie.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
option.Cookies.ExternalCookie.DataProtectionProvider = protector;
*/
}
).AddEntityFrameworkStores<ApplicationDbContext>()
.AddTokenProvider<EmailTokenProvider<ApplicationUser>>(Constants.EMailFactor)
.AddTokenProvider<UserTokenProvider>(Constants.DefaultFactor)
;
}
private void ConfigureOAuthApp(IApplicationBuilder app)
{
app.UseIdentity();
// External authentication shared cookie:
app.UseCookieAuthentication(options =>
{
//options.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
ExternalCookieAppOptions = options;
options.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
options.AutomaticAuthenticate = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
options.LoginPath = new PathString(Constants.LoginPath.Substring(1));
options.AccessDeniedPath = new PathString(Constants.AccessDeniedPath.Substring(1));
options.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
});
var gvents = new OAuthEvents();
var googleOptions = new YavscGoogleOptions
{
ClientId = Configuration["Authentication:Google:ClientId"],
ClientSecret = Configuration["Authentication:Google:ClientSecret"],
AccessType = "offline",
SaveTokensAsClaims = true,
UserInformationEndpoint = "https://www.googleapis.com/plus/v1/people/me",
Events = new OAuthEvents
{
OnCreatingTicket = async context =>
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
var gcontext = context as GoogleOAuthCreatingTicketContext;
context.Identity.AddClaim(new Claim(YavscClaimTypes.GoogleUserId, gcontext.GoogleUserId));
var service =
serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
await service.StoreTokenAsync(gcontext.GoogleUserId, context.TokenResponse);
}
}
}
};
googleOptions.Scope.Add("https://www.googleapis.com/auth/calendar");
app.UseMiddleware<Yavsc.Auth.GoogleMiddleware>(googleOptions);
// Facebook
app.UseFacebookAuthentication(options =>
{
options.AppId = Configuration["Authentication:Facebook:AppId"];
options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
options.Scope.Add("email");
options.UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=id,name,email,first_name,last_name";
});
/* Generic OAuth (here GitHub): options.Notifications = new OAuthAuthenticationNotifications
{
OnGetUserInformationAsync = async context =>
{
// Get the GitHub user
HttpRequestMessage userRequest = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
userRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
userRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage userResponse = await context.Backchannel.SendAsync(userRequest, context.HttpContext.RequestAborted);
userResponse.EnsureSuccessStatusCode();
var text = await userResponse.Content.ReadAsStringAsync();
JObject user = JObject.Parse(text);
var identity = new ClaimsIdentity(
context.Options.AuthenticationType,
ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType);
JToken value;
var id = user.TryGetValue("id", out value) ? value.ToString() : null;
if (!string.IsNullOrEmpty(id))
{
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, id, ClaimValueTypes.String, context.Options.AuthenticationType));
}
var userName = user.TryGetValue("login", out value) ? value.ToString() : null;
if (!string.IsNullOrEmpty(userName))
{
identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, userName, ClaimValueTypes.String, context.Options.AuthenticationType));
}
var name = user.TryGetValue("name", out value) ? value.ToString() : null;
if (!string.IsNullOrEmpty(name))
{
identity.AddClaim(new Claim("urn:github:name", name, ClaimValueTypes.String, context.Options.AuthenticationType));
}
var link = user.TryGetValue("url", out value) ? value.ToString() : null;
if (!string.IsNullOrEmpty(link))
{
identity.AddClaim(new Claim("urn:github:url", link, ClaimValueTypes.String, context.Options.AuthenticationType));
}
context.Identity = identity;
}
}; */
app.UseOAuthAuthorizationServer(
options =>
{
OAuthServerAppOptions = options;
options.AuthorizeEndpointPath = new PathString(Constants.AuthorizePath.Substring(1));
options.TokenEndpointPath = new PathString(Constants.TokenPath.Substring(1));
options.ApplicationCanDisplayErrors = true;
options.AllowInsecureHttp = true;
options.AuthenticationScheme = OAuthDefaults.AuthenticationType;
options.Provider = new OAuthAuthorizationServerProvider
{
OnValidateClientRedirectUri = ValidateClientRedirectUri,
@ -201,8 +140,48 @@ namespace Yavsc
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
}
}
);
app.UseIdentity();
var gvents = new OAuthEvents();
YavscGoogleAppOptions = new YavscGoogleOptions
{
ClientId = Configuration["Authentication:Google:ClientId"],
ClientSecret = Configuration["Authentication:Google:ClientSecret"],
AccessType = "offline",
SaveTokensAsClaims = true,
UserInformationEndpoint = "https://www.googleapis.com/plus/v1/people/me",
Events = new OAuthEvents
{
OnCreatingTicket = async context =>
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
var gcontext = context as GoogleOAuthCreatingTicketContext;
context.Identity.AddClaim(new Claim(YavscClaimTypes.GoogleUserId, gcontext.GoogleUserId));
var service =
serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
await service.StoreTokenAsync(gcontext.GoogleUserId, context.TokenResponse);
}
}
}
};
YavscGoogleAppOptions.Scope.Add("https://www.googleapis.com/auth/calendar");
app.UseMiddleware<Yavsc.Auth.GoogleMiddleware>(YavscGoogleAppOptions);
// Facebook
app.UseFacebookAuthentication(options =>
{
FacebookAppOptions = options;
options.AppId = Configuration["Authentication:Facebook:AppId"];
options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
options.Scope.Add("email");
options.UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=id,name,email,first_name,last_name";
});
}
}
}

View file

@ -6,23 +6,25 @@ using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using OAuth.AspNet.AuthServer;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Auth;
namespace Yavsc
{
public partial class Startup
{
private Application GetApplication(string clientId)
private Client GetApplication(string clientId)
{
var dbContext = new ApplicationDbContext();
var app = dbContext.Applications.FirstOrDefault(x=>x.ApplicationID == clientId);
var app = dbContext.Applications.FirstOrDefault(x => x.Id == clientId);
return app;
}
private readonly ConcurrentDictionary<string, string> _authenticationCodes = new ConcurrentDictionary<string, string>(StringComparer.Ordinal);
private Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
if (context==null) throw new InvalidOperationException("context == null");
if (context == null) throw new InvalidOperationException("context == null");
var app = GetApplication(context.ClientId);
if (app == null) return Task.FromResult(0);
Startup.logger.LogInformation($"ValidateClientRedirectUri: Validated ({app.RedirectUri})");
@ -32,16 +34,40 @@ namespace Yavsc
private Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId,clientSecret;
string clientId, clientSecret;
if (context.TryGetBasicCredentials(out clientId, out clientSecret) ||
context.TryGetFormCredentials(out clientId, out clientSecret))
{
var app = GetApplication(clientId);
if (app != null && app.Secret == clientSecret)
var client = GetApplication(clientId);
if (client.Type == ApplicationTypes.NativeConfidential)
{
Startup.logger.LogInformation($"ValidateClientAuthentication: Validated ({clientId})");
if (string.IsNullOrWhiteSpace(clientSecret))
{
context.SetError("invalid_clientId", "Client secret should be sent.");
return Task.FromResult<object>(null);
}
else
{
if (client.Secret != Helper.GetHash(clientSecret))
{
context.SetError("invalid_clientId", "Client secret is invalid.");
return Task.FromResult<object>(null);
}
}
}
if (!client.Active)
{
context.SetError("invalid_clientId", "Client is inactive.");
return Task.FromResult<object>(null);
}
if (client != null && client.Secret == clientSecret)
{
logger.LogInformation($"\\o/ ValidateClientAuthentication: Validated ({clientId})");
context.Validated();
} else Startup.logger.LogInformation($"ValidateClientAuthentication: KO ({clientId})");
}
else Startup.logger.LogInformation($"ValidateClientAuthentication: KO ({clientId})");
}
else Startup.logger.LogInformation($"ValidateClientAuthentication: nor Basic neither Form credential found");
return Task.FromResult(0);
@ -49,7 +75,12 @@ namespace Yavsc
private Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
logger.LogWarning($"GrantResourceOwnerCredentials task ... {context.UserName}");
// var user = ValidateUser(context.UserName, context.Password)
ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity(context.UserName, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x))));
// TODO set a NameIdentifier, roles and scopes claims
context.Validated(principal);
@ -67,7 +98,7 @@ namespace Yavsc
private void CreateAuthenticationCode(AuthenticationTokenCreateContext context)
{
Startup.logger.LogInformation("CreateAuthenticationCode");
logger.LogInformation("CreateAuthenticationCode");
context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
_authenticationCodes[context.Token] = context.SerializeTicket();
}
@ -78,20 +109,21 @@ namespace Yavsc
if (_authenticationCodes.TryRemove(context.Token, out value))
{
context.DeserializeTicket(value);
logger.LogInformation("ReceiveAuthenticationCode: Success");
}
}
private void CreateRefreshToken(AuthenticationTokenCreateContext context)
{
var uid = context.Ticket.Principal.GetUserId();
Startup.logger.LogInformation($"CreateRefreshToken for {uid}");
logger.LogInformation($"CreateRefreshToken for {uid}");
context.SetToken(context.SerializeTicket());
}
private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
{
var uid = context.Ticket.Principal.GetUserId();
Startup.logger.LogInformation($"ReceiveRefreshToken for {uid}");
logger.LogInformation($"ReceiveRefreshToken for {uid}");
context.DeserializeTicket(context.Token);
}
}

View file

@ -8,9 +8,6 @@ using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Localization;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Filters;
@ -22,7 +19,6 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.Net.Http.Headers;
using Yavsc.Auth;
using Yavsc.Formatters;
using Yavsc.Models;
using Yavsc.Services;

View file

@ -1,12 +1,17 @@
using System.Collections.Generic;
using Microsoft.Extensions.Primitives;
namespace Yavsc
namespace Yavsc.Models.Auth
{
public class AuthorisationView { 
public Application Application { get; set; }
public IEnumerable<string> Scopes { get; set; }
public Scope[] Scopes { get; set; }
public string RedirectUrl { get; set; }
public string Message { get; set; }
public string ClientId {get; set; }
public string State {get; set; }
public string ResponseType { get; set; }
public IDictionary<string,StringValues> QueryStringComponents { get; set; }
}
}

View file

@ -1,4 +1,4 @@
@model Yavsc.Application
@model Yavsc.Models.Auth.Client
@{
ViewData["Title"] = "Create";
@ -8,9 +8,17 @@
<form asp-action="Create">
<div class="form-horizontal">
<h4>Application</h4>
<h4>Client</h4>
<hr />
<div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="checkbox">
<input asp-for="Active" />
<label asp-for="Active"></label>
</div>
</div>
</div>
<div class="form-group">
<label asp-for="DisplayName" class="col-md-2 control-label"></label>
<div class="col-md-10">
@ -32,6 +40,13 @@
<span asp-validation-for="RedirectUri" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="RefreshTokenLifeTime" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="RefreshTokenLifeTime" class="form-control" />
<span asp-validation-for="RefreshTokenLifeTime" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Secret" class="col-md-2 control-label"></label>
<div class="col-md-10">
@ -39,6 +54,16 @@
<span asp-validation-for="Secret" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Type" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select name="Type" class="form-control">
<option value="0" >JavaScript</option>
<option value="1" >NativeConfidential</option>
</select>
<span asp-validation-for="Type" class="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />

View file

@ -1,4 +1,4 @@
@model Yavsc.Application
@model Yavsc.Models.Auth.Client
@{
ViewData["Title"] = "Delete";
@ -8,9 +8,15 @@
<h3>Are you sure you want to delete this?</h3>
<div>
<h4>Application</h4>
<h4>Client</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Active)
</dt>
<dd>
@Html.DisplayFor(model => model.Active)
</dd>
<dt>
@Html.DisplayNameFor(model => model.DisplayName)
</dt>
@ -29,12 +35,24 @@
<dd>
@Html.DisplayFor(model => model.RedirectUri)
</dd>
<dt>
@Html.DisplayNameFor(model => model.RefreshTokenLifeTime)
</dt>
<dd>
@Html.DisplayFor(model => model.RefreshTokenLifeTime)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Secret)
</dt>
<dd>
@Html.DisplayFor(model => model.Secret)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Type)
</dt>
<dd>
@Html.DisplayFor(model => model.Type)
</dd>
</dl>
<form asp-action="Delete">

View file

@ -1,4 +1,4 @@
@model Yavsc.Application
@model Yavsc.Models.Auth.Client
@{
ViewData["Title"] = "Details";
@ -7,9 +7,21 @@
<h2>Details</h2>
<div>
<h4>Application</h4>
<h4>Client</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Id)
</dt>
<dd>
@Html.DisplayFor(model => model.Id)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Active)
</dt>
<dd>
@Html.DisplayFor(model => model.Active)
</dd>
<dt>
@Html.DisplayNameFor(model => model.DisplayName)
</dt>
@ -29,10 +41,10 @@
@Html.DisplayFor(model => model.RedirectUri)
</dd>
<dt>
@Html.DisplayNameFor(model => model.ApplicationID)
@Html.DisplayNameFor(model => model.RefreshTokenLifeTime)
</dt>
<dd>
@Html.DisplayFor(model => model.ApplicationID)
@Html.DisplayFor(model => model.RefreshTokenLifeTime)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Secret)
@ -40,9 +52,15 @@
<dd>
@Html.DisplayFor(model => model.Secret)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Type)
</dt>
<dd>
@Html.DisplayFor(model => model.Type)
</dd>
</dl>
</div>
<p>
<a asp-action="Edit" asp-route-id="@Model.ApplicationID">Edit</a> |
<a asp-action="Edit" asp-route-id="@Model.Id">Edit</a> |
<a asp-action="Index">Back to List</a>
</p>

View file

@ -1,4 +1,4 @@
@model Yavsc.Application
@model Yavsc.Models.Auth.Client
@{
ViewData["Title"] = "Edit";
@ -8,10 +8,18 @@
<form asp-action="Edit">
<div class="form-horizontal">
<h4>Application</h4>
<h4>Client</h4>
<hr />
<div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="ApplicationID" />
<input type="hidden" asp-for="Id" />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="checkbox">
<input asp-for="Active" />
<label asp-for="Active"></label>
</div>
</div>
</div>
<div class="form-group">
<label asp-for="DisplayName" class="col-md-2 control-label"></label>
<div class="col-md-10">
@ -33,6 +41,13 @@
<span asp-validation-for="RedirectUri" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="RefreshTokenLifeTime" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="RefreshTokenLifeTime" class="form-control" />
<span asp-validation-for="RefreshTokenLifeTime" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Secret" class="col-md-2 control-label"></label>
<div class="col-md-10">
@ -40,6 +55,13 @@
<span asp-validation-for="Secret" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Type" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="Type" class="form-control"></select>
<span asp-validation-for="Type" class="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />

View file

@ -1,4 +1,4 @@
@model IEnumerable<Yavsc.Application>
@model IEnumerable<Yavsc.Models.Auth.Client>
@{
ViewData["Title"] = "Index";
@ -12,7 +12,7 @@
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.ApplicationID)
@Html.DisplayNameFor(model => model.Active)
</th>
<th>
@Html.DisplayNameFor(model => model.DisplayName)
@ -23,16 +23,22 @@
<th>
@Html.DisplayNameFor(model => model.RedirectUri)
</th>
<th>
@Html.DisplayNameFor(model => model.RefreshTokenLifeTime)
</th>
<th>
@Html.DisplayNameFor(model => model.Secret)
</th>
<th>
@Html.DisplayNameFor(model => model.Type)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ApplicationID)
@Html.DisplayFor(modelItem => item.Active)
</td>
<td>
@Html.DisplayFor(modelItem => item.DisplayName)
@ -43,13 +49,19 @@
<td>
@Html.DisplayFor(modelItem => item.RedirectUri)
</td>
<td>
@Html.DisplayFor(modelItem => item.RefreshTokenLifeTime)
</td>
<td>
@Html.DisplayFor(modelItem => item.Secret)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.ApplicationID">Edit</a> |
<a asp-action="Details" asp-route-id="@item.ApplicationID">Details</a> |
<a asp-action="Delete" asp-route-id="@item.ApplicationID">Delete</a>
@Html.DisplayFor(modelItem => item.Type)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="@item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
</td>
</tr>
}

View file

@ -0,0 +1,32 @@
@using Microsoft.AspNet.Http.Authentication
@using Microsoft.AspNet.WebUtilities
@using System.Security.Claims
@using Microsoft.Extensions.Primitives
@model Yavsc.Models.Auth.AuthorisationView
@{
ViewBag.Title = @SR["Authorize"];
}
<h1>Authorization Server</h1>
<h2>OAuth2 Authorize</h2>
<form method="POST" asp-action="Authorize" asp-controller="OAuth">
<p>Hello, @User.Identity.Name</p>
<p>@Model.Message</p>
<p>A third party application want to do the following on your behalf:</p>
<ul>
@foreach (var scope in Model.Scopes)
{
<li><em>@scope.Id</em>: @scope.Description</li>
}
</ul>
<p>
<input type="submit" class="btn btn-lg btn-success" name="submit.Grant" value="Grant" />
<input type="submit" class="btn btn-lg btn-danger" name="submit.Deny" value="Deny" />
<input type="submit" class="btn btn-lg btn-success" name="submit.Login" value="Sign in as different user" />
</p>
@if (Model.QueryStringComponents!=null) {
@foreach (var key in Model.QueryStringComponents.Keys) {
@Html.Hidden(key,Model.QueryStringComponents[key])
}
}
</form>

View file

@ -1,32 +1,34 @@
@using Microsoft.AspNet.Http.Authentication
@using Microsoft.AspNet.Http.Authentication
@using Microsoft.AspNet.WebUtilities
@using System.Security.Claims
@using System.Security.Claims
@model Yavsc.Models.Auth.AuthorisationView
@{
AuthenticationManager authentication = Context.Authentication;
ClaimsPrincipal principal = authentication.AuthenticateAsync(Constants.ApplicationAuthenticationSheme).Result;
string[] scopes = QueryHelpers.ParseQuery(Context.Request.QueryString.Value)["scope"];
ViewBag.Title = @SR["Authorize"];
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Authorize</title>
</head>
<body>
<h1>Authorization Server</h1>
<h2>OAuth2 Authorize</h2>
<form method="POST">
<p>Hello, @principal.Identity.Name</p>
<p>A third party application want to do the following on your behalf:</p>
<ul>
@foreach (var scope in scopes)
<h1>Authorization Server</h1>
<h2>OAuth2 Authorize</h2>
<form method="POST" asp-action="Authorize" asp-controller="OAuth"
asp-route-client_id="@Model.ClientId"
asp-route-redirect_url="@Model.RedirectUrl"
asp-route-state="@Model.State"
asp-route-response_type="@Model.ResponseType"
>
<p>Hello, @User.Identity.Name</p>
<p>@Model.Message</p>
<p>A third party application want to do the following on your behalf:</p>
<ul>
@if (Model.Scopes!=null) {
@foreach (var scope in Model.Scopes)
{
<li>@scope</li>
}
</ul>
<p>
<input type="submit" name="submit.Grant" value="Grant" />
<input type="submit" name="submit.Login" value="Sign in as different user" />
</p>
</form>
</body>
</html>
<li><em>@scope.Id</em>: @scope.Description</li>
}
}
</ul>
<p>
<input type="submit" class="btn btn-lg btn-success" name="submit.Grant" value="Grant" />
<input type="submit" class="btn btn-lg btn-danger" name="submit.Deny" value="Deny" />
<input type="submit" class="btn btn-lg btn-success" name="submit.Login" value="Sign in as different user" />
</p>
</form>

View file

@ -1,22 +0,0 @@

@model AuthorisationView
<div class="jumbotron">
<h1>Authorization @Application?.DisplayName</h1>
<p>@Model.Message</p>
<p class="lead text-left">Do you wanna grant <strong>@Model.Application.DisplayName</strong> an access to your resources? (scopes requested: @Model.Message.Scope)</p>
<form enctype="application/x-www-form-urlencoded" method="post">
@Html.AntiForgeryToken()
@foreach (var scope in Model.Scopes) {
<li>@scope</li>
}
@Html.Hidden("ReturnUrl")
<input formaction="/oauth/accept" class="btn btn-lg btn-success" name="Authorize" type="submit" value="Yeah, sure" />
<input formaction="/oauth/deny" class="btn btn-lg btn-danger" name="Deny" type="submit" value="Hell, no" />
<input formaction="/oauth/deny" class="btn btn-lg btn-success" name="Submit.Login" type="submit" value="Login using another account" />
</form>
</div>

View file

@ -45,5 +45,12 @@
},
"RSAParamFile": "RSA-Params.json",
"ExpiresInHours": 168
},
"Authentication": {
"Google": {
"ApiKey": "[Your ApiKey]",
"ClientId" : "[Your ClientId]",
"ClientSecret": "[Your ClientSecret"
}
}
}

View file

@ -104,7 +104,8 @@
"Microsoft.AspNet.DataProtection.SystemWeb": "1.0.0-rc1-final",
"Microsoft.AspNet.Authentication.JwtBearer": "1.0.0-rc1-final",
"PayPalCoreSDK": "1.7.1",
"PayPalButtonManagerSDK": "2.10.109"
"PayPalButtonManagerSDK": "2.10.109",
"Microsoft.AspNet.Owin": "1.0.0-rc1-final"
},
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel --server.urls http://*:5000",

File diff suppressed because it is too large Load diff