[WIP] chat hub.

This commit is contained in:
2019-01-30 11:14:32 +00:00
parent c14b07ae87
commit 5eea24f8b8
12 changed files with 225 additions and 212 deletions

View File

@ -23,6 +23,8 @@ namespace Yavsc.Abstract.Streaming
// A name where to save this stream, relative to user's files root // A name where to save this stream, relative to user's files root
string DifferedFileName { get; set; } string DifferedFileName { get; set; }
int SequenceNumber { get; set; }
[Required] [Required]
string OwnerId {get; set; } string OwnerId {get; set; }

View File

@ -11,6 +11,9 @@ namespace Yavsc
TokenPath = "~/token", TokenPath = "~/token",
LoginPath = "~/signin", LoginPath = "~/signin",
LogoutPath = "~/signout", UserInfoPath = "~/api/me", LogoutPath = "~/signout", UserInfoPath = "~/api/me",
SignalRPath = "/api/signalr",
ApplicationAuthenticationSheme = "ServerCookie", ApplicationAuthenticationSheme = "ServerCookie",
ExternalAuthenticationSheme= "ExternalCookie", ExternalAuthenticationSheme= "ExternalCookie",
CompanyInfoUrl = " https://societeinfo.com/app/rest/api/v1/company/json?registration_number={0}&key={1}", CompanyInfoUrl = " https://societeinfo.com/app/rest/api/v1/company/json?registration_number={0}&key={1}",

View File

@ -13,17 +13,26 @@ namespace Yavsc.Models.Streaming
// set by the server, unique // set by the server, unique
public long Id { get; set; } public long Id { get; set; }
// a title for this flow //
/// <summary>
/// a title for this flow
/// </summary>
/// <value></value>
[StringLength(255)]
public string Title { get; set; } public string Title { get; set; }
// a little description // a little description
[StringLength(1023)]
public string Pitch { get; set; } public string Pitch { get; set; }
// The stream type // The stream type
[StringLength(127)]
public string MediaType { get; set; } public string MediaType { get; set; }
// A name where to save this stream, relative to user's files root // A name where to save this stream, relative to user's files root
[StringLength(255)]
public string DifferedFileName { get; set; } public string DifferedFileName { get; set; }
public int SequenceNumber { get; set; }
[Required] [Required]
public string OwnerId {get; set; } public string OwnerId {get; set; }

View File

@ -8,15 +8,17 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.SignalR;
using Microsoft.Data.Entity; using Microsoft.Data.Entity;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Streaming; using Yavsc.Models.Streaming;
using Yavsc.ViewModels.Streaming; using Yavsc.ViewModels.Streaming;
namespace Yavsc.Controllers namespace Yavsc.Controllers
{ {
[Route("api/LiveApi")] [Route("api/live")]
public class LiveApiController : Controller public class LiveApiController : Controller
{ {
public static ConcurrentDictionary<string, LiveCastMeta> Casters = new ConcurrentDictionary<string, LiveCastMeta>(); public static ConcurrentDictionary<string, LiveCastMeta> Casters = new ConcurrentDictionary<string, LiveCastMeta>();
@ -37,7 +39,10 @@ namespace Yavsc.Controllers
_dbContext = context; _dbContext = context;
_logger = loggerFactory.CreateLogger<LiveApiController>(); _logger = loggerFactory.CreateLogger<LiveApiController>();
} }
public async Task<string[]> GetFileNameHint(string id)
{
return await _dbContext.Tags.Where( t=> t.Name.StartsWith(id)).Select(t=>t.Name).Take(25).ToArrayAsync();
}
public async Task<IActionResult> GetLive(string id) public async Task<IActionResult> GetLive(string id)
{ {
@ -69,7 +74,7 @@ namespace Yavsc.Controllers
} }
var uid = User.GetUserId(); var uid = User.GetUserId();
// get some setup from user // get some setup from user
var flow = _dbContext.LiveFlow.SingleOrDefault(f=> (f.OwnerId==uid && f.Id == id)); var flow = _dbContext.LiveFlow.Include(f=>f.Owner).SingleOrDefault(f=> (f.OwnerId==uid && f.Id == id));
if (flow == null) if (flow == null)
{ {
ModelState.AddModelError("error",$"You don't own any flow with the id {id}"); ModelState.AddModelError("error",$"You don't own any flow with the id {id}");
@ -92,6 +97,11 @@ namespace Yavsc.Controllers
WebSocketReceiveResult received = await meta.Socket.ReceiveAsync WebSocketReceiveResult received = await meta.Socket.ReceiveAsync
(new ArraySegment<byte>(buffer), CancellationToken.None); (new ArraySegment<byte>(buffer), CancellationToken.None);
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
hubContext.Clients.All.addPublicStream(new { id = flow.Id, sender = flow.Owner.UserName, title = flow.Title, url = flow.GetFileUrl(),
mediaType = flow.MediaType }, $"{flow.Owner.UserName} is starting a stream!");
// FIXME do we really need to close those one in invalid state ? // FIXME do we really need to close those one in invalid state ?
Stack<string> ToClose = new Stack<string>(); Stack<string> ToClose = new Stack<string>();
@ -148,7 +158,6 @@ namespace Yavsc.Controllers
} }
// GET: api/LiveApi/5
[HttpGet("{id}", Name = "GetLiveFlow")] [HttpGet("{id}", Name = "GetLiveFlow")]
public async Task<IActionResult> GetLiveFlow([FromRoute] long id) public async Task<IActionResult> GetLiveFlow([FromRoute] long id)
{ {
@ -167,7 +176,6 @@ namespace Yavsc.Controllers
return Ok(liveFlow); return Ok(liveFlow);
} }
// PUT: api/LiveApi/5
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> PutLiveFlow([FromRoute] long id, [FromBody] LiveFlow liveFlow) public async Task<IActionResult> PutLiveFlow([FromRoute] long id, [FromBody] LiveFlow liveFlow)
{ {
@ -208,7 +216,6 @@ namespace Yavsc.Controllers
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/LiveApi
[HttpPost] [HttpPost]
public async Task<IActionResult> PostLiveFlow([FromBody] LiveFlow liveFlow) public async Task<IActionResult> PostLiveFlow([FromBody] LiveFlow liveFlow)
{ {

View File

@ -37,8 +37,9 @@ namespace Yavsc
app.UseAppBuilder(appBuilder => appBuilder.MapSignalR( app.UseAppBuilder(appBuilder => appBuilder.MapSignalR(
path, path,
new HubConfiguration() { new HubConfiguration() {
EnableDetailedErrors = false, EnableDetailedErrors = true,
EnableJSONP = false EnableJSONP = true,
EnableJavaScriptProxies = true
} }
)); ));
} }

View File

@ -12,6 +12,7 @@ using Yavsc.Abstract.FileSystem;
using Yavsc.Exceptions; using Yavsc.Exceptions;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.FileSystem; using Yavsc.Models.FileSystem;
using Yavsc.Models.Streaming;
using Yavsc.ViewModels; using Yavsc.ViewModels;
namespace Yavsc.Helpers namespace Yavsc.Helpers
@ -188,6 +189,16 @@ public static FileRecievedInfo ReceiveProSignature(this ClaimsPrincipal user, st
return item; return item;
} }
public static string GetFileUrl (this LiveFlow flow)
{
if (flow.DifferedFileName==null)
// no server-side backup for this stream
return null;
var fileInfo = new FileInfo(flow.DifferedFileName);
var ext = fileInfo.Extension;
var namelen = flow.DifferedFileName.Length - ext.Length;
var basename = flow.DifferedFileName.Substring(0,namelen);
return $"{Startup.UserFilesOptions.RequestPath}/{flow.Owner.UserName}/live/{basename}-{flow.SequenceNumber}{ext}";
}
} }
} }

View File

@ -22,19 +22,16 @@ using Microsoft.AspNet.SignalR;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Security.Claims;
namespace Yavsc namespace Yavsc
{ {
using System; using System;
using System.Threading;
using Microsoft.AspNet.Authorization; using Microsoft.AspNet.Authorization;
using Microsoft.Data.Entity; using Microsoft.Data.Entity;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Models; using Models;
using Models.Chat; using Models.Chat;
using Yavsc.ViewModels.Auth;
public class ChatHub : Hub, IDisposable public class ChatHub : Hub, IDisposable
{ {
@ -49,7 +46,7 @@ namespace Yavsc
_logger = loggerFactory.CreateLogger<ChatHub>(); _logger = loggerFactory.CreateLogger<ChatHub>();
} }
public override Task OnConnected() public override async Task OnConnected()
{ {
bool isAuth = false; bool isAuth = false;
string userName = null; string userName = null;
@ -60,27 +57,35 @@ namespace Yavsc
var group = isAuth ? var group = isAuth ?
"authenticated" : "anonymous"; "authenticated" : "anonymous";
// Log ("Cx: " + group); // Log ("Cx: " + group);
Groups.Add(Context.ConnectionId, group); await Groups.Add(Context.ConnectionId, group);
if (isAuth) if (isAuth)
{ {
/*
var user = _dbContext.Users.Single(u => u.UserName == userName); var user = _dbContext.Users.Include(u=>u.Connections).Single(u => u.UserName == userName);
if (user.Connections==null) if (user.Connections==null)
user.Connections = new List<ChatConnection>(); user.Connections = new List<ChatConnection>();
user.Connections.Add(new ChatConnection var ucx = user.Connections.FirstOrDefault(c=>c.ConnectionId == Context.ConnectionId);
{ if (ucx==null)
ConnectionId = Context.ConnectionId, user.Connections.Add(new ChatConnection
UserAgent = Context.Request.Headers["User-Agent"], {
Connected = true ConnectionId = Context.ConnectionId,
}); UserAgent = Context.Request.Headers["User-Agent"],
_dbContext.SaveChanges(); Connected = true
});
else {
ucx.Connected = true;
}
_dbContext.SaveChanges();
Clients.CallerState.BlackListedBy = await _dbContext.BlackListed.Where(r=>r.UserId == user.Id).Select(r=>r.OwnerId).ToArrayAsync();
*/
} }
} }
else Groups.Add(Context.ConnectionId, "anonymous"); else await Groups.Add(Context.ConnectionId, "anonymous");
Clients.Group("authenticated").notify("connected", Context.ConnectionId, userName); Clients.Group("authenticated").notify("connected", Context.ConnectionId, userName);
return base.OnConnected(); await OnConnected();
} }
public override Task OnDisconnected(bool stopCalled) public override Task OnDisconnected(bool stopCalled)
@ -140,7 +145,7 @@ namespace Yavsc
{ {
string uname = (Context.User != null) ? string uname = (Context.User != null) ?
$"[{Context.User.Identity.Name}]" : $"[{Context.User.Identity.Name}]" :
$"({name})"; $"?{name}";
Clients.All.addMessage(uname, message); Clients.All.addMessage(uname, message);
} }
@ -149,22 +154,18 @@ namespace Yavsc
[Authorize] [Authorize]
public async void SendPV(string connectionId, string message) public async void SendPV(string connectionId, string message)
{ {
// TODO personal black|white list + if (Clients.CallerState.BlackListedBy!=null)
// Contact list allowed only + foreach (string destId in Clients.CallerState.BlackListedBy)
// only pro {
string destUserId = (await _dbContext.ChatConnection.SingleAsync (c=>c.ConnectionId == connectionId)).ApplicationUserId; if (_dbContext.ChatConnection.Any(c => c.ConnectionId == connectionId && c.ApplicationUserId == destId ))
{
var sender = Context.User.Identity.Name; _logger.LogInformation($"PV aborted by black list");
var allow = await AllowPv(connectionId); Clients.Caller.send("denied");
if (!allow) { return ;
Clients.Caller.addPV(sender, "[private message was refused]"); }
return;
} }
var hubCxContext = Clients.User(connectionId);
var cli = Clients.Client(connectionId); var cli = Clients.Client(connectionId);
cli.addPV(sender, message); cli.addPV(Context.User.Identity.Name, message);
} }
private async Task<bool> AllowPv(string destConnectionId) private async Task<bool> AllowPv(string destConnectionId)

View File

@ -1,33 +1,31 @@
using System; using System;
using System.Security.Claims; using System.Security.Claims;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Util.Store;
using Microsoft.AspNet.Authentication; using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authentication.Cookies; using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.AspNet.Authentication.Facebook; using Microsoft.AspNet.Authentication.Facebook;
using Microsoft.AspNet.Authentication.Twitter;
using Microsoft.AspNet.Authentication.JwtBearer; using Microsoft.AspNet.Authentication.JwtBearer;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Authentication.Twitter;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel; using Microsoft.Extensions.OptionsModel;
using Microsoft.Extensions.WebEncoders; using Microsoft.Extensions.WebEncoders;
using OAuth.AspNet.AuthServer; using OAuth.AspNet.AuthServer;
using OAuth.AspNet.Tokens; using OAuth.AspNet.Tokens;
using Google.Apis.Util.Store;
using Microsoft.Extensions.Logging;
using Google.Apis.Auth.OAuth2.Responses;
namespace Yavsc namespace Yavsc {
{
using Auth; using Auth;
using Extensions; using Extensions;
using Models;
using Helpers.Google; using Helpers.Google;
using Models;
public partial class Startup public partial class Startup {
{
public static CookieAuthenticationOptions ExternalCookieAppOptions { get; private set; } public static CookieAuthenticationOptions ExternalCookieAppOptions { get; private set; }
public static IdentityOptions IdentityAppOptions { get; set; } public static IdentityOptions IdentityAppOptions { get; set; }
@ -36,194 +34,174 @@ namespace Yavsc
public static TwitterOptions TwitterAppOptions { get; private set; } public static TwitterOptions TwitterAppOptions { get; private set; }
public static OAuthAuthorizationServerOptions OAuthServerAppOptions { get; private set; } public static OAuthAuthorizationServerOptions OAuthServerAppOptions { get; private set; }
public static YavscGoogleOptions YavscGoogleAppOptions { get; private set; } public static YavscGoogleOptions YavscGoogleAppOptions { get; private set; }
public static MonoDataProtectionProvider ProtectionProvider { get; private set; } public static MonoDataProtectionProvider ProtectionProvider { get; private set; }
// public static CookieAuthenticationOptions BearerCookieOptions { get; private set; } // public static CookieAuthenticationOptions BearerCookieOptions { get; private set; }
private void ConfigureOAuthServices(IServiceCollection services) private void ConfigureOAuthServices (IServiceCollection services)
{ {
services.Configure<SharedAuthenticationOptions>(options => options.SignInScheme = Constants.ApplicationAuthenticationSheme); services.Configure<SharedAuthenticationOptions> (options => options.SignInScheme = Constants.ApplicationAuthenticationSheme);
services.Add(ServiceDescriptor.Singleton(typeof(IOptions<OAuth2AppSettings>), typeof(OptionsManager<OAuth2AppSettings>))); services.Add (ServiceDescriptor.Singleton (typeof (IOptions<OAuth2AppSettings>), typeof (OptionsManager<OAuth2AppSettings>)));
// used by the YavscGoogleOAuth middelware (TODO drop it) // used by the YavscGoogleOAuth middelware (TODO drop it)
services.AddTransient<Microsoft.Extensions.WebEncoders.UrlEncoder, UrlEncoder>(); services.AddTransient<Microsoft.Extensions.WebEncoders.UrlEncoder, UrlEncoder> ();
services.AddAuthentication(options => services.AddAuthentication (options => {
{
options.SignInScheme = Constants.ExternalAuthenticationSheme; options.SignInScheme = Constants.ExternalAuthenticationSheme;
}); });
ProtectionProvider = new MonoDataProtectionProvider(Configuration["Site:Title"]); ; ProtectionProvider = new MonoDataProtectionProvider (Configuration["Site:Title"]);;
services.AddInstance<MonoDataProtectionProvider> services.AddInstance<MonoDataProtectionProvider>
(ProtectionProvider); (ProtectionProvider);
services.AddIdentity<ApplicationUser, IdentityRole>( services.AddIdentity<ApplicationUser, IdentityRole> (
option => option => {
{ IdentityAppOptions = option;
IdentityAppOptions = option; option.User.AllowedUserNameCharacters += " ";
option.User.AllowedUserNameCharacters += " "; option.User.RequireUniqueEmail = true;
option.User.RequireUniqueEmail = true; // option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme;
// option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme; option.Cookies.ApplicationCookie.LoginPath = "/signin";
option.Cookies.ApplicationCookie.LoginPath = "/signin"; // option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
// option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme; /*
/* option.Cookies.ApplicationCookie.DataProtectionProvider = protector;
option.Cookies.ApplicationCookie.DataProtectionProvider = protector; option.Cookies.ApplicationCookie.LoginPath = new PathString(Constants.LoginPath.Substring(1));
option.Cookies.ApplicationCookie.LoginPath = new PathString(Constants.LoginPath.Substring(1)); option.Cookies.ApplicationCookie.AccessDeniedPath = new PathString(Constants.AccessDeniedPath.Substring(1));
option.Cookies.ApplicationCookie.AccessDeniedPath = new PathString(Constants.AccessDeniedPath.Substring(1)); option.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
option.Cookies.ApplicationCookie.AutomaticAuthenticate = true; option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme; option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme; option.Cookies.TwoFactorRememberMeCookie.ExpireTimeSpan = TimeSpan.FromDays(30);
option.Cookies.TwoFactorRememberMeCookie.ExpireTimeSpan = TimeSpan.FromDays(30); option.Cookies.TwoFactorRememberMeCookie.DataProtectionProvider = protector;
option.Cookies.TwoFactorRememberMeCookie.DataProtectionProvider = protector; option.Cookies.ExternalCookieAuthenticationScheme = Constants.ExternalAuthenticationSheme;
option.Cookies.ExternalCookieAuthenticationScheme = Constants.ExternalAuthenticationSheme; option.Cookies.ExternalCookie.AutomaticAuthenticate = true;
option.Cookies.ExternalCookie.AutomaticAuthenticate = true; option.Cookies.ExternalCookie.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
option.Cookies.ExternalCookie.AuthenticationScheme = Constants.ExternalAuthenticationSheme; option.Cookies.ExternalCookie.DataProtectionProvider = protector;
option.Cookies.ExternalCookie.DataProtectionProvider = protector; */
*/ }
} ).AddEntityFrameworkStores<ApplicationDbContext> ()
).AddEntityFrameworkStores<ApplicationDbContext>() .AddTokenProvider<EmailTokenProvider<ApplicationUser>> (Constants.DefaultFactor)
.AddTokenProvider<EmailTokenProvider<ApplicationUser>>(Constants.DefaultFactor) // .AddTokenProvider<UserTokenProvider>(Constants.DefaultFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.DefaultFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.SMSFactor) // .AddTokenProvider<UserTokenProvider>(Constants.SMSFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.EMailFactor) // .AddTokenProvider<UserTokenProvider>(Constants.EMailFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.AppFactor) // .AddTokenProvider<UserTokenProvider>(Constants.AppFactor)
// .AddDefaultTokenProviders() // .AddDefaultTokenProviders()
; ;
} }
private void ConfigureOAuthApp(IApplicationBuilder app, private void ConfigureOAuthApp (IApplicationBuilder app,
SiteSettings settingsOptions, ILogger logger) SiteSettings settingsOptions, ILogger logger) {
{
app.UseIdentity(); app.UseIdentity ();
app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), app.UseWhen (context => context.Request.Path.StartsWithSegments ("/api"),
branch => branch => {
{ branch.UseJwtBearerAuthentication (
branch.UseJwtBearerAuthentication( options => {
options => options.AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme;
{ options.AutomaticAuthenticate = true;
options.AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme; options.SecurityTokenValidators.Clear ();
options.AutomaticAuthenticate = true; options.SecurityTokenValidators.Add (new TicketDataFormatTokenValidator (
options.SecurityTokenValidators.Clear(); ProtectionProvider
options.SecurityTokenValidators.Add(new TicketDataFormatTokenValidator( ));
ProtectionProvider }
)); );
}
);
}); // External authentication shared cookie:
app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api"), branch.UseCookieAuthentication (options => {
branch => ExternalCookieAppOptions = options;
{ options.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
// External authentication shared cookie: options.AutomaticAuthenticate = true;
branch.UseCookieAuthentication(options => options.ExpireTimeSpan = TimeSpan.FromMinutes (5);
{ options.LoginPath = new PathString (Constants.LoginPath.Substring (1));
ExternalCookieAppOptions = options; // TODO implement an access denied page
options.AuthenticationScheme = Constants.ExternalAuthenticationSheme; options.AccessDeniedPath = new PathString (Constants.LoginPath.Substring (1));
options.AutomaticAuthenticate = true; });
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
options.LoginPath = new PathString(Constants.LoginPath.Substring(1));
// TODO implement an access denied page
options.AccessDeniedPath = new PathString(Constants.LoginPath.Substring(1));
});
YavscGoogleAppOptions = new YavscGoogleOptions {
ClientId = GoogleWebClientConfiguration["web:client_id"],
ClientSecret = GoogleWebClientConfiguration["web:client_secret"],
AccessType = "offline",
Scope = {
"profile",
"https://www.googleapis.com/auth/plus.login",
"https://www.googleapis.com/auth/admin.directory.resource.calendar",
"https://www.googleapis.com/auth/calendar",
"https://www.googleapis.com/auth/calendar.events"
},
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 dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext> ();
var store = serviceScope.ServiceProvider.GetService<IDataStore> ();
await store.StoreAsync (gcontext.GoogleUserId, new TokenResponse {
AccessToken = gcontext.TokenResponse.AccessToken,
RefreshToken = gcontext.TokenResponse.RefreshToken,
TokenType = gcontext.TokenResponse.TokenType,
ExpiresInSeconds = int.Parse (gcontext.TokenResponse.ExpiresIn),
IssuedUtc = DateTime.Now
});
await dbContext.StoreTokenAsync (gcontext.GoogleUserId,
gcontext.TokenResponse.Response,
gcontext.TokenResponse.AccessToken,
gcontext.TokenResponse.TokenType,
gcontext.TokenResponse.RefreshToken,
gcontext.TokenResponse.ExpiresIn);
YavscGoogleAppOptions = new YavscGoogleOptions }
{ }
ClientId = GoogleWebClientConfiguration ["web:client_id"], }
ClientSecret = GoogleWebClientConfiguration ["web:client_secret"], };
AccessType = "offline",
Scope = { "profile", "https://www.googleapis.com/auth/plus.login",
"https://www.googleapis.com/auth/admin.directory.resource.calendar",
"https://www.googleapis.com/auth/calendar",
"https://www.googleapis.com/auth/calendar.events"},
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 dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
var store = serviceScope.ServiceProvider.GetService<IDataStore>();
await store.StoreAsync(gcontext.GoogleUserId, new TokenResponse {
AccessToken = gcontext.TokenResponse.AccessToken,
RefreshToken = gcontext.TokenResponse.RefreshToken,
TokenType = gcontext.TokenResponse.TokenType,
ExpiresInSeconds = int.Parse(gcontext.TokenResponse.ExpiresIn),
IssuedUtc = DateTime.Now
});
await dbContext.StoreTokenAsync (gcontext.GoogleUserId,
gcontext.TokenResponse.Response,
gcontext.TokenResponse.AccessToken,
gcontext.TokenResponse.TokenType,
gcontext.TokenResponse.RefreshToken,
gcontext.TokenResponse.ExpiresIn);
}
}
}
};
branch.UseMiddleware<Yavsc.Auth.GoogleMiddleware>(YavscGoogleAppOptions);
/* FIXME 403
branch.UseTwitterAuthentication(options=>
{
TwitterAppOptions = options;
options.ConsumerKey = Configuration["Authentication:Twitter:ClientId"];
options.ConsumerSecret = Configuration["Authentication:Twitter:ClientSecret"];
}); */
branch.UseOAuthAuthorizationServer( branch.UseMiddleware<Yavsc.Auth.GoogleMiddleware> (YavscGoogleAppOptions);
/* FIXME 403
branch.UseTwitterAuthentication(options=>
{
TwitterAppOptions = options;
options.ConsumerKey = Configuration["Authentication:Twitter:ClientId"];
options.ConsumerSecret = Configuration["Authentication:Twitter:ClientSecret"];
}); */
options => branch.UseOAuthAuthorizationServer (
{
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.TokenDataProtector = ProtectionProvider.CreateProtector("Bearer protection");
options.Provider = new OAuthAuthorizationServerProvider options => {
{ OAuthServerAppOptions = options;
OnValidateClientRedirectUri = ValidateClientRedirectUri, options.AuthorizeEndpointPath = new PathString (Constants.AuthorizePath.Substring (1));
OnValidateClientAuthentication = ValidateClientAuthentication, options.TokenEndpointPath = new PathString (Constants.TokenPath.Substring (1));
OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials, options.ApplicationCanDisplayErrors = true;
OnGrantClientCredentials = GrantClientCredetails options.AllowInsecureHttp = true;
}; options.AuthenticationScheme = OAuthDefaults.AuthenticationType;
options.TokenDataProtector = ProtectionProvider.CreateProtector ("Bearer protection");
options.AuthorizationCodeProvider = new AuthenticationTokenProvider options.Provider = new OAuthAuthorizationServerProvider {
{ OnValidateClientRedirectUri = ValidateClientRedirectUri,
OnCreate = CreateAuthenticationCode, OnValidateClientAuthentication = ValidateClientAuthentication,
OnReceive = ReceiveAuthenticationCode, OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,
}; OnGrantClientCredentials = GrantClientCredetails
};
options.RefreshTokenProvider = new AuthenticationTokenProvider options.AuthorizationCodeProvider = new AuthenticationTokenProvider {
{ OnCreate = CreateAuthenticationCode,
OnCreate = CreateRefreshToken, OnReceive = ReceiveAuthenticationCode,
OnReceive = ReceiveRefreshToken, };
};
options.AutomaticAuthenticate = true; options.RefreshTokenProvider = new AuthenticationTokenProvider {
options.AutomaticChallenge = true; OnCreate = CreateRefreshToken,
} OnReceive = ReceiveRefreshToken,
); };
});
Environment.SetEnvironmentVariable ("GOOGLE_APPLICATION_CREDENTIALS", "google-secret.json"); options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
}
);
});
Environment.SetEnvironmentVariable ("GOOGLE_APPLICATION_CREDENTIALS", "google-secret.json");
} }
} }
} }

View File

@ -9,7 +9,7 @@ namespace Yavsc
SiteSettings siteSettings, IHostingEnvironment env) SiteSettings siteSettings, IHostingEnvironment env)
{ {
app.UseWebSockets(); app.UseWebSockets();
app.UseSignalR("/api/signalr"); app.UseSignalR(Constants.SignalRPath);
} }
} }
} }

View File

@ -392,14 +392,15 @@ namespace Yavsc
{ {
options.AuthenticationDescriptions.Clear(); options.AuthenticationDescriptions.Clear();
options.AutomaticAuthentication = false; options.AutomaticAuthentication = false;
}); });
app.UseSession();
ConfigureOAuthApp(app, SiteSetup, logger); ConfigureOAuthApp(app, SiteSetup, logger);
ConfigureFileServerApp(app, SiteSetup, env, authorizationService); ConfigureFileServerApp(app, SiteSetup, env, authorizationService);
ConfigureWebSocketsApp(app, SiteSetup, env); ConfigureWebSocketsApp(app, SiteSetup, env);
ConfigureWorkflow(app, SiteSetup, logger); ConfigureWorkflow(app, SiteSetup, logger);
app.UseRequestLocalization(localizationOptions.Value, (RequestCulture) new RequestCulture((string)"en-US")); app.UseRequestLocalization(localizationOptions.Value, (RequestCulture) new RequestCulture((string)"en-US"));
app.UseSession();
app.UseMvc(routes => app.UseMvc(routes =>
{ {

View File

@ -44,7 +44,7 @@
@section scripts { @section scripts {
<!--Reference the autogenerated SignalR hub script. --> <!--Reference the autogenerated SignalR hub script. -->
<script src="~/api/signalr/hubs"></script> <script src="~/api/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.--> <!-- SignalR script to update the chat page and send messages.-->
@if (!ViewBag.IsAuthenticated) { // Get the user name and store it to prepend to messages. @if (!ViewBag.IsAuthenticated) { // Get the user name and store it to prepend to messages.

View File

@ -90,8 +90,8 @@
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-*", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-*",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.Server.WebListener": "1.0.0-rc1-final", "Microsoft.AspNet.Server.WebListener": "1.0.0-rc1-final",
"Microsoft.AspNet.SignalR.Core": "2.3.0", "Microsoft.AspNet.SignalR.Core": "2.2.1",
"Microsoft.AspNet.SignalR.JS": "2.3.0", "Microsoft.AspNet.SignalR.JS": "2.2.1",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-*", "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-*",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-*", "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-*",
"Microsoft.AspNet.WebSockets.Server": "1.0.0-rc1-*", "Microsoft.AspNet.WebSockets.Server": "1.0.0-rc1-*",