private string GenerateToken(AspnetMembership aspnetMembership)
        {
            //header
            var symetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Authentication:Secretkey"]));

            var signingCredencials = new SigningCredentials(symetricSecurityKey, SecurityAlgorithms.HmacSha256);
            var header             = new JwtHeader(signingCredencials);

            //claims

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, aspnetMembership.User.ToString()),
                new Claim(ClaimTypes.Email, aspnetMembership.Email),
                new Claim(ClaimTypes.Role, aspnetMembership.UserId.ToString()),
            };
            var payload = new JwtPayload
                          (
                _configuration["Authentication:Issuer"],
                _configuration["Authentication:Audience"],
                claims,
                DateTime.Now,
                DateTime.UtcNow.AddMinutes(10)

                          );

            //sign

            var token = new JwtSecurityToken(header, payload);

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
        //return a struct that contains {appUserEntity,password,passwordSalt,and password Question}  by username

        public UserInfoCorrectPassword GetMembershipEntity(string username)
        {
            // find the app user first since it will need to be returned to the frontend after login
            AppUserRepository appUserRepository = new AppUserRepository(checkNetDbContext);
            AppUserEntity     appUserEntity     = appUserRepository.GetAppUser(username);

            // if user not found
            if (appUserEntity == null)
            {
                return(new UserInfoCorrectPassword {
                });
            }

            AspnetMembership membershipModel = checkNetDbContext.AspnetMembership.Where(u => u.UserId == appUserEntity.UserId).FirstOrDefault();

            /*MembershipEntity membershipEntity = MembershipFactory.Create(membershipModel.ApplicationId, membershipModel.UserId
             *  , membershipModel.Password, membershipModel.PasswordSalt
             *  , membershipModel.Email, membershipModel.PasswordQuestion, membershipModel.PasswordAnswer
             *  , membershipModel.CreateDate, membershipModel.LastLoginDate, membershipModel.Comment);*/

            //AppUserRepository appUserRepository = new AppUserRepository(checkNetDbContext);


            var results = new UserInfoCorrectPassword {
                appuser          = appUserEntity,
                password         = membershipModel.Password,
                passwordSalt     = membershipModel.PasswordSalt,
                passwordQuestion = membershipModel.PasswordQuestion
            };

            return(results);
        }
        //return membership records by id
        public MembershipEntity GetMembershipEntity(Guid UserId)
        {
            AspnetMembership MembershipModel   = checkNetDbContext.AspnetMembership.Find(UserId);
            MembershipEntity MembershiprEntity = MembershipFactory.Create(MembershipModel.ApplicationId, MembershipModel.UserId, MembershipModel.Password, MembershipModel.PasswordSalt, MembershipModel.Email
                                                                          , MembershipModel.PasswordQuestion, MembershipModel.PasswordAnswer, MembershipModel.CreateDate, MembershipModel.LastLoginDate, MembershipModel.Comment);

            return(MembershiprEntity);
        }
Esempio n. 4
0
        public async Task <IdentityResult> CreateAsync(ApplicationUser user, CancellationToken cancellationToken)
        {
            Guid applicationId;
            var  tnx = await db.Database.BeginTransactionAsync(IsolationLevel.Serializable, cancellationToken);

            var application = await db.AspnetApplications.SingleOrDefaultAsync(c => c.ApplicationName == applicationName, cancellationToken);

            if (application == null)
            {
                applicationId = Guid.NewGuid();
                var newApplication = new AspnetApplications
                {
                    ApplicationId          = applicationId,
                    ApplicationName        = applicationName,
                    LoweredApplicationName = applicationName?.ToLowerInvariant(),
                };
                await db.AspnetApplications.AddAsync(newApplication, cancellationToken);
            }
            else
            {
                applicationId = application.ApplicationId;
            }
            Guid userId  = Guid.NewGuid();
            var  newUser = new AspnetUsers
            {
                ApplicationId    = applicationId,
                UserId           = userId,
                UserName         = user.UserName,
                LoweredUserName  = user.NormalizedUserName,
                IsAnonymous      = false,
                LastActivityDate = user.LastActivityDate,
            };
            await db.AspnetUsers.AddAsync(newUser, cancellationToken);

            var newMembership = new AspnetMembership
            {
                ApplicationId           = applicationId,
                UserId                  = userId,
                Password                = user.PasswordHash,
                PasswordSalt            = utility.GenerateSalt(),
                Email                   = user.Email,
                LoweredEmail            = user.Email?.ToLowerInvariant(),
                PasswordQuestion        = user.PasswordQuestion,
                IsApproved              = user.IsApproved,
                IsLockedOut             = user.IsLockedOut,
                CreateDate              = user.CreationDate,
                LastLoginDate           = user.LastLoginDate,
                LastPasswordChangedDate = user.LastPasswordChangedDate,
                LastLockoutDate         = user.LastLockoutDate,
            };
            await db.AspnetMembership.AddAsync(newMembership, cancellationToken);

            await db.SaveChangesAsync(cancellationToken);

            tnx.Commit();
            return(IdentityResult.Success);
        }
Esempio n. 5
0
 public static UserModel ToViewModel(this AspnetMembership user)
 {
     return(new UserModel()
     {
         UserId = user.UserId,
         Password = user.Password,
         Email = user.Email,
         IsApproved = user.IsApproved,
         IsLockedOut = user.IsLockedOut,
         CreateDate = user.CreateDate,
         LastLoginDate = user.LastLoginDate
     });
 }
Esempio n. 6
0
        private bool DoActivate(string username, string activationCode, bool manualLogin)
        {
            bool userCreated = false;

            MembershipUser membershipUser = Membership.GetUser(username, false);

            if (membershipUser != null)
            {
                string           userId     = membershipUser.ProviderUserKey.ToString();
                AspnetMembership membership = AspnetMembership.FetchByID(new Guid(userId));

                if (membership.PasswordQuestion == activationCode || (manualLogin && ConfigurationManager.AppSettings["PromoActivationCode"].ToLower().Trim() == activationCode.ToLower().Trim()))
                {
                    membership.PasswordQuestion = "-";
                    membership.Save();
                    Roles.RemoveUserFromRole(username, "NotActivated");
                    Roles.AddUserToRole(username, "Basic");
                    DataObjectUser.CreateUser(UserDataContext.GetUserDataContext(), username);
                    UserProfile userProfile = UserProfile.GetProfile(username);
                    if (userProfile == null)
                    {
                        userProfile          = (UserProfile)UserProfile.Create(username);
                        userProfile.UserId   = new Guid(membershipUser.ProviderUserKey.ToString());
                        userProfile.Nickname = username;
                    }
                    Community.CreateUserProfileCommunity(UserDataContext.GetUserDataContext(), userProfile);
                    DataObjectUser.JoinCommunities(userId, _4screen.CSB.Common.SiteConfig.GetSiteContext(UserProfile.Current));
                    DataObjectUser.AddDefaultFriends(userId);
                    _4screen.CSB.Extensions.Business.IncentivePointsManager.AddIncentivePointEvent("USER_ACTIVATE", UserDataContext.GetUserDataContext());
                    SetProfileDefaults(new Guid(userId));
                    userCreated = true;
                }
                else if (membership.PasswordQuestion != activationCode)
                {
                    lblInfo.Text       += language.GetString("MessageActivatCodeInvalid");
                    pnlError.Visible    = true;
                    pnlActivate.Visible = false;
                }
            }
            else
            {
                lblInfo.Text       += language.GetString("MessageActivatUserInvalid");
                pnlError.Visible    = true;
                pnlActivate.Visible = false;
            }

            return(userCreated);
        }
        public async Task <IActionResult> Token(string username, string password)
        {
            // Obviously the username and password parameters have to be provided or
            // there is nothing to validate.
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                OpResult <AspnetMembership> authenticatedUserResult = await securityManager.AuthenticateUserAsync(username, password);

                if (authenticatedUserResult.Code == OperationResultCode.Success)
                {
                    AspnetMembership authenticatedUser = authenticatedUserResult.Result;

                    ClaimsIdentity userClaimsIdentity = new ClaimsIdentity(new GenericIdentity(authenticatedUser.UserId.ToString(), "Token"));
                    UserModel      userModel          = authenticatedUser.ToViewModel();
                    userClaimsIdentity.AddClaims(userModel.ToClaims());
                    //LoadClientIdForClients(userModel, authenticatedUser);
                    return(GenerateToken(userClaimsIdentity));
                }
            }

            // Credentials are invalid, or account doesn't exist
            return(BadRequest("Refresh token must be provided & valid."));
        }
        public virtual async Task <OpResult <AspnetMembership> > AuthenticateUserAsync(string userName, string password)
        {
            OpResult <AspnetMembership> result = new OpResult <AspnetMembership>()
            {
                Code = OperationResultCode.Error
            };

            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
            {
                AspnetMembership user = await _userDbSet.FirstOrDefaultAsync(x => x.Email == userName);

                if (user != null)
                {
                    result.Code   = OperationResultCode.Success;
                    result.Result = user;

                    return(result);
                }

                result.Message = "Oops!  We were unable to find an active account with " +
                                 "that email & password combination.";
            }
            return(result);
        }
        public async Task RegisterUser(AspnetMembership membership)
        {
            await _unitOfWork.AspnetMembershipRepository.Add(membership);

            await _unitOfWork.SaveChangesAsync();
        }
        public void Insert(Guid ApplicationId,Guid UserId,string Password,int PasswordFormat,string PasswordSalt,string MobilePIN,string Email,string LoweredEmail,string PasswordQuestion,string PasswordAnswer,bool IsApproved,bool IsLockedOut,DateTime CreateDate,DateTime LastLoginDate,DateTime LastPasswordChangedDate,DateTime LastLockoutDate,int FailedPasswordAttemptCount,DateTime FailedPasswordAttemptWindowStart,int FailedPasswordAnswerAttemptCount,DateTime FailedPasswordAnswerAttemptWindowStart,string Comment)
        {
            AspnetMembership item = new AspnetMembership();

            item.ApplicationId = ApplicationId;

            item.UserId = UserId;

            item.Password = Password;

            item.PasswordFormat = PasswordFormat;

            item.PasswordSalt = PasswordSalt;

            item.MobilePIN = MobilePIN;

            item.Email = Email;

            item.LoweredEmail = LoweredEmail;

            item.PasswordQuestion = PasswordQuestion;

            item.PasswordAnswer = PasswordAnswer;

            item.IsApproved = IsApproved;

            item.IsLockedOut = IsLockedOut;

            item.CreateDate = CreateDate;

            item.LastLoginDate = LastLoginDate;

            item.LastPasswordChangedDate = LastPasswordChangedDate;

            item.LastLockoutDate = LastLockoutDate;

            item.FailedPasswordAttemptCount = FailedPasswordAttemptCount;

            item.FailedPasswordAttemptWindowStart = FailedPasswordAttemptWindowStart;

            item.FailedPasswordAnswerAttemptCount = FailedPasswordAnswerAttemptCount;

            item.FailedPasswordAnswerAttemptWindowStart = FailedPasswordAnswerAttemptWindowStart;

            item.Comment = Comment;

            item.Save(UserName);
        }
Esempio n. 11
0
 public void Update(AspnetMembership obj)
 {
     dao.Update(obj);
 }
Esempio n. 12
0
 public void Update(AspnetMembership obj)
 {
     HibernateTemplate.SaveOrUpdate(obj);
 }