コード例 #1
0
        public async Task <ActionResult> IpLogin(UserModel model)
        {
            TokenData tokenData;

            // Try to get ws federation claims
            SocialIdentity socialIdentity;
            ClaimsIdentity claimsIdentity;
            var            claims = new Dictionary <string, string>();

            if ((socialIdentity = User.Identity as SocialIdentity) != null && socialIdentity.IsAuthenticated)
            {
                // Ws federation authentication for already signed in user
                claims = socialIdentity.SocialClaims.ToDictionary(claim => claim.Type, claim => claim.Value);
            }
            else if ((claimsIdentity = User.Identity as ClaimsIdentity) != null && claimsIdentity.IsAuthenticated)
            {
                // Ws federation authentication
                claims = claimsIdentity.Claims.ToDictionary(claim => claim.Type, claim => claim.Value);
            }

            // Try to extract token data from claims
            if (claims.Count > 0)
            {
                ITokenDataExtractor tokenDataExtractor = _tokenDataExtractorFactory.CreateTokenDataExtractor(TokenType.Claims);
                tokenData = tokenDataExtractor.Get(new IpData {
                    Token = JsonConvert.SerializeObject(claims)
                });

                FederatedAuthentication.WSFederationAuthenticationModule.SignOut(true);
            }
            else if (model != null && !string.IsNullOrEmpty(model.UserIdentifier))
            {
                if (!ModelState.IsValid)
                {
                    return(View(model));
                }

                // Registration form data
                tokenData = model;
            }
            else
            {
                // Failure while authentication
                return(View("_IpAccessDeclined"));
            }

            DomainUser user        = null;
            DomainUser currentUser = null;

            try
            {
                user = await GetUserByToken(tokenData);
            }
            catch (ForbiddenException)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden));
            }

            currentUser = await GetCurrentUser();

            try
            {
                if (currentUser != null)
                {
                    if (user == null)
                    {
                        await _userService.AddMembersipAsync(currentUser.Id, tokenData);

                        user = await GetUserByEmail(tokenData);

                        if (user != null && user.Id != currentUser.Id)
                        {
                            await _userService.MergeFromAsync(user.Id, currentUser.Id);
                        }
                        else
                        {
                            if (String.IsNullOrEmpty(currentUser.Email) && !String.IsNullOrEmpty(tokenData.Email))
                            {
                                await _userService.ChangeEmailAsync(UserId, tokenData.Email);
                            }
                        }
                    }
                    else
                    {
                        if (user.Id != currentUser.Id)
                        {
                            await _userService.MergeFromAsync(user.Id, currentUser.Id);
                        }
                    }
                    // Set cookies
                    await _authenticationService.SetUserAsync(currentUser, tokenData);
                }
                else
                {
                    if (user == null)
                    {
                        user = await GetUserByEmail(tokenData);

                        if (user != null)
                        {
                            await _userService.AddMembersipAsync(user.Id, tokenData);
                        }
                        else
                        {
                            user = await CompleteRegistrationAsync(tokenData);
                        }
                    }

                    // Set cookies if not authenticated
                    await _authenticationService.SetUserAsync(user, tokenData);
                }
            }
            catch (Exception e)
            {
                Trace.TraceError("Failed IpLogin '{0}:{1}': {2}", tokenData.IdentityProvider, tokenData.UserIdentifier, e);
                return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
            }

            // For statistics
            HttpContext.Items.Add("isLogin", true);

            // Return user to the authentication page
            if (Request.Cookies.AllKeys.Contains(ReturnUrl))
            {
                string returnUrl = HttpUtility.UrlDecode(Request.Cookies[ReturnUrl].Value);

                // Remove cookie
                Response.Cookies.Add(new HttpCookie(ReturnUrl)
                {
                    Expires = DateTime.Now.AddDays(-1d)
                });

                // Redirect to requested url
                if (!string.IsNullOrEmpty(returnUrl) && returnUrl.StartsWith("/"))
                {
                    return(Redirect(returnUrl));
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
コード例 #2
0
        public async Task <HttpResponseMessage> Post(SessionIpModel model)
        {
            ITokenDataExtractor tokenDataExtractor = _tokenDataExtractorFactory.CreateTokenDataExtractor(model.Type);

            TokenData tokenData;

            try
            {
                tokenData = tokenDataExtractor.Get(model);
            }
            catch (BadRequestException)
            {
                ModelState.AddModelError("Token", ResponseMessages.AccountsInvalidToken);
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            // Return result
            DomainUser user = null;

            try
            {
                user = await _userService.FindByIdentityAsync(tokenData.IdentityProvider, tokenData.UserIdentifier);
            }
            catch (NotFoundException)
            {
            }

            // Try to find user by email
            if (user == null && !string.IsNullOrEmpty(tokenData.Email))
            {
                try
                {
                    user = await _userService.FindByEmailAsync(tokenData.Email);
                }
                catch (NotFoundException)
                {
                }

                // Add ip memebership to user
                if (user != null)
                {
                    await _userService.AddMembersipAsync(user.Id, tokenData);
                }
            }

            var httpStatusCode = HttpStatusCode.OK;

            // Check whether registration is required
            if (user == null)
            {
                var profileData = new DomainUser
                {
                    ApplicationName = AppName,
                    Name            = tokenData.Name,
                    Email           = tokenData.Email,
                    UserAgent       = _productIdExtractor.Get(UserAgent),
                    Roles           = new List <string> {
                        DomainRoles.User
                    },
                    Memberships = new List <UserMembership>
                    {
                        new UserMembership
                        {
                            IdentityProvider = tokenData.IdentityProvider,
                            UserIdentifier   = tokenData.UserIdentifier,
                        }
                    }
                };

                user = await _userService.AddAsync(profileData);

                // Send registration e-mail
                try
                {
                    await _emailNotificationService.SendRegistrationEmailAsync(user);
                }
                catch (Exception e)
                {
                    Trace.TraceError("Failed to send registration email to address {0} for user {1}: {2}", user.Email, user.Id, e);
                }

                // Send notification into social network
                ISocialNetworkNotifier notifier = _notificationFactory.GetNotifier(tokenData.IdentityProvider);
                if (notifier != null)
                {
                    try
                    {
                        await notifier.SendWelcomeMessageAsync(user, tokenData);
                    }
                    catch (BadGatewayException)
                    {
                    }
                    catch (Exception e)
                    {
                        Trace.TraceError("Failed to send welcome message to user {0}: {1}", user.Id, e);
                    }
                }

                httpStatusCode = HttpStatusCode.Created;
            }

            var token = await _authenticationService.SetUserAsync(user, tokenData, true);

            return(Request.CreateResponse(httpStatusCode, new AuthenticationTokenModel {
                Token = token
            }));
        }