Ejemplo n.º 1
0
        public async Task<IHttpActionResult> ExternalSignin(SigninExternalTokenBindingModel model)
        {

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            ExternalLoginData externalLogin = await ExternalLoginData.FromToken(model.Provider, model.Token);

            if (externalLogin == null)
            {
                return InternalServerError();
            }

            if (externalLogin.LoginProvider != model.Provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return InternalServerError();
            }

            ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                externalLogin.ProviderKey));

            bool hasRegistered = user != null;
            ClaimsIdentity identity = null;

            if (hasRegistered)
            {
                if (!user.IsActiveUser)
                {
                    var response = new HttpResponseMessage(HttpStatusCode.Forbidden);

                    response.ReasonPhrase = user.Id;
                    return ResponseMessage(response);
                }

                //var hub = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
                //hub.Clients.All.logout(user.Email);

                //var loggedInUsers = NotificationHub._connections.GetConnections(user.Email);
                //if (loggedInUsers.Count() > 0)
                //{
                //    var hub = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
                //    foreach (var connectionId in loggedInUsers)
                //    {
                //        hub.Clients.Client(connectionId).logout();
                //    }
                //}

                identity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);
                IEnumerable<Claim> claims = externalLogin.GetClaims();
                identity.AddClaims(claims);
                Authentication.SignIn(identity);
            }
            else
            {
                return NotFound();
            }

            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
            ticket.Properties.IssuedUtc = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(365));
            var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
            Request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);



            // Create the response building a JSON object that mimics exactly the one issued by the default /Token endpoint
            JObject token = new JObject(
                new JProperty("userName", user.UserName),
                new JProperty("isFreeUser", user.IsFreeUser),
                new JProperty("id", user.Id),
                new JProperty("fullName", user.FullName),
                new JProperty("access_token", accessToken),
                new JProperty("token_type", "bearer"),
                new JProperty("showDownloadOption", (user.SubscriptionId == 1)),
                new JProperty("expires_in", TimeSpan.FromDays(365).TotalSeconds.ToString()),
                new JProperty(".issued", currentUtc.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'")),
                new JProperty(".expires", currentUtc.Add(TimeSpan.FromDays(365)).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"))
            );

            //_Uow._LoggedInTracking.Add(new EF.LoggedInTracking
            //{
            //    DateTimeLoggedIn = DateTime.UtcNow,
            //    Token = accessToken,
            //    UserId = user.Id
            //});
            //await _Uow.CommitAsync();

            return Ok(token);
        }
Ejemplo n.º 2
0
        public async Task<IHttpActionResult> RegisterExternalToken(RegisterExternalTokenBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            ExternalLoginData externalLogin = await ExternalLoginData.FromToken(model.Provider, model.Token);

            if (externalLogin == null)
            {
                return InternalServerError();
            }

            if (externalLogin.LoginProvider != model.Provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return InternalServerError();
            }

            ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                externalLogin.ProviderKey));

            bool hasRegistered = user != null;
            ClaimsIdentity identity = null;
            IdentityResult result;

            if (hasRegistered)
            {
                identity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);
                IEnumerable<Claim> claims = externalLogin.GetClaims();
                identity.AddClaims(claims);
                Authentication.SignIn(identity);
                if (user.IsActiveUser)
                {
                    AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                    var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
                    ticket.Properties.IssuedUtc = currentUtc;
                    ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(365));
                    var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
                    Request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);



                    // Create the response building a JSON object that mimics exactly the one issued by the default /Token endpoint
                    JObject token = new JObject(
                        new JProperty("userName", user.UserName),
                        new JProperty("isFreeUser", user.IsFreeUser),
                        new JProperty("id", user.Id),
                        new JProperty("fullName", user.FullName),
                        new JProperty("access_token", accessToken),
                        new JProperty("token_type", "bearer"),
                        new JProperty("showDownloadOption", (user.SubscriptionId == 1)),
                        new JProperty("expires_in", TimeSpan.FromDays(365).TotalSeconds.ToString()),
                        new JProperty(".issued", currentUtc.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'")),
                        new JProperty(".expires", currentUtc.Add(TimeSpan.FromDays(365)).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"))
                    );

                    //_Uow._LoggedInTracking.Add(new EF.LoggedInTracking
                    //{
                    //    DateTimeLoggedIn = DateTime.UtcNow,
                    //    Token = accessToken,
                    //    UserId = user.Id
                    //});
                    //await _Uow.CommitAsync();

                    return Ok(user.Id);
                }
            }
            else
            {
                var subscription = await _Uow._Subscription.GetByIdAsync(2);
                user = new ApplicationUser()
                {
                    Id = Guid.NewGuid().ToString(),
                    UserName = model.Email,
                    Email = model.Email,
                    FullName = model.FullName,
                    CountryId = model.CountryId,
                    CreatedOn = DateTime.UtcNow,
                    CurrentViews = 0,
                    IsActiveUser = true,
                    IsAllowMobileVideos = true,
                    IsFilterByIP = false,
                    IsParentalControl = false,
                    IsPasswordReset = false,
                    NoOfConcurentViews = 1,
                    SubscriptionDate = DateTime.UtcNow,
                    SubscriptionId = 2,
                    ExpirationDate = DateTime.UtcNow.AddDays(subscription.TimeDuration.GetValueOrDefault()),
                    Active = true,
                    IsFreeUser = true,
                    IsInstitutionalAccount = false,
                };

                result = await UserManager.CreateAsync(user);
                if (!result.Succeeded)
                {
                    return GetErrorResult(result);
                }

                var info = new ExternalLoginInfo()
                {
                    DefaultUserName = model.Email,
                    Login = new UserLoginInfo(model.Provider, externalLogin.ProviderKey)
                };

                result = await UserManager.AddLoginAsync(user.Id, info.Login);
                if (!result.Succeeded)
                {
                    return GetErrorResult(result);
                }

                identity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);
                IEnumerable<Claim> claims = externalLogin.GetClaims();
                identity.AddClaims(claims);
                //Authentication.SignIn(identity);
            }

            //AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            //var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
            //ticket.Properties.IssuedUtc = currentUtc;
            //ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(365));
            //var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
            //Request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);



            //// Create the response building a JSON object that mimics exactly the one issued by the default /Token endpoint
            //JObject token = new JObject(
            //    new JProperty("userName", user.UserName),
            //    new JProperty("id", user.Id),
            //    new JProperty("fullName", user.FullName),
            //    new JProperty("access_token", accessToken),
            //    new JProperty("token_type", "bearer"),
            //    new JProperty("expires_in", TimeSpan.FromDays(365).TotalSeconds.ToString()),
            //    new JProperty(".issued", currentUtc.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'")),
            //    new JProperty(".expires", currentUtc.Add(TimeSpan.FromDays(365)).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"))
            //);
            return Ok(user.Id);
        }