示例#1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UserViewModel"/> class
        /// with a specific <see cref="SecurityUserInfo"/> instance.
        /// </summary>
        /// <param name="userEntity">The <see cref="UserEntity"/> instance.</param>
        /// <param name="securityUserInfo">The <see cref="SecurityUserInfo"/> instance.</param>
        public UserViewModel(UserEntity userEntity, SecurityUserInfo securityUserInfo) : base(securityUserInfo)
        {
            this.Email         = securityUserInfo.Email;
            this.HasRoles      = securityUserInfo.Roles?.Any() == true;
            this.IsLockedOut   = securityUserInfo.Lockout.GetValueOrDefault(false);
            this.LastLoginTime = securityUserInfo.User.LastLoginTime?.DateTime;
            this.Roles         = new List <RoleViewModel>();
            this.Username      = securityUserInfo.UserName;

            var given  = userEntity.Names.Where(n => n.NameUseKey == NameUseKeys.OfficialRecord).SelectMany(n => n.Component).Where(c => c.ComponentTypeKey == NameComponentKeys.Given).Select(c => c.Value).ToList();
            var family = userEntity.Names.Where(n => n.NameUseKey == NameUseKeys.OfficialRecord).SelectMany(n => n.Component).Where(c => c.ComponentTypeKey == NameComponentKeys.Family).Select(c => c.Value).ToList();

            this.Name = string.Join(" ", given) + " " + string.Join(" ", family);

            if (userEntity.LanguageCommunication.Any(l => l.IsPreferred))
            {
                var language = userEntity.LanguageCommunication.First(l => l.IsPreferred);

                this.Language = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(c => c.TwoLetterISOLanguageName == language.LanguageCode)?.DisplayName ?? language.LanguageCode;
            }

            if (userEntity.Telecoms.Any(t => t.AddressUseKey == TelecomAddressUseKeys.MobileContact))
            {
                this.PhoneNumber = userEntity.Telecoms.First(t => t.AddressUseKey == TelecomAddressUseKeys.MobileContact).Value;
            }
            else
            {
                this.PhoneNumber = userEntity.Telecoms.FirstOrDefault()?.Value;
            }

            if (this.HasRoles)
            {
                this.Roles = securityUserInfo.Roles.Select(r => new RoleViewModel(r));
            }
        }
示例#2
0
        public Object UpdateSecurityUser([RestMessage(RestMessageFormat.SimpleJson)] SecurityUserInfo user)
        {
            var localSecSrv = ApplicationContext.Current.GetService <IRepositoryService <SecurityUser> >();

            var amiServ = new AmiServiceClient(ApplicationContext.Current.GetRestClient("ami"));

            if (user.PasswordOnly)
            {
                var idp = ApplicationContext.Current.GetService <IIdentityProviderService>();
                idp.ChangePassword(user.Entity.UserName.ToLower(), user.Entity.Password, AuthenticationContext.Current.Principal);
                return(AuthenticationContext.Current.Session);
            }
            else
            {
                // Session
                amiServ.Client.Credentials = new TokenCredentials(AuthenticationContext.Current.Principal);
                var remoteUser = amiServ.GetUser(user.Entity.Key.Value);
                remoteUser.Entity.Email       = user.Entity.Email;
                remoteUser.Entity.PhoneNumber = user.Entity.PhoneNumber;
                // Save the remote user in the local
                localSecSrv.Save(remoteUser.Entity);
                amiServ.UpdateUser(remoteUser.Entity.Key.Value, remoteUser);
                return(remoteUser.Entity);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SubmitBugReportModel"/> class
 /// with a specific <see cref="SecurityUserInfo"/> instance.
 /// </summary>
 /// <param name="securityUserInfo">The <see cref="SecurityUserInfo"/> instance.</param>
 public SubmitBugReportModel(SecurityUserInfo securityUserInfo)
 {
     this.AttachBugInfo = true;
     this.Id            = securityUserInfo.UserId.Value;
     this.Reporter      = securityUserInfo.UserName;
     this.Success       = false;
 }
示例#4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UserViewModel"/> class
 /// with a specific <see cref="SecurityUserInfo"/> instance.
 /// </summary>
 /// <param name="securityUserInfo">The <see cref="SecurityUserInfo"/> instance.</param>
 public UserViewModel(SecurityUserInfo securityUserInfo) : base(securityUserInfo)
 {
     this.Email         = securityUserInfo.Email;
     this.HasRoles      = securityUserInfo.Roles?.Any() == true;
     this.IsLockedOut   = securityUserInfo.Lockout.HasValue && securityUserInfo.Lockout.Value;
     this.LastLoginTime = securityUserInfo.User.LastLoginTime?.DateTime;
     this.PhoneNumber   = securityUserInfo.User.PhoneNumber;
     this.Roles         = new List <RoleViewModel>();
     this.Username      = securityUserInfo.UserName;
 }
示例#5
0
        /// <summary>
        /// Updates a security user.
        /// </summary>
        /// <param name="userId">The id of the security user to be updated.</param>
        /// <param name="info">The security user containing the updated information.</param>
        /// <returns>Returns the updated security user.</returns>
        public SecurityUserInfo UpdateUser(string rawUserId, SecurityUserInfo info)
        {
            Guid userId = Guid.Parse(rawUserId);
            // First change password if needed
            var userRepository = ApplicationContext.Current.GetService <ISecurityRepositoryService>();
            var idpService     = ApplicationContext.Current.GetService <IIdentityProviderService>();

            if (!String.IsNullOrEmpty(info.Password))
            {
                var user = userRepository.ChangePassword(userId, info.Password);
                idpService.RemoveClaim(user.UserName, OpenIzClaimTypes.OpenIZPasswordlessAuth);
            }

            if (info.UserName == null)
            {
                info.UserName = userRepository.GetUser(userId)?.UserName;
            }

            if (info.User != null)
            {
                userRepository.SaveUser(info.User);
            }

            if (info.Lockout.HasValue)
            {
                if (info.Lockout.Value)
                {
                    userRepository.LockUser(userId);
                }
                else
                {
                    userRepository.UnlockUser(userId);
                }
            }

            // First, we remove the roles
            if (info.Roles != null && info.Roles.Any())
            {
                var irps = ApplicationContext.Current.GetService <IRoleProviderService>();

                var roles = irps.GetAllRoles(info.UserName);

                // if the roles provided are not equal to the current roles of the user, only then change the roles of the user
                if (roles != info.Roles.Select(r => r.Name).ToArray())
                {
                    irps.RemoveUsersFromRoles(new String[] { info.UserName }, info.Roles.Select(o => o.Name).ToArray(), AuthenticationContext.Current.Principal);
                    irps.AddUsersToRoles(new String[] { info.UserName }, info.Roles.Select(o => o.Name).ToArray(), AuthenticationContext.Current.Principal);
                }
            }

            return(info);
        }
示例#6
0
        /// <summary>
        /// Converts an <see cref="EditUserModel"/> instance to a <see cref="SecurityUserInfo"/> instance.
        /// </summary>
        /// <param name="userEntity">The <see cref="UserEntity"/> instance.</param>
        /// <returns>Returns a <see cref="SecurityUserInfo"/> instance.</returns>
        public SecurityUserInfo ToSecurityUserInfo(UserEntity userEntity)
        {
            var securityUserInfo = new SecurityUserInfo
            {
                Email  = this.Email,
                UserId = this.Id,
                User   = userEntity.SecurityUser
            };

            securityUserInfo.User.Email       = this.Email;
            securityUserInfo.User.PhoneNumber = this.PhoneNumber;

            return(securityUserInfo);
        }
示例#7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EditUserModel"/> class
 /// with a specific <see cref="UserEntity"/> instance and
 /// a specific <see cref="SecurityUserInfo"/> instance.
 /// </summary>
 /// <param name="userEntity">The <see cref="UserEntity"/> instance.</param>
 /// <param name="securityUserInfo">The <see cref="SecurityUserInfo"/> instance.</param>
 public EditUserModel(UserEntity userEntity, SecurityUserInfo securityUserInfo) : this()
 {
     this.CreationTime  = securityUserInfo.User.CreationTime.DateTime;
     this.Email         = securityUserInfo.User.Email;
     this.GivenName     = string.Join(", ", userEntity.Names.Where(n => n.NameUseKey == NameUseKeys.OfficialRecord).SelectMany(n => n.Component).Where(c => c.ComponentTypeKey == NameComponentKeys.Given).Select(c => c.Value).ToList());
     this.Id            = securityUserInfo.UserId.Value;
     this.Language      = userEntity.LanguageCommunication.FirstOrDefault(l => l.IsPreferred)?.LanguageCode;
     this.LockoutStatus = securityUserInfo.Lockout.GetValueOrDefault(false).ToLockoutStatus();
     this.IsObsolete    = securityUserInfo.User.ObsoletionTime.HasValue;
     this.Roles         = securityUserInfo.Roles.Select(r => r.Id.ToString()).ToList();
     this.Surname       = string.Join(", ", userEntity.Names.Where(n => n.NameUseKey == NameUseKeys.OfficialRecord).SelectMany(n => n.Component).Where(c => c.ComponentTypeKey == NameComponentKeys.Family).Select(c => c.Value).ToList());
     this.Username      = securityUserInfo.UserName;
     this.UserRoles     = securityUserInfo.Roles.Select(r => new RoleViewModel(r)).OrderBy(q => q.Name).ToList();
 }
示例#8
0
        public ActionResult Create(CreateDeviceModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var synchronizersRole = this.AmiClient.GetRoles(r => r.Name == "SYNCHRONIZERS").CollectionItem.FirstOrDefault();
                    var deviceRole        = this.AmiClient.GetRoles(r => r.Name == "DEVICE").CollectionItem.FirstOrDefault();

                    var device = this.AmiClient.CreateDevice(model.ToSecurityDeviceInfo());

                    var securityUserInfo = new SecurityUserInfo
                    {
                        Password = model.DeviceSecret,
                        Roles    = new List <SecurityRoleInfo>
                        {
                            deviceRole,
                            synchronizersRole
                        },
                        UserName = model.Name,
                        User     = new SecurityUser
                        {
                            Key          = Guid.NewGuid(),
                            UserClass    = UserClassKeys.ApplicationUser,
                            UserName     = model.Name,
                            SecurityHash = Guid.NewGuid().ToString()
                        },
                    };

                    this.AmiClient.CreateUser(securityUserInfo);

                    TempData["success"] = Locale.DeviceCreatedSuccessfully;

                    return(RedirectToAction("ViewDevice", new { id = device.Id }));
                }
            }
            catch (Exception e)
            {
                Trace.TraceError($"Unable to create device: {e}");
            }

            TempData["error"] = Locale.UnableToCreateDevice;

            return(View(model));
        }
示例#9
0
        public ActionResult ForgotPassword(ForgotPasswordModel model)
        {
            var amiServiceClient = GetDeviceServiceClient();

            var userId = Guid.Empty;

            var resetPasswordModel = new ResetPasswordModel
            {
                UserId = userId
            };

            try
            {
                amiServiceClient.SendTfaSecret(new TfaRequestInfo
                {
                    Purpose        = "PasswordReset",
                    ResetMechanism = model.TfaMechanism,
                    UserName       = model.Username,
                    Verification   = model.Verification
                });

                var user = this.AmiClient.GetUsers(u => u.UserName == model.Username && u.ObsoletionTime == null).CollectionItem.FirstOrDefault();

                // here, we don't care if the user is null, since throwing an error if the user in null
                // could indicate that the user doesn't exist to a potentially malicious user
                if (user == null)
                {
                    user = new SecurityUserInfo(new SecurityUser
                    {
                        Key = Guid.NewGuid()
                    });
                }

                resetPasswordModel.UserId = user.UserId.Value;

                this.TempData["success"] = Locale.ResetCodeSent;
            }
            catch (Exception e)
            {
                Trace.TraceError($"Unable to send TFA mechanism: {e}");
            }

            return(View("ResetPassword", resetPasswordModel));
        }
示例#10
0
        /// <summary>
        /// Add a new user to the role
        /// </summary>
        public object Add(Type scopingType, object scopingKey, object item)
        {
            var scope = this.m_roleRepository.Get((Guid)scopingKey);

            if (scope == null)
            {
                throw new KeyNotFoundException($"Could not find SecurityRole with identifier {scopingKey}");
            }

            try
            {
                this.m_pep.Demand(PermissionPolicyIdentifiers.AlterRoles);

                // Get user entity
                if (item is SecurityUser su)
                {
                    item = new SecurityUserInfo(su);
                }

                var rd = item as SecurityUserInfo;
                if (!rd.Entity.Key.HasValue)
                {
                    rd.Entity = this.m_securityRepository.GetUser(rd.Entity.UserName);
                }
                if (rd.Entity == null)
                {
                    throw new KeyNotFoundException($"Could not find specified user");
                }

                this.m_roleProvider.AddUsersToRoles(new string[] { rd.Entity.UserName }, new string[] { scope.Name }, AuthenticationContext.Current.Principal);
                AuditUtil.AuditSecurityAttributeAction(new object[] { scope }, true, $"add user={rd.Entity.UserName}");
                return(rd.Entity);
            }
            catch
            {
                AuditUtil.AuditSecurityAttributeAction(new object[] { scope }, false);
                throw;
            }
        }
示例#11
0
        /// <summary>
        /// Creates a security user.
        /// </summary>
        /// <param name="user">The security user to be created.</param>
        /// <returns>Returns the newly created security user.</returns>
        public SecurityUserInfo CreateUser(SecurityUserInfo user)
        {
            var userRepository      = ApplicationContext.Current.GetService <ISecurityRepositoryService>();
            var roleProviderService = ApplicationContext.Current.GetService <IRoleProviderService>();

            var userToCreate = new SecurityUser
            {
                Email    = user.Email,
                UserName = user.UserName,
            };

            if (user.User == null)
            {
                userToCreate.UserClass = UserClassKeys.HumanUser;
            }
            else
            {
                userToCreate.InvalidLoginAttempts = user.User.InvalidLoginAttempts;
                userToCreate.PhoneNumber          = user.User.PhoneNumber;
                userToCreate.UserClass            = user.User.UserClass == Guid.Empty ? UserClassKeys.HumanUser : user.User.UserClass;
            }

            if (user.Lockout.HasValue && user.Lockout.Value)
            {
                // to not overflow the date time value into 5 digit years
                userToCreate.Lockout = DateTime.MaxValue.AddYears(-100);
            }

            var securityUser = userRepository.CreateUser(userToCreate, user.Password);

            if (user.Roles?.Any() == true)
            {
                roleProviderService.AddUsersToRoles(new String[] { user.UserName }, user.Roles.Select(o => o.Name).ToArray(), AuthenticationContext.Current.Principal);
            }

            return(new SecurityUserInfo(securityUser));
        }
        public override object Create(object data, bool updateIfExists)
        {
            if (data is SecurityUser)
            {
                data = new SecurityUserInfo(data as SecurityUser);
            }
            var td = data as SecurityUserInfo;

            // Don't allow callers to overwrite expiration
            td.Entity.PasswordExpiration = null;
            // Insert the user
            var retVal = base.Create(data, updateIfExists) as SecurityUserInfo;

            // User information to roles
            if (td.Roles.Count > 0)
            {
                ApplicationServiceContext.Current.GetService <IRoleProviderService>().AddUsersToRoles(new string[] { retVal.Entity.UserName }, td.Roles.ToArray(), AuthenticationContext.Current.Principal);
            }

            return(new SecurityUserInfo(retVal.Entity)
            {
                Roles = td.Roles
            });
        }
        public override object Update(object data)
        {
            if (data is SecurityUser)
            {
                data = new SecurityUserInfo(data as SecurityUser);
            }

            var td = data as SecurityUserInfo;

            // Don't allow callers to overwrite expiration
            td.Entity.PasswordExpiration = null;

            // Update the user
            if (td.PasswordOnly)
            {
                // Validate that the user name matches the SID
                var user = ApplicationServiceContext.Current.GetService <IRepositoryService <SecurityUser> >().Get(td.Entity.Key.Value);
                // Check upstream?
                if (user != null && user.UserName?.ToLowerInvariant() != td.Entity.UserName.ToLowerInvariant())
                {
                    this.m_tracer.TraceError($"Username mismatch expect {user.UserName.ToLowerInvariant()} but got {td.Entity.UserName.ToLowerInvariant()}", 403);
                    throw new FaultException(403, this.m_localizationService.FormatString("error.rest.ami.mismatchUsername", new
                    {
                        param  = user.UserName.ToLowerInvariant(),
                        param2 = td.Entity.UserName.ToLowerInvariant()
                    }));
                }

                ApplicationServiceContext.Current.GetService <IIdentityProviderService>().ChangePassword(td.Entity.UserName, td.Entity.Password, AuthenticationContext.Current.Principal);

                if (user != null)
                {
                    this.FireSecurityAttributesChanged(user, true, "Password");
                }
                else
                {
                    this.FireSecurityAttributesChanged(td.Entity, true, "Password");
                }
                return(null);
            }
            else
            {
                // We're doing a general update, so we have to demand access
                ApplicationServiceContext.Current.GetService <IPolicyEnforcementService>().Demand(PermissionPolicyIdentifiers.LoginAsService);
                td.Entity.Password = null;

                //td.Entity.Roles = td.Roles.Select(o => new SecurityRole() { Name = o }).ToList();
                var retVal = base.Update(data) as SecurityUserInfo;

                // Roles? We want to update
                if (td.Roles != null && td.Roles.Count > 0)
                {
                    var irps = ApplicationServiceContext.Current.GetService <IRoleProviderService>();
                    irps.RemoveUsersFromRoles(new String[] { td.Entity.UserName }, irps.GetAllRoles().Where(o => !td.Roles.Contains(o)).ToArray(), AuthenticationContext.Current.Principal);
                    irps.AddUsersToRoles(new string[] { td.Entity.UserName }, td.Roles.ToArray(), AuthenticationContext.Current.Principal);
                    this.FireSecurityAttributesChanged(retVal.Entity, true, $"Roles = {String.Join(",", td.Roles)}");
                }

                return(new SecurityUserInfo(retVal.Entity)
                {
                    Roles = td.Roles
                });
            }
        }
示例#14
0
        /// <summary>
        /// Changes the users password.
        /// </summary>
        /// <param name="userName">The username of the user.</param>
        /// <param name="newPassword">The new password of the user.</param>
        /// <param name="principal">The authentication principal (the user that is changing the password).</param>
        public void ChangePassword(string userName, string newPassword, System.Security.Principal.IPrincipal principal)
        {
            try
            {
                // The principal must change their own password or must have the changepassword credential
                if (!userName.Equals(principal.Identity.Name, StringComparison.InvariantCultureIgnoreCase))
                {
                    new PolicyPermission(System.Security.Permissions.PermissionState.Unrestricted, PolicyIdentifiers.ChangePassword).Demand();
                }
                else if (!principal.Identity.IsAuthenticated)
                {
                    throw new InvalidOperationException("Unauthenticated principal cannot change user password");
                }

                // Get the user's identity
                var securityUserService = ApplicationContext.Current.GetService <ISecurityRepositoryService>();
                using (AmiServiceClient client = new AmiServiceClient(ApplicationContext.Current.GetRestClient("ami")))
                {
                    client.Client.Accept = "application/xml";

                    Guid userId = Guid.Empty;
                    if (principal is ClaimsPrincipal)
                    {
                        var subjectClaim = (principal as ClaimsPrincipal).FindClaim(ClaimTypes.Sid);
                        if (subjectClaim != null)
                        {
                            userId = Guid.Parse(subjectClaim.Value);
                        }
                    }

                    // User ID not found - lookup
                    if (userId == Guid.Empty)
                    {
                        // User service is null
                        var securityUser = securityUserService.GetUser(principal.Identity);
                        if (securityUser == null)
                        {
                            var tuser = client.GetUsers(o => o.UserName == principal.Identity.Name).CollectionItem.FirstOrDefault();
                            if (tuser == null)
                            {
                                throw new ArgumentException(string.Format("User {0} not found", userName));
                            }
                            else
                            {
                                userId = tuser.UserId.Value;
                            }
                        }
                        else
                        {
                            userId = securityUser.Key.Value;
                        }
                    }

                    // Use the current configuration's credential provider
                    var user = new SecurityUserInfo()
                    {
                        UserId   = userId,
                        UserName = userName,
                        Password = newPassword
                    };

                    // Set the credentials
                    client.Client.Credentials = ApplicationContext.Current.Configuration.GetServiceDescription("ami").Binding.Security.CredentialProvider.GetCredentials(principal);

                    client.UpdateUser(user.UserId.Value, user);
                    var localIdp = new LocalIdentityService();

                    // Change locally
                    localIdp.ChangePassword(userName, newPassword);

                    // Audit - Local IDP has alerted this already
                    if (!(localIdp is ISecurityAuditEventSource))
                    {
                        this.SecurityAttributesChanged?.Invoke(this, new SecurityAuditDataEventArgs(user, "password"));
                    }
                }
            }
            catch (Exception e)
            {
                this.m_tracer.TraceError("Error changing password for user {0} : {1}", userName, e);
                throw;
            }
        }
示例#15
0
 /// <summary>
 /// Creates the security user.
 /// </summary>
 /// <param name="userInfo">The user information.</param>
 /// <returns>Returns the created security user info.</returns>
 /// <exception cref="System.NotImplementedException"></exception>
 public SecurityUserInfo CreateSecurityUser(SecurityUserInfo userInfo)
 {
     throw new NotImplementedException();
 }
示例#16
0
 /// <summary>
 /// Updates a user.
 /// </summary>
 /// <param name="id">The id of the user to be updated.</param>
 /// <param name="user">The user containing the updated information.</param>
 /// <returns>Returns the updated user.</returns>
 public SecurityUserInfo UpdateUser(Guid id, SecurityUserInfo user)
 {
     return(this.Client.Put <SecurityUserInfo, SecurityUserInfo>($"SecurityUser/{id}", user));
 }
示例#17
0
        /// <summary>
        /// Changes the users password.
        /// </summary>
        /// <param name="userName">The username of the user.</param>
        /// <param name="newPassword">The new password of the user.</param>
        /// <param name="principal">The authentication principal (the user that is changing the password).</param>
        public void ChangePassword(string userName, string newPassword, System.Security.Principal.IPrincipal principal)
        {
            try
            {
                // The principal must change their own password or must have the changepassword credential
                if (!userName.Equals(principal.Identity.Name, StringComparison.InvariantCultureIgnoreCase))
                {
                    new PolicyPermission(System.Security.Permissions.PermissionState.Unrestricted, PermissionPolicyIdentifiers.ChangePassword).Demand();
                }
                else if (!principal.Identity.IsAuthenticated)
                {
                    throw new InvalidOperationException("Unauthenticated principal cannot change user password");
                }

                // Get the user's identity
                var securityUserService = ApplicationContext.Current.GetService <ISecurityRepositoryService>();
                var localIdp            = ApplicationContext.Current.GetService <IOfflineIdentityProviderService>();
                if (localIdp?.IsLocalUser(userName) == true) // User is a local user, so we only change password on local
                {
                    localIdp.ChangePassword(userName, newPassword, principal);
                }
                else
                {
                    using (AmiServiceClient client = new AmiServiceClient(ApplicationContext.Current.GetRestClient("ami")))
                    {
                        Guid userId = Guid.Empty;
                        if (principal.Identity.Name.ToLowerInvariant() == userName.ToLowerInvariant())
                        {
                            var subjectClaim = (principal as IClaimsPrincipal).FindFirst(SanteDBClaimTypes.Sid);
                            if (subjectClaim != null)
                            {
                                userId = Guid.Parse(subjectClaim.Value);
                            }
                        }

                        // User ID not found - lookup
                        if (userId == Guid.Empty)
                        {
                            // User service is null
                            var securityUser = securityUserService.GetUser(userName);
                            if (securityUser == null)
                            {
                                var tuser = client.GetUsers(o => o.UserName == userName).CollectionItem.OfType <SecurityUserInfo>().FirstOrDefault();
                                if (tuser == null)
                                {
                                    throw new ArgumentException(string.Format("User {0} not found", userName));
                                }
                                else
                                {
                                    userId = tuser.Entity.Key.Value;
                                }
                            }
                            else
                            {
                                userId = securityUser.Key.Value;
                            }
                        }

                        // Use the current configuration's credential provider
                        var user = new SecurityUserInfo(new SecurityUser()
                        {
                            Key      = userId,
                            UserName = userName,
                            Password = newPassword
                        })
                        {
                            PasswordOnly = true
                        };

                        // Set the credentials
                        client.Client.Credentials = ApplicationContext.Current.Configuration.GetServiceDescription("ami").Binding.Security.CredentialProvider.GetCredentials(principal);

                        client.UpdateUser(userId, user);

                        // Change locally
                        var userInfo = localIdp?.GetIdentity(userName);
                        if (userInfo != null)
                        {
                            localIdp?.ChangePassword(userName, newPassword, principal);
                        }

                        // Audit - Local IDP has alerted this already
                        AuditUtil.AuditSecurityAttributeAction(new object[] { user.ToIdentifiedData() }, true, new string[] { "password" });
                    }
                }
            }
            catch (Exception e)
            {
                this.m_tracer.TraceError("Error changing password for user {0} : {1}", userName, e);
                throw;
            }
        }
示例#18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UserViewModel"/> class
 /// with a specific <see cref="SecurityUserInfo"/> instance.
 /// </summary>
 /// <param name="securityUserInfo">The <see cref="SecurityUserInfo"/> instance.</param>
 protected SecurityViewModel(SecurityUserInfo securityUserInfo) : this(securityUserInfo.User, securityUserInfo.Roles)
 {
 }
示例#19
0
        public async Task <ActionResult> JoinRealmAsync(JoinRealmModel model)
        {
            HttpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            this.Response.Cookies.Remove("access_token");

            if (ModelState.IsValid)
            {
                model.Address = model.Address.HasTrailingBackSlash() ? model.Address.RemoveTrailingBackSlash() : model.Address;
                model.Address = model.Address.HasTrailingForwardSlash() ? model.Address.RemoveTrailingForwardSlash() : model.Address;

                Realm realm = unitOfWork.RealmRepository.Get(r => r.Address == model.Address && r.ObsoletionTime != null).AsEnumerable().SingleOrDefault();

                // remove any leading or trailing spaces
                model.Address = model.Address.Trim();

                // HACK: the UrlAttribute class thinks that http://localhost is not a valid url...
                if (model.Address.StartsWith("http://localhost"))
                {
                    model.Address = model.Address.Replace("http://localhost", "http://127.0.0.1");
                }
                else if (model.Address.StartsWith("https://localhost"))
                {
                    model.Address = model.Address.Replace("https://localhost", "https://127.0.0.1");
                }

                // is the user attempting to join a realm which they have already left?
                if (realm != null)
                {
                    realm.Map(model);
                    realm.ObsoletionTime = null;

                    unitOfWork.RealmRepository.Update(realm);
                    unitOfWork.Save();
                }
                else
                {
                    realm = unitOfWork.RealmRepository.Create();

                    realm.Map(model);
                    realm.DeviceId     = Environment.MachineName + "-" + Guid.NewGuid().ToString().ToUpper();
                    realm.DeviceSecret = Guid.NewGuid().ToString().ToUpper();

                    var activeRealms = unitOfWork.RealmRepository.AsQueryable().Where(r => r.ObsoletionTime == null).AsEnumerable();

                    foreach (var activeRealm in activeRealms)
                    {
                        activeRealm.ObsoletionTime = DateTime.UtcNow;
                        unitOfWork.RealmRepository.Update(activeRealm);
                    }

                    unitOfWork.RealmRepository.Add(realm);
                    unitOfWork.Save();
                }

                try
                {
                    var result = await this.SignInManager.PasswordSignInAsync(model.Username, model.Password, false, false);

                    switch (result)
                    {
                    case SignInStatus.Success:
                        using (var amiServiceClient = new AmiServiceClient(new RestClientService(Constants.Ami, this.HttpContext, this.SignInManager.AccessToken)))
                        {
                            var synchronizers = amiServiceClient.GetRoles(r => r.Name == "SYNCHRONIZERS").CollectionItem.FirstOrDefault();
                            var device        = amiServiceClient.GetRoles(r => r.Name == "DEVICE").CollectionItem.FirstOrDefault();

                            var securityUserInfo = new SecurityUserInfo
                            {
                                Password = realm.DeviceSecret,
                                Roles    = new List <SecurityRoleInfo>
                                {
                                    device,
                                    synchronizers
                                },
                                UserName = realm.DeviceId,
                                User     = new SecurityUser
                                {
                                    Key          = Guid.NewGuid(),
                                    UserClass    = UserClassKeys.ApplicationUser,
                                    UserName     = realm.DeviceId,
                                    SecurityHash = Guid.NewGuid().ToString()
                                },
                            };

                            amiServiceClient.CreateUser(securityUserInfo);

                            var securityDeviceInfo = new SecurityDeviceInfo
                            {
                                Device = new SecurityDevice
                                {
                                    DeviceSecret = realm.DeviceSecret,
                                    Name         = realm.DeviceId
                                }
                            };

                            amiServiceClient.CreateDevice(securityDeviceInfo);
                        }

                        MvcApplication.MemoryCache.Set(RealmConfig.RealmCacheKey, true, ObjectCache.InfiniteAbsoluteExpiration);
                        break;

                    default:
                        // always sign out the user when joining the realm
                        SignInManager.AuthenticationManager.SignOut();

                        var addedRealm = unitOfWork.RealmRepository.Get(r => r.Address == model.Address).FirstOrDefault();

                        if (addedRealm != null)
                        {
                            unitOfWork.RealmRepository.Delete(addedRealm.Id);
                            unitOfWork.Save();
                        }

                        ModelState.AddModelError("", Locale.IncorrectUsernameOrPassword);

                        return(View(model));
                    }

                    this.TempData["success"] = Locale.RealmJoinedSuccessfully;

                    return(RedirectToAction("Login", "Account"));
                }
                catch (Exception e)
                {
                    Trace.TraceError($"Unable to join realm: {e}");

                    var addedRealm = unitOfWork.RealmRepository.Get(r => r.Address == model.Address).Single();
                    unitOfWork.RealmRepository.Delete(addedRealm.Id);
                    unitOfWork.Save();
                }
                finally
                {
                    // always sign out the user when joining the realm
                    HttpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                }
            }

            TempData["error"] = Locale.UnableToJoinRealm;

            return(View(model));
        }
示例#20
0
 /// <summary>
 /// Creates a user in the IMS.
 /// </summary>
 /// <param name="user">The user to be created.</param>
 /// <returns>Returns the newly created user.</returns>
 public SecurityUserInfo CreateUser(SecurityUserInfo user)
 {
     return(this.Client.Post <SecurityUserInfo, SecurityUserInfo>("SecurityUser", user));
 }